/** * MapView - Handles all canvas rendering for the map viewer */ class MapView { constructor(canvas) { this.canvas = canvas; this.ctx = canvas.getContext('2d'); // View state this.zoom = CONFIG.MIN_ZOOM + 1; // Hoechste Zoomstufe der aktuellen Karte - MapController.loadMap setzt sie aus dem // Kachel-Manifest (manche Karten haben nur Kacheln bis Stufe 5). this.maxZoom = CONFIG.MAX_ZOOM; this.centerWorldX = (CONFIG.WORLD_MIN_X + CONFIG.WORLD_MAX_X) / 2; this.centerWorldY = (CONFIG.WORLD_MIN_Y + CONFIG.WORLD_MAX_Y) / 2; // Icon cache this.iconCache = {}; this.loadingIcons = new Map(); // Dateiname -> Promise des laufenden Ladens // Icons, die nicht geladen werden konnten - nicht bei jedem Neuzeichnen wieder anfragen, // sondern gleich das Emoji zeichnen. this.failedIcons = new Set(); // Interaction state this.isDragging = false; this.lastMouseX = 0; this.lastMouseY = 0; this.renderRequested = false; } /** * Resize canvas to fill window */ resize() { this.canvas.width = window.innerWidth; this.canvas.height = window.innerHeight; // Anderes Seitenverhaeltnis (z.B. Handy gedreht): Ansicht wieder in die Karte holen this.clampView(); } /** * Convert world coordinates to screen coordinates */ worldToScreen(worldX, worldY) { const worldWidth = CONFIG.WORLD_MAX_X - CONFIG.WORLD_MIN_X; const zoomScale = Math.pow(2, this.zoom - CONFIG.MIN_ZOOM); const visibleWidth = worldWidth / zoomScale; const scale = this.canvas.width / visibleWidth; const camOffsetX = -this.centerWorldX * scale + this.canvas.width / 2; const camOffsetY = -this.centerWorldY * scale + this.canvas.height / 2; return { x: worldX * scale + camOffsetX, y: worldY * scale + camOffsetY }; } /** * Convert screen coordinates to world coordinates */ screenToWorld(screenX, screenY) { const worldWidth = CONFIG.WORLD_MAX_X - CONFIG.WORLD_MIN_X; const zoomScale = Math.pow(2, this.zoom - CONFIG.MIN_ZOOM); const visibleWidth = worldWidth / zoomScale; const scale = this.canvas.width / visibleWidth; const camOffsetX = -this.centerWorldX * scale + this.canvas.width / 2; const camOffsetY = -this.centerWorldY * scale + this.canvas.height / 2; return { x: (screenX - camOffsetX) / scale, y: (screenY - camOffsetY) / scale }; } /** * Get viewport bounds in world coordinates */ getViewBounds() { const topLeft = this.screenToWorld(0, 0); const bottomRight = this.screenToWorld(this.canvas.width, this.canvas.height); return { minX: Math.min(topLeft.x, bottomRight.x), maxX: Math.max(topLeft.x, bottomRight.x), minY: Math.min(topLeft.y, bottomRight.y), maxY: Math.max(topLeft.y, bottomRight.y) }; } /** * Render the map with tiles and markers */ async render(tileService, mapData) { const ctx = this.ctx; const width = this.canvas.width; const height = this.canvas.height; // Clear canvas ctx.fillStyle = '#0a0a1e'; ctx.fillRect(0, 0, width, height); // Zeichenebene der Taktiken sofort mitziehen, nicht erst nach dem Laden der Kacheln. if (this.onViewChange) this.onViewChange(); // Pin eines geteilten Ortes mitziehen (LocationController) if (this.onPinUpdate) this.onPinUpdate(); if (!mapData.currentMap) return; const slug = mapData.currentMap.slug; const worldWidth = CONFIG.WORLD_MAX_X - CONFIG.WORLD_MIN_X; // Calculate scale and camera offset const zoomScale = Math.pow(2, this.zoom - CONFIG.MIN_ZOOM); const visibleWidth = worldWidth / zoomScale; const scale = width / visibleWidth; const camOffsetX = -this.centerWorldX * scale + width / 2; const camOffsetY = -this.centerWorldY * scale + height / 2; // Aendert sich die Ansicht, waehrend dieses Bild noch auf Kacheln oder Icons wartet, hoert // es auf (sonst landen Kacheln und Marker an der alten Stelle ueber dem neuen Bild). const isStale = this.staleCheck(tileService, mapData); // Draw tiles at current zoom level const tilesPerSide = Math.pow(2, this.zoom); const tileWorldSize = worldWidth / tilesPerSide; const tileScreenSize = tileWorldSize * scale; for (let tx = 0; tx < tilesPerSide; tx++) { for (let ty = 0; ty < tilesPerSide; ty++) { // World position of this tile's top-left corner const tileWorldX = CONFIG.WORLD_MIN_X + tx * tileWorldSize; const tileWorldY = CONFIG.WORLD_MIN_Y + ty * tileWorldSize; // Screen position after camera transform const screenX = tileWorldX * scale + camOffsetX; const screenY = tileWorldY * scale + camOffsetY; // Skip tiles completely outside viewport (with margin) if (screenX + tileScreenSize < -tileScreenSize || screenX > width + tileScreenSize || screenY + tileScreenSize < -tileScreenSize || screenY > height + tileScreenSize) { continue; } const tileImg = await tileService.loadTile(slug, this.zoom, tx, ty); if (isStale()) return; if (tileImg) { ctx.drawImage(tileImg, screenX, screenY, tileScreenSize, tileScreenSize); } else { // Placeholder for missing/loading tiles ctx.fillStyle = '#1a1a3e'; ctx.fillRect(screenX, screenY, tileScreenSize, tileScreenSize); } } } // Draw markers this.drawMarkers(mapData, isStale); // Preload adjacent zoom levels in background const viewBounds = this.getViewBounds(); tileService.preloadAdjacentZoomLevels(slug, this.zoom, viewBounds); } /** * Prueft fuer ein laufendes Bild, ob sich die Ansicht (Karte, Zoom, Position, Groesse) seit * seinem Start geaendert hat. Dann ist es veraltet und stoesst einmal ein frisches Bild an - * so erscheint, was es gerade fertig geladen hat, trotzdem an der richtigen Stelle. * Ein Kartenwechsel zeichnet loadMap selbst neu, sobald die neue Karte geladen ist. */ staleCheck(tileService, mapData) { const map = mapData.currentMap; const zoom = this.zoom; const centerX = this.centerWorldX; const centerY = this.centerWorldY; const width = this.canvas.width; const height = this.canvas.height; let stale = false; return () => { if (stale) return true; if (mapData.currentMap === map && this.zoom === zoom && this.centerWorldX === centerX && this.centerWorldY === centerY && this.canvas.width === width && this.canvas.height === height) { return false; } stale = true; if (mapData.currentMap === map) this.requestRender(tileService, mapData); return true; }; } /** * Load an icon image from local data directory */ async loadIcon(iconPath) { if (!iconPath) return null; // Extract filename from path const filename = iconPath.split('/').pop(); if (this.iconCache[filename]) { return this.iconCache[filename]; } // Datei fehlt oder ist kaputt: nicht erneut anfragen, gleich das Emoji zeichnen if (this.failedIcons.has(filename)) { return null; } // Laedt schon (z.B. fuer ein frueheres Bild): auf dasselbe Laden warten if (this.loadingIcons.has(filename)) { return this.loadingIcons.get(filename); } const loading = new Promise(resolve => { const img = new Image(); // Langsam: vorerst das Emoji - kommt das Bild spaeter doch noch, nimmt es das naechste Bild const timer = setTimeout(() => resolve(null), 3000); img.onload = () => { clearTimeout(timer); this.iconCache[filename] = img; resolve(img); }; img.onerror = () => { clearTimeout(timer); this.failedIcons.add(filename); resolve(null); }; img.src = `${CONFIG.ICONS_DIR}/${filename}`; }); this.loadingIcons.set(filename, loading); loading.then(() => this.loadingIcons.delete(filename)); return loading; } /** * Draw all visible markers using icon images */ async drawMarkers(mapData, isStale = () => false) { const ctx = this.ctx; for (const marker of mapData.markers) { const catKey = `${marker.group_name}/${marker.category_name}`; if (!mapData.visibleCategories.has(catKey)) continue; const iconSize = this.markerSize(); // Try to load and draw icon image let iconImg = null; if (marker.iconImage) { iconImg = await this.loadIcon(marker.iconImage); // Ansicht hat sich beim Warten geaendert: nicht an der alten Stelle weiterzeichnen if (isStale()) return; } // Position erst nach dem Warten bestimmen const screen = this.worldToScreen(marker.worldX, marker.worldY); if (iconImg) { // Draw icon image centered at marker position ctx.drawImage(iconImg, screen.x - iconSize / 2, screen.y - iconSize / 2, iconSize, iconSize); } else { // Fallback to emoji if no icon available const symbol = CONFIG.CATEGORY_SYMBOLS[marker.category_name] || '📍'; const fontSize = Math.round(iconSize * 0.75); ctx.font = `${fontSize}px sans-serif`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.fillText(symbol, screen.x, screen.y); } } } /** * Groesse der Marker-Icons in Pixeln - waechst mit der Zoomstufe, damit man sie auch * herausgezoomt noch erkennt. */ markerSize() { const sizes = { 2: 20, 3: 24, 4: 28, 5: 32, 6: 38 }; return sizes[this.zoom] || (this.zoom < 2 ? 18 : 38); } /** * Zoom in */ zoomIn() { // Nur bis zur hoechsten Stufe dieser Karte - darueber gibt es keine Kacheln if (this.zoom < this.maxZoom) { this.zoom++; this.clampView(); return true; } return false; } /** * Zoom out */ zoomOut() { if (this.zoom > CONFIG.MIN_ZOOM) { this.zoom--; this.clampView(); return true; } return false; } /** * Eine Stufe rein (+1) oder raus (-1) zoomen, wobei der Weltpunkt unter * screenX/screenY an seiner Stelle bleibt (z.B. zwischen zwei Fingern). */ zoomAt(step, screenX, screenY) { const before = this.screenToWorld(screenX, screenY); const changed = step > 0 ? this.zoomIn() : this.zoomOut(); if (!changed) return false; const after = this.screenToWorld(screenX, screenY); const scale = this.worldToScreen(1, 0).x - this.worldToScreen(0, 0).x; this.panBy((after.x - before.x) * scale, (after.y - before.y) * scale); return true; } /** * Reset view to default */ resetView() { this.zoom = Math.min(CONFIG.MIN_ZOOM + 1, this.maxZoom); this.centerWorldX = (CONFIG.WORLD_MIN_X + CONFIG.WORLD_MAX_X) / 2; this.centerWorldY = (CONFIG.WORLD_MIN_Y + CONFIG.WORLD_MAX_Y) / 2; this.clampView(); } /** * Pan by screen delta */ panBy(dx, dy) { const scale = this.worldScale(); if (!scale) return; // Each screen pixel represents 1/scale world units const worldDx = -(dx / scale); const worldDy = -(dy / scale); this.centerWorldX += worldDx; this.centerWorldY += worldDy; // Nicht ueber den Kartenrand hinaus ziehen this.clampView(); } /** * Bildschirmpixel pro Welteinheit bei der aktuellen Zoomstufe */ worldScale() { const worldWidth = CONFIG.WORLD_MAX_X - CONFIG.WORLD_MIN_X; const visibleWidth = worldWidth / Math.pow(2, this.zoom - CONFIG.MIN_ZOOM); return this.canvas.width / visibleWidth; } /** * Ansicht in der Karte halten: Ist der sichtbare Bereich auf einer Achse groesser als die Karte * (z.B. Handy hochkant ganz herausgezoomt), steht die Karte auf dieser Achse mittig; sonst * bleiben die Raender der Ansicht innerhalb der Karte - kein Ziehen ins Leere. */ clampView() { const scale = this.worldScale(); // Noch ohne Groesse (z.B. Rahmen unsichtbar): nichts zu begrenzen if (!scale || !this.canvas.height) return; const clampAxis = (center, min, max, halfVisible) => { if (!isFinite(center) || max - min <= halfVisible * 2) return (min + max) / 2; return Math.min(max - halfVisible, Math.max(min + halfVisible, center)); }; this.centerWorldX = clampAxis(this.centerWorldX, CONFIG.WORLD_MIN_X, CONFIG.WORLD_MAX_X, this.canvas.width / scale / 2); this.centerWorldY = clampAxis(this.centerWorldY, CONFIG.WORLD_MIN_Y, CONFIG.WORLD_MAX_Y, this.canvas.height / scale / 2); } /** * Request a render frame */ requestRender(tileService, mapData) { if (!this.renderRequested) { this.renderRequested = true; requestAnimationFrame(() => { this.render(tileService, mapData); this.renderRequested = false; }); } } /** * Find nearest marker to screen position */ findNearestMarker(mapData, screenX, screenY, threshold = this.markerSize() * 0.7) { let nearest = null; let nearestDist = threshold; for (const marker of mapData.markers) { const catKey = `${marker.group_name}/${marker.category_name}`; if (!mapData.visibleCategories.has(catKey)) continue; const screen = this.worldToScreen(marker.worldX, marker.worldY); const dx = screenX - screen.x; const dy = screenY - screen.y; const dist = Math.sqrt(dx * dx + dy * dy); if (dist < nearestDist) { nearestDist = dist; nearest = marker; } } return nearest; } }