Dungeon Viewer changes

This commit is contained in:
dingo
2026-01-11 08:21:50 -05:00
parent fb2b339121
commit 14c50f0aae
3 changed files with 268 additions and 292 deletions
+2 -2
View File
@@ -19,12 +19,12 @@ public class DungeonGeneratorV3
/// Enable verbose logging to trace tile selection decisions.
/// Set to true to debug tile/template selection issues.
/// </summary>
public static bool VerboseLogging { get; set; } = true;
public static bool VerboseLogging { get; set; } = false;
/// <summary>
/// Log every single tile placement (WARNING: extremely verbose for large dungeons)
/// </summary>
public static bool LogEveryTile { get; set; } = true;
public static bool LogEveryTile { get; set; } = false;
/// <summary>
/// Enable socket-based tile matching. When true, tiles are selected based on
+249 -284
View File
@@ -21,31 +21,28 @@
.stat-card { background: rgba(30, 30, 50, 0.8); border: 1px solid #374151; border-radius: 8px; padding: 12px; }
.inspector { background: rgba(20, 20, 40, 0.95); border: 1px solid #4f46e5; border-radius: 8px; padding: 16px; }
.inspector-stat { display: flex; justify-content: space-between; padding: 4px 0; border-bottom: 1px solid rgba(255,255,255,0.1); }
.tool-btn { padding: 6px 10px; border-radius: 6px; font-size: 12px; transition: all 0.15s; }
.tool-btn { padding: 6px 10px; border-radius: 6px; font-size: 12px; transition: all 0.15s; background: #374151; color: #ccc; border: none; cursor: pointer; }
.tool-btn:hover { background: #4b5563; }
.tool-btn.active { background: #4f46e5; color: white; }
.zoom-controls { display: flex; align-items: center; gap: 8px; }
.zoom-btn { width: 32px; height: 32px; display: flex; align-items: center; justify-content: center; }
/* Tile picker modal */
.tile-picker-modal { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.8); z-index: 1000; display: flex; align-items: center; justify-content: center; }
.tile-picker-content { background: #1a1a2e; border: 2px solid #4f46e5; border-radius: 12px; max-width: 90vw; max-height: 90vh; overflow: hidden; display: flex; flex-direction: column; }
.tile-picker-header { padding: 16px; border-bottom: 1px solid #374151; display: flex; justify-content: space-between; align-items: center; }
.tile-picker-body { display: flex; flex: 1; overflow: hidden; }
.tile-picker-sheets { width: 200px; border-right: 1px solid #374151; overflow-y: auto; padding: 8px; }
.tile-picker-grid { flex: 1; overflow: auto; padding: 16px; }
.sheet-item { padding: 8px; border-radius: 6px; cursor: pointer; margin-bottom: 4px; }
.sheet-item:hover, .sheet-item.selected { background: #374151; }
.tile-grid { display: grid; gap: 2px; }
.tile-cell { border: 1px solid transparent; cursor: pointer; image-rendering: pixelated; }
/* Tile Drawer */
.tile-drawer { position: fixed; top: 0; right: -320px; width: 320px; height: 100vh; background: #1a1a2e; border-left: 2px solid #4f46e5; z-index: 1000; transition: right 0.3s ease; display: flex; flex-direction: column; }
.tile-drawer.open { right: 0; }
.tile-drawer-header { padding: 16px; border-bottom: 1px solid #374151; display: flex; justify-content: space-between; align-items: center; flex-shrink: 0; }
.tile-drawer-body { flex: 1; overflow-y: auto; padding: 12px; }
.sheet-section { margin-bottom: 16px; }
.sheet-header { padding: 8px; background: #252540; border-radius: 6px; cursor: pointer; display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
.sheet-header:hover { background: #303050; }
.sheet-header.expanded { background: #4f46e5; }
.tile-grid { display: grid; gap: 2px; padding: 4px; background: #0a0a15; border-radius: 4px; }
.tile-cell { border: 2px solid transparent; cursor: pointer; image-rendering: pixelated; background: #1a1a2e; }
.tile-cell:hover { border-color: #4f46e5; }
.tile-cell.selected { border-color: #22c55e; border-width: 2px; }
.tile-preview { width: 64px; height: 64px; border: 2px solid #374151; margin: 8px auto; image-rendering: pixelated; background: #000; }
/* Template picker */
.template-list { max-height: 300px; overflow-y: auto; }
.template-item { padding: 8px; border-radius: 6px; cursor: pointer; display: flex; align-items: center; gap: 8px; }
.template-item:hover { background: #374151; }
.template-item.selected { background: #4f46e5; }
.tile-cell.selected { border-color: #22c55e; }
.tile-preview-box { display: flex; align-items: center; gap: 12px; padding: 12px; background: #252540; border-radius: 8px; margin-bottom: 12px; }
.tile-preview-canvas { width: 48px; height: 48px; border: 2px solid #374151; image-rendering: pixelated; background: #000; }
.drawer-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 999; display: none; }
.drawer-overlay.open { display: block; }
</style>
<div class="mb-4">
@@ -69,16 +66,15 @@ else
<div class="flex items-center justify-between mb-4">
<h2 class="text-xl font-semibold text-white">Live Dungeon Map</h2>
<div class="flex items-center gap-4">
<!-- Zoom Controls -->
<div class="zoom-controls">
<button onclick="zoomOut()" class="btn btn-sm btn-secondary zoom-btn">−</button>
<div class="flex items-center gap-2">
<button onclick="zoomOut()" class="tool-btn zoom-btn">−</button>
<span id="zoomLevel" class="text-sm text-gray-400 w-12 text-center">100%</span>
<button onclick="zoomIn()" class="btn btn-sm btn-secondary zoom-btn">+</button>
<button onclick="zoomFit()" class="btn btn-sm btn-secondary">Fit</button>
<button onclick="zoomIn()" class="tool-btn zoom-btn">+</button>
<button onclick="zoomFit()" class="tool-btn">Fit</button>
</div>
<div class="flex items-center gap-2 text-sm text-gray-400">
<div class="w-2 h-2 bg-green-400 rounded-full animate-pulse"></div>
<button onclick="toggleAutoRefresh()" id="autoRefreshBtn" class="btn btn-sm btn-secondary">Auto: ON</button>
<button onclick="toggleAutoRefresh()" id="autoRefreshBtn" class="tool-btn">Auto: ON</button>
</div>
</div>
</div>
@@ -90,30 +86,26 @@ else
<button onclick="setEditMode('floor')" id="modeFloor" class="tool-btn">🟦 Floor</button>
<button onclick="setEditMode('wall')" id="modeWall" class="tool-btn">⬛ Wall</button>
<button onclick="setEditMode('tile')" id="modeTile" class="tool-btn">🎨 Tile</button>
<button onclick="setEditMode('template')" id="modeTemplate" class="tool-btn">📦 Template</button>
<button onclick="setEditMode('erase')" id="modeErase" class="tool-btn">🗑️ Erase</button>
<span class="text-xs text-gray-500 ml-auto" id="editHint">Click/drag on map</span>
<button onclick="toggleTileDrawer()" id="drawerToggle" class="tool-btn ml-auto">📋 Tile Picker</button>
</div>
<!-- Selected Tile Preview -->
<div id="selectedTilePreview" class="hidden mb-3 p-2 bg-gray-800 rounded flex items-center gap-4">
<canvas id="previewCanvas" width="32" height="32" class="tile-preview"></canvas>
<div>
<!-- Selected Tile Info (shown when in tile mode) -->
<div id="selectedTileInfo" class="hidden mb-3 p-2 bg-gray-800 rounded flex items-center gap-4">
<canvas id="previewCanvas" width="32" height="32" class="tile-preview-canvas"></canvas>
<div class="flex-1">
<div class="text-sm text-white" id="selectedTileName">No tile selected</div>
<div class="text-xs text-gray-400" id="selectedTileInfo">Click "Tile" to pick</div>
<button onclick="openTilePicker()" class="btn btn-sm btn-secondary mt-1">Change Tile</button>
<div class="text-xs text-gray-400">Click "Tile Picker" to select</div>
</div>
<div class="ml-auto flex items-center gap-2">
<label class="text-xs text-gray-400">Layer:</label>
<select id="tileLayer" class="input text-xs w-20">
<div class="flex items-center gap-2">
<select id="tileLayer" class="input text-xs w-24">
<option value="0">Ground</option>
<option value="1">Decor</option>
<option value="2">Walls</option>
<option value="3">Ceiling</option>
</select>
<label class="flex items-center gap-1 text-xs text-gray-400">
<input type="checkbox" id="tileWalkable" checked class="w-4 h-4">
Walkable
<input type="checkbox" id="tileWalkable" checked class="w-4 h-4"> Walk
</label>
</div>
</div>
@@ -132,7 +124,7 @@ else
</div>
</div>
<!-- Player Inspector -->
<!-- Inspectors -->
<div id="playerInspector" class="inspector mt-4 hidden">
<div class="flex items-center justify-between mb-3">
<h3 class="text-lg font-semibold text-green-400" id="playerInspectorName">Player</h3>
@@ -147,7 +139,6 @@ else
</div>
</div>
<!-- Mob Inspector -->
<div id="mobInspector" class="inspector mt-4 hidden">
<div class="flex items-center justify-between mb-3">
<h3 class="text-lg font-semibold text-red-400" id="mobInspectorName">Mob</h3>
@@ -156,27 +147,24 @@ else
<div id="mobInspectorContent" class="space-y-1 text-sm"></div>
<div class="flex gap-2 mt-4">
<button onclick="killSelectedMob()" class="btn btn-danger btn-sm flex-1">🗡️ Kill</button>
<button onclick="copyMobPosition()" class="btn btn-secondary btn-sm flex-1">📍 Copy Pos</button>
<button onclick="copyMobPosition()" class="btn btn-secondary btn-sm flex-1">📍 Copy</button>
</div>
</div>
</div>
<!-- Right: Info Panel -->
<div class="w-full lg:w-80 space-y-4">
<!-- Dungeon Info -->
<div class="stat-card">
<h3 class="text-lg font-semibold text-white mb-3">Dungeon Info</h3>
<div class="space-y-2 text-sm">
<div class="flex justify-between"><span class="text-gray-400">ID</span><span class="text-white font-mono text-xs">@Model.Dungeon.Id.ToString()[..12]...</span></div>
<div class="flex justify-between"><span class="text-gray-400">Tier</span><span class="text-white">@Model.Dungeon.Tier</span></div>
<div class="flex justify-between"><span class="text-gray-400">Bracket</span><span class="text-white">@Model.Dungeon.LevelBracketMin-@Model.Dungeon.LevelBracketMax</span></div>
<div class="flex justify-between"><span class="text-gray-400">Size</span><span class="text-white">@Model.MapWidth × @Model.MapHeight</span></div>
<div class="flex justify-between"><span class="text-gray-400">Tiles</span><span class="text-white">@Model.VisualTileCount placed</span></div>
<div class="flex justify-between"><span class="text-gray-400">Tiles</span><span class="text-white">@Model.VisualTileCount</span></div>
<div class="flex justify-between"><span class="text-gray-400">Sheets</span><span class="text-white" id="sheetCount">0</span></div>
<div class="flex justify-between"><span class="text-gray-400">Duration</span><span class="text-white" id="duration">@Model.Duration</span></div>
</div>
</div>
<!-- Live Stats -->
<div class="stat-card">
<h3 class="text-lg font-semibold text-white mb-3">Live Stats</h3>
<div class="grid grid-cols-2 gap-3">
@@ -191,7 +179,6 @@ else
</div>
</div>
<!-- Spawn Mob -->
<div class="stat-card">
<h3 class="text-lg font-semibold text-white mb-3">Spawn Mob</h3>
<div class="space-y-2">
@@ -207,46 +194,44 @@ else
<input type="number" id="spawnY" class="input text-sm" placeholder="Y" value="@(Model.MapHeight / 2 * 32)" />
</div>
<button onclick="spawnMob()" class="btn btn-success w-full text-sm">+ Spawn</button>
<p class="text-xs text-gray-500">Right-click map to set position</p>
</div>
</div>
<!-- Actions -->
<div class="stat-card">
<h3 class="text-lg font-semibold text-white mb-3">Actions</h3>
<div class="space-y-2">
<form method="post" asp-page-handler="KillAllMobs">
@Html.AntiForgeryToken()
<input type="hidden" name="id" value="@Model.Dungeon.Id" />
<button type="submit" class="btn btn-secondary w-full text-sm" onclick="return confirm('Kill all mobs?')">Kill All Mobs</button>
<button type="submit" class="btn btn-secondary w-full text-sm" onclick="return confirm('Kill all?')">Kill All Mobs</button>
</form>
<form method="post" asp-page-handler="CompleteDungeon">
@Html.AntiForgeryToken()
<input type="hidden" name="id" value="@Model.Dungeon.Id" />
<button type="submit" class="btn btn-secondary w-full text-sm">Force Complete</button>
</form>
<button onclick="broadcastTileUpdate()" class="btn btn-primary w-full text-sm">📡 Broadcast Tiles</button>
<button onclick="broadcastTiles()" class="btn btn-primary w-full text-sm">📡 Broadcast Tiles</button>
</div>
</div>
</div>
</div>
<!-- Tile Picker Modal -->
<div id="tilePickerModal" class="tile-picker-modal hidden">
<div class="tile-picker-content" style="width: 800px; height: 600px;">
<div class="tile-picker-header">
<h3 class="text-lg font-semibold text-white">Select Tile</h3>
<button onclick="closeTilePicker()" class="text-gray-400 hover:text-white text-2xl">&times;</button>
<!-- Tile Picker Drawer -->
<div id="drawerOverlay" class="drawer-overlay" onclick="closeTileDrawer()"></div>
<div id="tileDrawer" class="tile-drawer">
<div class="tile-drawer-header">
<h3 class="text-lg font-semibold text-white">Tile Picker</h3>
<button onclick="closeTileDrawer()" class="text-gray-400 hover:text-white text-xl">✕</button>
</div>
<div class="tile-drawer-body">
<!-- Selected tile preview -->
<div class="tile-preview-box">
<canvas id="drawerPreview" width="48" height="48" class="tile-preview-canvas"></canvas>
<div>
<div class="text-sm text-white" id="drawerTileName">No tile selected</div>
<div class="text-xs text-gray-400" id="drawerTileInfo">Select from below</div>
</div>
</div>
<div class="tile-picker-body">
<div class="tile-picker-sheets">
<div class="text-xs text-gray-400 mb-2 px-2">Sprite Sheets</div>
<div id="sheetList"></div>
</div>
<div class="tile-picker-grid">
<div id="tileGridContainer">
<p class="text-gray-500">Select a sheet to view tiles</p>
</div>
</div>
<!-- Sheet list -->
<div id="sheetList">
<p class="text-gray-500 text-sm">Loading sheets...</p>
</div>
</div>
</div>
@@ -262,96 +247,202 @@ else
let visualTiles = @Html.Raw(Model.VisualTilesJson);
let tileSheets = @Html.Raw(Model.TileSheetsJson);
let autoRefresh = true;
let refreshInterval;
let autoRefresh = true, refreshInterval;
let zoom = 1.0;
const minZoom = 0.25, maxZoom = 4.0;
// Selection state
let selectedMobId = null, selectedPlayerId = null;
let currentMobs = [], currentPlayers = [];
// Edit state
let editMode = 'none';
let isDrawing = false;
let editMode = 'none', isDrawing = false;
let teleportMode = false, godModeEnabled = false;
// Tile painting state
let selectedSheetId = 0, selectedFrameIndex = 0;
let sheetTextures = {}; // sheet_id -> Image
let sheetTextures = {};
let expandedSheets = {};
// ==================== INITIALIZATION ====================
// ==================== INIT ====================
async function init() {
console.log('[Admin] Init - tileSheets:', tileSheets.length);
document.getElementById('sheetCount').textContent = tileSheets.length;
await loadSheetTextures();
initMap();
buildSheetList();
updateEntities(@Html.Raw(Model.PlayersJson), @Html.Raw(Model.MobsJson));
refreshInterval = setInterval(fetchUpdate, 500);
}
async function loadSheetTextures() {
const cdnBase = 'https://assets.aeternalisgames.com/downloads/';
const promises = tileSheets.map(sheet => new Promise(resolve => {
const img = new Image();
img.crossOrigin = 'anonymous';
img.onload = () => { sheetTextures[sheet.id] = img; console.log('[Admin] Loaded sheet', sheet.id, sheet.path); resolve(); };
img.onerror = () => { console.warn('[Admin] Failed to load', sheet.path); resolve(); };
img.src = cdnBase + sheet.path;
}));
await Promise.all(promises);
console.log('[Admin] Loaded', Object.keys(sheetTextures).length, 'textures');
}
function initMap() {
const canvas = document.getElementById('mapCanvas');
const viewport = document.getElementById('mapViewport');
const entityLayer = document.getElementById('entityLayer');
canvas.width = mapWidth * tileSize;
canvas.height = mapHeight * tileSize;
entityLayer.style.width = canvas.width + 'px';
entityLayer.style.height = canvas.height + 'px';
applyZoom();
loadSheetTextures().then(() => drawMap());
drawMap();
setupCanvasEvents(canvas);
}
async function loadSheetTextures() {
const promises = tileSheets.map(async sheet => {
const img = new Image();
img.crossOrigin = 'anonymous';
return new Promise((resolve) => {
img.onload = () => { sheetTextures[sheet.id] = img; resolve(); };
img.onerror = () => resolve();
img.src = 'https://assets.aeternalisgames.com/downloads/' + sheet.path;
});
});
await Promise.all(promises);
console.log('[Admin] Loaded', Object.keys(sheetTextures).length, 'sheet textures');
}
function drawMap() {
const canvas = document.getElementById('mapCanvas');
const ctx = canvas.getContext('2d');
ctx.imageSmoothingEnabled = false;
// Draw base walkability
// Base walkability
for (let y = 0; y < mapHeight; y++) {
for (let x = 0; x < mapWidth; x++) {
const idx = y * mapWidth + x;
ctx.fillStyle = walkableData[idx] ? '#1e3a5f' : '#1a1a2e';
ctx.fillStyle = walkableData[y * mapWidth + x] ? '#1e3a5f' : '#1a1a2e';
ctx.fillRect(x * tileSize, y * tileSize, tileSize, tileSize);
}
}
// Draw visual tiles
// Visual tiles
for (const tile of visualTiles) {
const sheet = tileSheets.find(s => s.id === tile.sid);
const texture = sheetTextures[tile.sid];
if (!sheet || !texture) continue;
const tex = sheetTextures[tile.sid];
if (!sheet || !tex) continue;
const cols = Math.floor(sheet.sheetW / sheet.tileW);
const srcX = (tile.frame % cols) * sheet.tileW;
const srcY = Math.floor(tile.frame / cols) * sheet.tileH;
ctx.save();
ctx.translate(tile.x * tileSize + tileSize/2, tile.y * tileSize + tileSize/2);
if (tile.r) ctx.rotate(tile.r * Math.PI / 2);
if (tile.fx) ctx.scale(-1, 1);
if (tile.fy) ctx.scale(1, -1);
ctx.drawImage(texture, srcX, srcY, sheet.tileW, sheet.tileH, -tileSize/2, -tileSize/2, tileSize, tileSize);
ctx.restore();
ctx.drawImage(tex, srcX, srcY, sheet.tileW, sheet.tileH, tile.x * tileSize, tile.y * tileSize, tileSize, tileSize);
}
// Draw grid
// Grid
ctx.strokeStyle = 'rgba(255,255,255,0.05)';
for (let x = 0; x <= mapWidth; x++) {
ctx.beginPath(); ctx.moveTo(x * tileSize, 0); ctx.lineTo(x * tileSize, mapHeight * tileSize); ctx.stroke();
for (let i = 0; i <= mapWidth; i++) { ctx.beginPath(); ctx.moveTo(i * tileSize, 0); ctx.lineTo(i * tileSize, mapHeight * tileSize); ctx.stroke(); }
for (let i = 0; i <= mapHeight; i++) { ctx.beginPath(); ctx.moveTo(0, i * tileSize); ctx.lineTo(mapWidth * tileSize, i * tileSize); ctx.stroke(); }
}
// ==================== TILE DRAWER ====================
function toggleTileDrawer() {
const drawer = document.getElementById('tileDrawer');
const overlay = document.getElementById('drawerOverlay');
drawer.classList.toggle('open');
overlay.classList.toggle('open');
}
function closeTileDrawer() {
document.getElementById('tileDrawer').classList.remove('open');
document.getElementById('drawerOverlay').classList.remove('open');
}
function buildSheetList() {
const container = document.getElementById('sheetList');
if (tileSheets.length === 0) {
container.innerHTML = '<p class="text-gray-500 text-sm">No tile sheets in this dungeon</p>';
return;
}
for (let y = 0; y <= mapHeight; y++) {
ctx.beginPath(); ctx.moveTo(0, y * tileSize); ctx.lineTo(mapWidth * tileSize, y * tileSize); ctx.stroke();
let html = '';
for (const sheet of tileSheets) {
const name = sheet.name || sheet.path?.split('/').pop() || `Sheet ${sheet.id}`;
html += `
<div class="sheet-section" data-sheet-id="${sheet.id}">
<div class="sheet-header ${expandedSheets[sheet.id] ? 'expanded' : ''}" onclick="toggleSheet(${sheet.id})">
<span class="text-white text-sm">${name}</span>
<span class="text-gray-400 text-xs">${expandedSheets[sheet.id] ? '▼' : '▶'}</span>
</div>
<div class="sheet-tiles ${expandedSheets[sheet.id] ? '' : 'hidden'}" id="sheetTiles_${sheet.id}"></div>
</div>
`;
}
container.innerHTML = html;
// Render expanded sheets
for (const sheetId of Object.keys(expandedSheets)) {
if (expandedSheets[sheetId]) renderSheetTiles(parseInt(sheetId));
}
}
function toggleSheet(sheetId) {
expandedSheets[sheetId] = !expandedSheets[sheetId];
buildSheetList();
if (expandedSheets[sheetId]) renderSheetTiles(sheetId);
}
function renderSheetTiles(sheetId) {
const sheet = tileSheets.find(s => s.id === sheetId);
const texture = sheetTextures[sheetId];
const container = document.getElementById(`sheetTiles_${sheetId}`);
if (!sheet || !texture || !container) return;
const cols = Math.floor(sheet.sheetW / sheet.tileW);
const rows = Math.floor(sheet.sheetH / sheet.tileH);
const totalTiles = cols * rows;
const cellSize = Math.min(32, Math.floor(280 / cols));
let html = `<div class="tile-grid" style="grid-template-columns: repeat(${cols}, ${cellSize}px);">`;
for (let i = 0; i < totalTiles; i++) {
const isSelected = sheetId === selectedSheetId && i === selectedFrameIndex;
html += `<canvas class="tile-cell ${isSelected ? 'selected' : ''}" width="${cellSize}" height="${cellSize}"
data-sheet="${sheetId}" data-frame="${i}" onclick="selectTile(${sheetId}, ${i})"></canvas>`;
}
html += '</div>';
container.innerHTML = html;
// Draw tiles
container.querySelectorAll('.tile-cell').forEach(canvas => {
const frame = parseInt(canvas.dataset.frame);
const ctx = canvas.getContext('2d');
ctx.imageSmoothingEnabled = false;
const srcX = (frame % cols) * sheet.tileW;
const srcY = Math.floor(frame / cols) * sheet.tileH;
ctx.drawImage(texture, srcX, srcY, sheet.tileW, sheet.tileH, 0, 0, cellSize, cellSize);
});
}
function selectTile(sheetId, frameIndex) {
selectedSheetId = sheetId;
selectedFrameIndex = frameIndex;
const sheet = tileSheets.find(s => s.id === sheetId);
const texture = sheetTextures[sheetId];
// Update drawer preview
if (sheet && texture) {
const cols = Math.floor(sheet.sheetW / sheet.tileW);
const srcX = (frameIndex % cols) * sheet.tileW;
const srcY = Math.floor(frameIndex / cols) * sheet.tileH;
const drawerCanvas = document.getElementById('drawerPreview');
const dCtx = drawerCanvas.getContext('2d');
dCtx.imageSmoothingEnabled = false;
dCtx.clearRect(0, 0, 48, 48);
dCtx.drawImage(texture, srcX, srcY, sheet.tileW, sheet.tileH, 0, 0, 48, 48);
const mainCanvas = document.getElementById('previewCanvas');
const mCtx = mainCanvas.getContext('2d');
mCtx.imageSmoothingEnabled = false;
mCtx.clearRect(0, 0, 32, 32);
mCtx.drawImage(texture, srcX, srcY, sheet.tileW, sheet.tileH, 0, 0, 32, 32);
const name = sheet.name || sheet.path?.split('/').pop() || `Sheet ${sheetId}`;
document.getElementById('drawerTileName').textContent = name;
document.getElementById('drawerTileInfo').textContent = `Frame ${frameIndex}`;
document.getElementById('selectedTileName').textContent = `${name} #${frameIndex}`;
}
// Update selection visuals
document.querySelectorAll('.tile-cell').forEach(el => el.classList.remove('selected'));
event?.target?.classList.add('selected');
// Auto-switch to tile mode
setEditMode('tile');
}
// ==================== ZOOM ====================
@@ -369,227 +460,110 @@ else
function zoomIn() { zoom = Math.min(maxZoom, zoom * 1.25); applyZoom(); }
function zoomOut() { zoom = Math.max(minZoom, zoom / 1.25); applyZoom(); }
function zoomFit() {
const viewport = document.getElementById('mapViewport');
const fitZoom = Math.min(viewport.clientWidth / (mapWidth * tileSize), viewport.clientHeight / (mapHeight * tileSize), 1);
zoom = Math.max(minZoom, fitZoom * 0.95);
const vp = document.getElementById('mapViewport');
zoom = Math.max(minZoom, Math.min(vp.clientWidth / (mapWidth * tileSize), vp.clientHeight / (mapHeight * tileSize), 1) * 0.95);
applyZoom();
}
// ==================== CANVAS EVENTS ====================
function setupCanvasEvents(canvas) {
canvas.oncontextmenu = (e) => {
canvas.oncontextmenu = e => {
e.preventDefault();
const pos = getTilePos(e);
document.getElementById('spawnX').value = pos.x * tileSize + tileSize/2;
document.getElementById('spawnY').value = pos.y * tileSize + tileSize/2;
};
canvas.onmousedown = (e) => {
canvas.onmousedown = e => {
if (e.button !== 0) return;
const pos = getTilePos(e);
if (teleportMode && selectedPlayerId) {
teleportPlayer(pos.x * tileSize + tileSize/2, pos.y * tileSize + tileSize/2);
teleportMode = false;
document.getElementById('teleportBtn').classList.remove('btn-primary');
return;
}
if (editMode === 'none') return;
isDrawing = true;
paintTile(pos.x, pos.y);
};
canvas.onmousemove = (e) => {
if (!isDrawing || editMode === 'none') return;
const pos = getTilePos(e);
paintTile(pos.x, pos.y);
};
canvas.onmouseup = () => { isDrawing = false; };
canvas.onmouseleave = () => { isDrawing = false; };
canvas.onmousemove = e => { if (isDrawing && editMode !== 'none') paintTile(getTilePos(e).x, getTilePos(e).y); };
canvas.onmouseup = () => isDrawing = false;
canvas.onmouseleave = () => isDrawing = false;
}
function getTilePos(e) {
const canvas = document.getElementById('mapCanvas');
const rect = canvas.getBoundingClientRect();
return {
x: Math.floor((e.clientX - rect.left) / (tileSize * zoom)),
y: Math.floor((e.clientY - rect.top) / (tileSize * zoom))
};
const rect = document.getElementById('mapCanvas').getBoundingClientRect();
return { x: Math.floor((e.clientX - rect.left) / (tileSize * zoom)), y: Math.floor((e.clientY - rect.top) / (tileSize * zoom)) };
}
// ==================== TILE EDITING ====================
// ==================== EDIT MODE ====================
function setEditMode(mode) {
editMode = mode;
document.querySelectorAll('[id^="mode"]').forEach(b => b.classList.remove('active'));
document.getElementById('mode' + mode.charAt(0).toUpperCase() + mode.slice(1))?.classList.add('active');
document.getElementById('mapCanvas').classList.toggle('edit-mode', mode !== 'none');
const preview = document.getElementById('selectedTilePreview');
preview.classList.toggle('hidden', mode !== 'tile');
if (mode === 'tile' && selectedSheetId === 0) openTilePicker();
const hints = { none: 'Click entities to inspect', floor: 'Click to place floor', wall: 'Click to place wall',
tile: 'Click to place selected tile', template: 'Click to place template', erase: 'Click to remove tiles' };
document.getElementById('editHint').textContent = hints[mode] || '';
document.getElementById('selectedTileInfo').classList.toggle('hidden', mode !== 'tile');
}
async function paintTile(x, y) {
if (x < 0 || x >= mapWidth || y < 0 || y >= mapHeight) return;
let body = { id: dungeonId, x, y };
let handler = '';
let handler = '', params = `id=${dungeonId}&x=${x}&y=${y}`;
if (editMode === 'floor') {
handler = 'SetTile';
body.walkable = true;
handler = 'SetTile'; params += '&walkable=true';
walkableData[y * mapWidth + x] = true;
} else if (editMode === 'wall') {
handler = 'SetTile';
body.walkable = false;
handler = 'SetTile'; params += '&walkable=false';
walkableData[y * mapWidth + x] = false;
} else if (editMode === 'tile') {
} else if (editMode === 'tile' && selectedSheetId > 0) {
handler = 'PlaceVisualTile';
body.sheetId = selectedSheetId;
body.frameIndex = selectedFrameIndex;
body.layer = parseInt(document.getElementById('tileLayer').value);
body.walkable = document.getElementById('tileWalkable').checked;
walkableData[y * mapWidth + x] = body.walkable;
// Update local visual tiles
const existing = visualTiles.findIndex(t => t.x === x && t.y === y && t.l === body.layer);
const newTile = { x, y, sid: selectedSheetId, frame: selectedFrameIndex, l: body.layer };
if (existing >= 0) visualTiles[existing] = newTile;
else visualTiles.push(newTile);
const layer = parseInt(document.getElementById('tileLayer').value);
const walkable = document.getElementById('tileWalkable').checked;
params += `&sheetId=${selectedSheetId}&frameIndex=${selectedFrameIndex}&layer=${layer}&walkable=${walkable}`;
walkableData[y * mapWidth + x] = walkable;
const idx = visualTiles.findIndex(t => t.x === x && t.y === y && t.l === layer);
const tile = { x, y, sid: selectedSheetId, frame: selectedFrameIndex, l: layer };
if (idx >= 0) visualTiles[idx] = tile; else visualTiles.push(tile);
} else if (editMode === 'erase') {
handler = 'RemoveTile';
visualTiles = visualTiles.filter(t => t.x !== x || t.y !== y);
walkableData[y * mapWidth + x] = false;
} else return;
// Redraw immediately for responsiveness
drawMap();
// Send to server
const params = new URLSearchParams(body).toString();
await fetch(`/admin/dungeons/view?handler=${handler}&${params}`, {
method: 'POST',
headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
method: 'POST', headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
});
}
// ==================== TILE PICKER ====================
function openTilePicker() {
document.getElementById('tilePickerModal').classList.remove('hidden');
const list = document.getElementById('sheetList');
list.innerHTML = tileSheets.map(s =>
`<div class="sheet-item ${s.id === selectedSheetId ? 'selected' : ''}" onclick="selectSheet(${s.id})">${s.name || 'Sheet ' + s.id}</div>`
).join('');
if (selectedSheetId > 0) showSheetTiles(selectedSheetId);
}
function closeTilePicker() {
document.getElementById('tilePickerModal').classList.add('hidden');
}
function selectSheet(sheetId) {
selectedSheetId = sheetId;
document.querySelectorAll('.sheet-item').forEach(el => el.classList.remove('selected'));
event.target.classList.add('selected');
showSheetTiles(sheetId);
}
function showSheetTiles(sheetId) {
const sheet = tileSheets.find(s => s.id === sheetId);
const texture = sheetTextures[sheetId];
if (!sheet || !texture) return;
const cols = Math.floor(sheet.sheetW / sheet.tileW);
const rows = Math.floor(sheet.sheetH / sheet.tileH);
const container = document.getElementById('tileGridContainer');
// Create canvas for each tile
let html = `<div class="tile-grid" style="grid-template-columns: repeat(${cols}, ${sheet.tileW}px);">`;
for (let i = 0; i < cols * rows; i++) {
html += `<canvas class="tile-cell ${i === selectedFrameIndex && sheetId === selectedSheetId ? 'selected' : ''}"
width="${sheet.tileW}" height="${sheet.tileH}" data-frame="${i}" onclick="selectTile(${sheetId}, ${i})"></canvas>`;
}
html += '</div>';
container.innerHTML = html;
// Draw tiles
container.querySelectorAll('.tile-cell').forEach(canvas => {
const frame = parseInt(canvas.dataset.frame);
const ctx = canvas.getContext('2d');
ctx.imageSmoothingEnabled = false;
const srcX = (frame % cols) * sheet.tileW;
const srcY = Math.floor(frame / cols) * sheet.tileH;
ctx.drawImage(texture, srcX, srcY, sheet.tileW, sheet.tileH, 0, 0, sheet.tileW, sheet.tileH);
});
}
function selectTile(sheetId, frameIndex) {
selectedSheetId = sheetId;
selectedFrameIndex = frameIndex;
document.querySelectorAll('.tile-cell').forEach(el => el.classList.remove('selected'));
event.target.classList.add('selected');
// Update preview
const sheet = tileSheets.find(s => s.id === sheetId);
const texture = sheetTextures[sheetId];
if (sheet && texture) {
const canvas = document.getElementById('previewCanvas');
const ctx = canvas.getContext('2d');
ctx.imageSmoothingEnabled = false;
ctx.clearRect(0, 0, 32, 32);
const cols = Math.floor(sheet.sheetW / sheet.tileW);
const srcX = (frameIndex % cols) * sheet.tileW;
const srcY = Math.floor(frameIndex / cols) * sheet.tileH;
ctx.drawImage(texture, srcX, srcY, sheet.tileW, sheet.tileH, 0, 0, 32, 32);
document.getElementById('selectedTileName').textContent = sheet.name || 'Sheet ' + sheetId;
document.getElementById('selectedTileInfo').textContent = `Frame ${frameIndex}`;
}
closeTilePicker();
setEditMode('tile');
}
// ==================== ENTITIES ====================
function updateEntities(players, mobs) {
currentPlayers = players;
currentMobs = mobs;
currentPlayers = players; currentMobs = mobs;
const layer = document.getElementById('entityLayer');
layer.innerHTML = '';
players.forEach(p => {
const div = document.createElement('div');
div.className = 'entity-dot player-dot' + (p.id == selectedPlayerId ? ' selected' : '');
div.style.left = p.x + 'px';
div.style.top = p.y + 'px';
div.title = p.name;
div.onclick = () => selectPlayer(p);
div.style.left = p.x + 'px'; div.style.top = p.y + 'px';
div.title = p.name; div.onclick = () => selectPlayer(p);
layer.appendChild(div);
});
mobs.filter(m => m.alive).forEach(m => {
const div = document.createElement('div');
div.className = 'entity-dot ' + (m.isBoss ? 'boss-dot' : 'mob-dot') + (m.id == selectedMobId ? ' selected' : '');
div.style.left = m.x + 'px';
div.style.top = m.y + 'px';
div.title = m.name;
div.onclick = () => selectMob(m);
div.style.left = m.x + 'px'; div.style.top = m.y + 'px';
div.title = m.name; div.onclick = () => selectMob(m);
layer.appendChild(div);
});
}
// ==================== PLAYER/MOB INSPECTION (simplified) ====================
function selectPlayer(p) {
selectedPlayerId = p.id; selectedMobId = null; closeMobInspector();
document.getElementById('playerInspector').classList.remove('hidden');
@@ -601,7 +575,6 @@ else
}
function closePlayerInspector() { selectedPlayerId = null; document.getElementById('playerInspector').classList.add('hidden'); updateEntities(currentPlayers, currentMobs); }
function selectMob(m) {
selectedMobId = m.id; selectedPlayerId = null; closePlayerInspector();
document.getElementById('mobInspector').classList.remove('hidden');
@@ -612,9 +585,10 @@ else
<div class="inspector-stat"><span class="text-gray-400">State</span><span>${m.state}</span></div>`;
updateEntities(currentPlayers, currentMobs);
}
function closeMobInspector() { selectedMobId = null; document.getElementById('mobInspector').classList.add('hidden'); updateEntities(currentPlayers, currentMobs); }
// ==================== ACTIONS ====================
async function healSelectedPlayer() {
if (!selectedPlayerId) return;
await fetch(`/admin/dungeons/view?handler=HealPlayer&id=${dungeonId}&playerId=${selectedPlayerId}`, {
@@ -635,11 +609,11 @@ else
await fetch(`/admin/dungeons/view?handler=SetGodMode&id=${dungeonId}&playerId=${selectedPlayerId}&enabled=${godModeEnabled}`, {
method: 'POST', headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
});
document.getElementById('godModeBtn').textContent = godModeEnabled ? '🛡️ GOD ON' : '🛡️ God';
document.getElementById('godModeBtn').textContent = godModeEnabled ? '🛡️ ON' : '🛡️ God';
}
async function killSelectedPlayer() {
if (!confirm('Kill player?')) return;
if (!confirm('Kill?')) return;
await fetch(`/admin/dungeons/view?handler=KillPlayer&id=${dungeonId}&playerId=${selectedPlayerId}`, {
method: 'POST', headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
});
@@ -660,23 +634,20 @@ else
async function spawnMob() {
const mobDefId = document.getElementById('spawnMobSelect').value;
const x = document.getElementById('spawnX').value;
const y = document.getElementById('spawnY').value;
if (!mobDefId) return alert('Select a mob');
const x = document.getElementById('spawnX').value, y = document.getElementById('spawnY').value;
await fetch(`/admin/dungeons/view?handler=SpawnMob&id=${dungeonId}&mobDefId=${mobDefId}&x=${x}&y=${y}`, {
method: 'POST', headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
});
}
async function broadcastTileUpdate() {
async function broadcastTiles() {
await fetch(`/admin/dungeons/view?handler=BroadcastTiles&id=${dungeonId}`, {
method: 'POST', headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
});
alert('Tile update broadcast sent!');
alert('Tile update queued for broadcast!');
}
// ==================== AUTO REFRESH ====================
async function fetchUpdate() {
try {
const resp = await fetch(`/admin/dungeons/view?handler=Status&id=${dungeonId}`);
@@ -697,12 +668,6 @@ else
else clearInterval(refreshInterval);
}
// ==================== INIT ====================
document.addEventListener('DOMContentLoaded', () => {
initMap();
updateEntities(@Html.Raw(Model.PlayersJson), @Html.Raw(Model.MobsJson));
refreshInterval = setInterval(fetchUpdate, 500);
});
document.addEventListener('DOMContentLoaded', init);
</script>
}
+17 -6
View File
@@ -37,6 +37,23 @@ public class ViewModel : AdminPageModel
MobDefinitions = await _db.DungeonMobDefinitions
.Where(m => m.IsEnabled).OrderBy(m => m.Name).ToListAsync();
// Load ALL available tile sheets from database (not just those in dungeon)
var allSheets = await _db.Set<TileMapSheet>()
.Where(s => s.IsEnabled)
.OrderBy(s => s.Name)
.ToListAsync();
TileSheetsJson = JsonSerializer.Serialize(allSheets.Select(s => new {
id = s.Id,
name = s.Name,
path = s.CdnPath,
tileW = s.TileWidth,
tileH = s.TileHeight,
sheetW = s.SheetWidth,
sheetH = s.SheetHeight,
cols = s.Columns
}));
if (Dungeon == null) return;
Duration = FormatDuration(DateTime.UtcNow - Dungeon.CreatedAt);
@@ -58,12 +75,6 @@ public class ViewModel : AdminPageModel
x = t.X, y = t.Y, sid = t.SheetId, frame = t.FrameIndex,
l = t.Layer, r = t.Rotation, fx = t.FlipX, fy = t.FlipY
}));
TileSheetsJson = JsonSerializer.Serialize(layout.TileMapSheets.Select(s => new {
id = s.Id, name = s.CdnPath?.Split('/').LastOrDefault() ?? $"Sheet {s.Id}",
path = s.CdnPath, tileW = s.TileWidth, tileH = s.TileHeight,
sheetW = s.SheetWidth, sheetH = s.SheetHeight, cols = s.Columns
}));
}
else { MapWidth = 100; MapHeight = 100; }