-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathterrain_viewer.html
More file actions
627 lines (555 loc) · 21.1 KB
/
terrain_viewer.html
File metadata and controls
627 lines (555 loc) · 21.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Manual Tile Viewer</title>
<style>
html,
body {
height: 100%;
margin: 0;
padding: 0;
overflow: hidden; /* Prevent body scrollbars */
font-family: sans-serif;
background-color: #eee; /* Background for area outside map */
}
#map-container {
position: relative; /* Context for absolute positioning inside */
width: 100%;
height: 100%;
overflow: hidden; /* Crucial: Clips the tile-grid */
cursor: grab; /* Indicate draggable */
background-color: #ccc; /* Fallback if tiles don't load */
}
#map-container.dragging {
cursor: grabbing;
}
#tile-grid {
position: absolute;
top: 0;
left: 0;
width: 1px; /* Will be effectively infinite */
height: 1px;
will-change: transform; /* Hint for performance */
user-select: none; /* Prevent text selection during drag */
-webkit-user-select: none;
-ms-user-select: none;
transform: translate3d(0, 0, 0); /* Force GPU acceleration */
}
.tile-image {
position: absolute;
width: 256px; /* Standard tile size */
height: 256px;
user-select: none; /* Prevent image selection */
-webkit-user-select: none;
-ms-user-select: none;
pointer-events: none; /* Prevent image interference with dragging */
background-color: #0a1a33; /* Slightly lighter shade of the main color */
backface-visibility: hidden; /* Performance boost */
border: 0.1px solid rgba(255, 255, 255, 0.8); /* Add white border with transparency */
box-sizing: border-box; /* Make sure border is included in the width/height */
}
.tile-coords {
position: absolute;
top: 2px;
right: 2px;
color: #f7c1cc;
font-size: 12px;
font-weight: bold;
padding: 1px 3px;
border-radius: 2px;
pointer-events: none;
z-index: 1; /* Above tile image */
white-space: nowrap;
}
/* Custom zoom controls (same as before) */
.custom-zoom {
position: absolute;
top: 10px;
left: 10px;
z-index: 1000;
background: white;
border: 1px solid #ccc;
border-radius: 4px;
box-shadow: 0 1px 5px rgba(0, 0, 0, 0.65);
}
.custom-zoom button {
display: block;
width: 30px;
height: 30px;
font-size: 18px;
font-weight: bold;
border: none;
background-color: white;
cursor: pointer;
line-height: 30px;
text-align: center;
}
.custom-zoom button:first-child {
border-bottom: 1px solid #ccc;
border-radius: 4px 4px 0 0;
}
.custom-zoom button:last-child {
border-radius: 0 0 4px 4px;
}
.custom-zoom button:hover {
background-color: #f4f4f4;
}
.custom-zoom button:disabled {
cursor: default;
background-color: #eee;
color: #aaa;
}
#loading-indicator {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: rgba(255, 255, 255, 0.8);
padding: 10px 20px;
border-radius: 5px;
z-index: 2000;
display: none; /* Hidden by default */
}
/* Stats card */
#stats-card {
position: absolute;
bottom: 10px;
right: 10px;
background-color: rgba(255, 255, 255, 0.8);
padding: 8px 12px;
border-radius: 4px;
font-size: 12px;
box-shadow: 0 1px 5px rgba(0, 0, 0, 0.4);
z-index: 1000;
max-width: 250px;
line-height: 1.4;
}
#stats-card table {
margin: 0;
border-collapse: collapse;
}
#stats-card td {
padding: 2px 5px;
}
#stats-card td:first-child {
font-weight: bold;
padding-right: 10px;
}
</style>
</head>
<body>
<div id="map-container">
<div id="tile-grid"></div>
</div>
<div class="custom-zoom">
<button id="zoom-in" title="Zoom in">+</button>
<button id="zoom-out" title="Zoom out">-</button>
</div>
<div id="loading-indicator">Loading...</div>
<div id="stats-card">
<table>
<tr>
<td>FPS:</td>
<td id="fps-value">0</td>
</tr>
<tr>
<td>Center:</td>
<td id="center-value">0.000, 0.000</td>
</tr>
<tr>
<td>Zoom:</td>
<td id="zoom-value">0</td>
</tr>
<tr>
<td>Tiles:</td>
<td id="tiles-value">0</td>
</tr>
<tr>
<td>Memory:</td>
<td id="memory-value">0 MB</td>
</tr>
</table>
</div>
<script>
// --- Configuration ---
const tilesJsonPath = "./terrain_tiles/tiles.json"; // Adjust if needed
const tilePath = "./terrain_tiles/{z}/{x}/{y}.png"; // Adjust if needed
const TILE_SIZE = 256; // Pixel dimensions of a tile
const TILE_BUFFER = 1; // Buffer of tiles to load around viewport
const TILE_MEMORY_ESTIMATE = 0.25; // Estimated MB per tile
// --- DOM Elements ---
const mapContainer = document.getElementById("map-container");
const tileGrid = document.getElementById("tile-grid");
const zoomInButton = document.getElementById("zoom-in");
const zoomOutButton = document.getElementById("zoom-out");
const loadingIndicator = document.getElementById("loading-indicator");
// Stats elements
const fpsValue = document.getElementById("fps-value");
const centerValue = document.getElementById("center-value");
const zoomValue = document.getElementById("zoom-value");
const tilesValue = document.getElementById("tiles-value");
const memoryValue = document.getElementById("memory-value");
// --- State Variables ---
let config = null; // To store loaded tiles.json data
let currentZoom = 10; // Initial default zoom
let minZoom = 0;
let maxZoom = 15;
// Offset of the tile grid's top-left corner relative to the container's top-left
let gridOffsetX = 0;
let gridOffsetY = 0;
let viewportWidth = mapContainer.clientWidth;
let viewportHeight = mapContainer.clientHeight;
let isDragging = false;
let startDragX = 0;
let startDragY = 0;
let startGridX = 0;
let startGridY = 0;
let tileLoadCounter = 0; // To track async tile loading
let visibleTiles = 0; // Number of tiles currently visible
let lastFrameTime = 0; // For FPS calculation
let frameCount = 0; // For FPS calculation
let fps = 0; // Current FPS
let tileCache = new Map(); // Cache for tile elements
let loadVisibleTilesDebounced = null; // For debouncing tile loading
let animationFrameId = null; // For animation frame
// --- Utility Functions ---
// Convert lat/lon to tile coordinates (from your utils)
function deg2num(lat_deg, lon_deg, zoom) {
const lat_rad = (lat_deg * Math.PI) / 180;
const n = Math.pow(2, zoom);
const xtile = Math.floor(((lon_deg + 180.0) / 360.0) * n);
const ytile = Math.floor(
((1.0 - Math.asinh(Math.tan(lat_rad)) / Math.PI) / 2.0) * n
);
return { x: xtile, y: ytile };
}
// Convert tile coordinates to lat/lon
function num2deg(xtile, ytile, zoom) {
const n = Math.pow(2, zoom);
const lon_deg = (xtile / n) * 360.0 - 180.0;
const lat_rad = Math.atan(Math.sinh(Math.PI * (1 - (2 * ytile) / n)));
const lat_deg = (lat_rad * 180.0) / Math.PI;
return { lat: lat_deg, lon: lon_deg };
}
// Debounce function to limit how often a function is called
function debounce(func, wait) {
let timeout;
return function (...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), wait);
};
}
// --- Core Logic ---
function updateGridTransform() {
// Use translate3d for hardware acceleration
tileGrid.style.transform = `translate3d(${gridOffsetX}px, ${gridOffsetY}px, 0)`;
// Update center coordinates in stats
updateCenterCoordinates();
}
function updateCenterCoordinates() {
// Calculate the center point in tile coordinates
const centerGridX = -gridOffsetX + viewportWidth / 2;
const centerGridY = -gridOffsetY + viewportHeight / 2;
// Convert to tile indices
const tileX = centerGridX / TILE_SIZE;
const tileY = centerGridY / TILE_SIZE;
// Convert to geographic coordinates
const geoCoords = num2deg(tileX, tileY, currentZoom);
// Update the display
centerValue.textContent = `${geoCoords.lat.toFixed(
5
)}, ${geoCoords.lon.toFixed(5)}`;
zoomValue.textContent = currentZoom;
}
function showLoading(show) {
loadingIndicator.style.display = show ? "block" : "none";
}
function loadVisibleTiles() {
if (!config) return; // Need config first
showLoading(true);
tileLoadCounter = 0; // Reset counter
// Calculate the pixel bounds of the visible area in the grid's coordinate system
const viewMinX = -gridOffsetX;
const viewMinY = -gridOffsetY;
const viewMaxX = viewMinX + viewportWidth;
const viewMaxY = viewMinY + viewportHeight;
// Calculate the range of tile indices needed
// Add a buffer of tiles around the viewport for smoother panning
const minTileX = Math.floor(viewMinX / TILE_SIZE) - TILE_BUFFER;
const maxTileX = Math.ceil(viewMaxX / TILE_SIZE) + TILE_BUFFER;
const minTileY = Math.floor(viewMinY / TILE_SIZE) - TILE_BUFFER;
const maxTileY = Math.ceil(viewMaxY / TILE_SIZE) + TILE_BUFFER;
const maxTileIndexAtZoom = Math.pow(2, currentZoom);
let tilesToLoad = 0;
let newTiles = new Set(); // Track tiles we're about to create
// First pass: identify tiles we need
for (let x = minTileX; x <= maxTileX; x++) {
for (let y = minTileY; y <= maxTileY; y++) {
// Wrap tile indices if necessary
const wrappedX =
((x % maxTileIndexAtZoom) + maxTileIndexAtZoom) %
maxTileIndexAtZoom;
// Clamp Y coordinate
if (y < 0 || y >= maxTileIndexAtZoom) {
continue;
}
const tileKey = `${currentZoom}/${wrappedX}/${y}`;
newTiles.add(tileKey);
// Skip if this tile is already in the DOM
if (tileCache.has(tileKey)) {
continue;
}
tilesToLoad++;
const tileUrl = tilePath
.replace("{z}", currentZoom)
.replace("{x}", wrappedX)
.replace("{y}", y);
const tile = document.createElement("img");
tile.className = "tile-image";
tile.src = tileUrl;
tile.style.left = `${x * TILE_SIZE}px`; // Use original x for positioning
tile.style.top = `${y * TILE_SIZE}px`;
tile.dataset.z = currentZoom;
tile.dataset.x = wrappedX; // Store wrapped coords
tile.dataset.y = y;
tile.loading = "lazy"; // Basic browser optimization
tile.decoding = "async"; // Use async decoding for better performance
// Add coordinate label
const coordsLabel = document.createElement("div");
coordsLabel.className = "tile-coords";
coordsLabel.textContent = tileKey;
coordsLabel.style.left = `${x * TILE_SIZE}px`; // Position label with tile
coordsLabel.style.top = `${y * TILE_SIZE}px`;
// Handle tile loading completion/error
const onTileLoadOrError = () => {
tileLoadCounter++;
if (tileLoadCounter >= tilesToLoad) {
showLoading(false);
}
};
tile.onload = onTileLoadOrError;
tile.onerror = () => {
tile.style.backgroundColor = "#080929"; // Indicate error visually
console.warn(`Failed to load tile: ${tileUrl}`);
onTileLoadOrError(); // Still count it as "processed"
};
tileGrid.appendChild(tile);
tileGrid.appendChild(coordsLabel);
// Store in cache
tileCache.set(tileKey, { tile, label: coordsLabel });
}
}
// Second pass: remove tiles that are no longer visible
for (const [tileKey, elements] of tileCache.entries()) {
if (!newTiles.has(tileKey)) {
// Remove from DOM and cache
tileGrid.removeChild(elements.tile);
tileGrid.removeChild(elements.label);
tileCache.delete(tileKey);
}
}
// Update stats
visibleTiles = tileCache.size;
tilesValue.textContent = visibleTiles;
memoryValue.textContent = `~${Math.round(
visibleTiles * TILE_MEMORY_ESTIMATE
)} MB`;
if (tilesToLoad === 0) {
showLoading(false); // Hide if no tiles were even attempted
}
}
function handleZoom(zoomIn) {
const newZoom = zoomIn ? currentZoom + 1 : currentZoom - 1;
if (newZoom < minZoom || newZoom > maxZoom) {
return; // Zoom level out of bounds
}
// 1. Calculate the pixel coordinates of the viewport center relative to the current grid
const centerGridX = -gridOffsetX + viewportWidth / 2;
const centerGridY = -gridOffsetY + viewportHeight / 2;
// 2. Calculate the scaling factor between zoom levels
const scaleFactor = Math.pow(2, newZoom - currentZoom);
// 3. Calculate the equivalent pixel coordinates in the new zoom level's grid
const newCenterGridX = centerGridX * scaleFactor;
const newCenterGridY = centerGridY * scaleFactor;
// 4. Calculate the new grid offset to keep the new center point aligned with the viewport center
gridOffsetX = viewportWidth / 2 - newCenterGridX;
gridOffsetY = viewportHeight / 2 - newCenterGridY;
// 5. Update state and reload
currentZoom = newZoom;
// Clear tile cache when zoom changes
tileCache.clear();
tileGrid.innerHTML = "";
updateGridTransform();
loadVisibleTiles();
updateZoomButtons();
}
function updateZoomButtons() {
zoomInButton.disabled = currentZoom >= maxZoom;
zoomOutButton.disabled = currentZoom <= minZoom;
}
function updateFPS(timestamp) {
if (!lastFrameTime) {
lastFrameTime = timestamp;
frameCount = 0;
}
frameCount++;
// Update FPS every second
if (timestamp - lastFrameTime >= 1000) {
fps = Math.round((frameCount * 1000) / (timestamp - lastFrameTime));
fpsValue.textContent = fps;
frameCount = 0;
lastFrameTime = timestamp;
}
animationFrameId = requestAnimationFrame(updateFPS);
}
// --- Event Handlers ---
function onMouseDown(event) {
// Prevent default image dragging behavior
if (event.target.tagName === "IMG") {
event.preventDefault();
}
isDragging = true;
startDragX = event.clientX;
startDragY = event.clientY;
startGridX = gridOffsetX;
startGridY = gridOffsetY;
mapContainer.classList.add("dragging");
// Add listeners to the window to catch mouse movements/mouseup outside the container
window.addEventListener("mousemove", onMouseMove, { passive: true });
window.addEventListener("mouseup", onMouseUp);
}
function onMouseMove(event) {
if (!isDragging) return;
const dx = event.clientX - startDragX;
const dy = event.clientY - startDragY;
gridOffsetX = startGridX + dx;
gridOffsetY = startGridY + dy;
updateGridTransform();
// Use debounced version for better performance during drag
loadVisibleTilesDebounced();
}
function onMouseUp(event) {
if (!isDragging) return;
isDragging = false;
mapContainer.classList.remove("dragging");
window.removeEventListener("mousemove", onMouseMove);
window.removeEventListener("mouseup", onMouseUp);
// Reload tiles now that dragging stopped
loadVisibleTiles();
}
function onResize() {
viewportWidth = mapContainer.clientWidth;
viewportHeight = mapContainer.clientHeight;
loadVisibleTiles();
}
// Touch event handlers for mobile support
function onTouchStart(event) {
if (event.touches.length !== 1) return;
event.preventDefault();
isDragging = true;
startDragX = event.touches[0].clientX;
startDragY = event.touches[0].clientY;
startGridX = gridOffsetX;
startGridY = gridOffsetY;
mapContainer.classList.add("dragging");
}
function onTouchMove(event) {
if (!isDragging || event.touches.length !== 1) return;
const dx = event.touches[0].clientX - startDragX;
const dy = event.touches[0].clientY - startDragY;
gridOffsetX = startGridX + dx;
gridOffsetY = startGridY + dy;
updateGridTransform();
loadVisibleTilesDebounced();
}
function onTouchEnd(event) {
if (!isDragging) return;
isDragging = false;
mapContainer.classList.remove("dragging");
loadVisibleTiles();
}
// --- Initialization ---
function initializeMap() {
showLoading(true);
// Create debounced version of loadVisibleTiles
loadVisibleTilesDebounced = debounce(loadVisibleTiles, 100);
// Start FPS counter
animationFrameId = requestAnimationFrame(updateFPS);
fetch(tilesJsonPath)
.then((response) => {
if (!response.ok)
throw new Error(
`HTTP ${response.status} fetching ${tilesJsonPath}`
);
return response.json();
})
.then((jsonConfig) => {
config = jsonConfig;
minZoom = config.minzoom ?? 0;
maxZoom = config.maxzoom ?? 15;
currentZoom = config.center
? Math.max(
minZoom,
Math.min(maxZoom, Math.round(config.center[2]))
)
: minZoom;
// Calculate initial center tile and pixel offset
const centerLon = config.center ? config.center[0] : 0;
const centerLat = config.center ? config.center[1] : 0;
const centerTile = deg2num(centerLat, centerLon, currentZoom);
// Calculate offset to place the *center* of the center tile at the viewport center
gridOffsetX =
viewportWidth / 2 - centerTile.x * TILE_SIZE - TILE_SIZE / 2;
gridOffsetY =
viewportHeight / 2 - centerTile.y * TILE_SIZE - TILE_SIZE / 2;
console.log(
`Initial Zoom: ${currentZoom}, Center Tile: ${centerTile.x},${
centerTile.y
}, Offset: ${gridOffsetX.toFixed(1)},${gridOffsetY.toFixed(1)}`
);
updateGridTransform();
loadVisibleTiles();
updateZoomButtons();
// Setup event listeners
mapContainer.addEventListener("mousedown", onMouseDown);
mapContainer.addEventListener("touchstart", onTouchStart, {
passive: false,
});
mapContainer.addEventListener("touchmove", onTouchMove, {
passive: true,
});
mapContainer.addEventListener("touchend", onTouchEnd);
zoomInButton.addEventListener("click", () => handleZoom(true));
zoomOutButton.addEventListener("click", () => handleZoom(false));
// Use passive event listener for better scroll performance
window.addEventListener("resize", onResize, { passive: true });
// Add wheel zoom support
mapContainer.addEventListener(
"wheel",
(e) => {
e.preventDefault();
handleZoom(e.deltaY < 0);
},
{ passive: false }
);
})
.catch((error) => {
console.error("Initialization failed:", error);
mapContainer.innerHTML = `<p style="color: red; padding: 20px;">Error loading map configuration: ${error.message}. Check console and ensure '${tilesJsonPath}' is accessible.</p>`;
showLoading(false);
});
}
// Start initialization when the DOM is ready
document.addEventListener("DOMContentLoaded", initializeMap);
// Clean up on page unload
window.addEventListener("beforeunload", () => {
if (animationFrameId) {
cancelAnimationFrame(animationFrameId);
}
tileCache.clear();
});
</script>
</body>
</html>