+
+
+
+
+
+
+
Select a sheet to view tiles
+
@@ -332,375 +257,426 @@ else
const dungeonId = '@Model.Dungeon?.Id';
const mapWidth = @(Model.MapWidth);
const mapHeight = @(Model.MapHeight);
- let walkableData = @Html.Raw(Model.WalkableJson);
const tileSize = 32;
+ let walkableData = @Html.Raw(Model.WalkableJson);
+ let visualTiles = @Html.Raw(Model.VisualTilesJson);
+ let tileSheets = @Html.Raw(Model.TileSheetsJson);
let autoRefresh = true;
let refreshInterval;
- let mapScale = 4;
+ let zoom = 1.0;
+ const minZoom = 0.25, maxZoom = 4.0;
// Selection state
- let selectedMobId = null;
- let selectedPlayerId = null;
- let currentMobs = [];
- let currentPlayers = [];
+ let selectedMobId = null, selectedPlayerId = null;
+ let currentMobs = [], currentPlayers = [];
- // Edit mode
- let editMode = 'none'; // none, floor, wall, fill
+ // Edit state
+ let editMode = 'none';
let isDrawing = false;
- let fillStartX = -1, fillStartY = -1;
- let teleportMode = false;
- let godModeEnabled = false;
+ let teleportMode = false, godModeEnabled = false;
+
+ // Tile painting state
+ let selectedSheetId = 0, selectedFrameIndex = 0;
+ let sheetTextures = {}; // sheet_id -> Image
+
+ // ==================== INITIALIZATION ====================
function initMap() {
const canvas = document.getElementById('mapCanvas');
- const container = document.getElementById('mapContainer');
- if (!canvas || !container) return;
+ const viewport = document.getElementById('mapViewport');
+ const entityLayer = document.getElementById('entityLayer');
- const ctx = canvas.getContext('2d');
- mapScale = Math.min(
- (container.clientWidth - 20) / mapWidth,
- (container.clientHeight - 20) / mapHeight,
- 8
- );
+ canvas.width = mapWidth * tileSize;
+ canvas.height = mapHeight * tileSize;
+ entityLayer.style.width = canvas.width + 'px';
+ entityLayer.style.height = canvas.height + 'px';
- canvas.width = mapWidth * mapScale;
- canvas.height = mapHeight * mapScale;
- canvas.style.width = canvas.width + 'px';
- canvas.style.height = canvas.height + 'px';
-
- drawMap(ctx);
+ applyZoom();
+ loadSheetTextures().then(() => drawMap());
setupCanvasEvents(canvas);
}
- function drawMap(ctx) {
+ 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
for (let y = 0; y < mapHeight; y++) {
for (let x = 0; x < mapWidth; x++) {
const idx = y * mapWidth + x;
- const walkable = walkableData[idx];
- ctx.fillStyle = walkable ? '#1e3a5f' : '#1a1a2e';
- ctx.fillRect(x * mapScale, y * mapScale, mapScale, mapScale);
- ctx.strokeStyle = 'rgba(255,255,255,0.03)';
- ctx.strokeRect(x * mapScale, y * mapScale, mapScale, mapScale);
+ ctx.fillStyle = walkableData[idx] ? '#1e3a5f' : '#1a1a2e';
+ ctx.fillRect(x * tileSize, y * tileSize, tileSize, tileSize);
}
}
+
+ // Draw 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 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();
+ }
+
+ // Draw 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 y = 0; y <= mapHeight; y++) {
+ ctx.beginPath(); ctx.moveTo(0, y * tileSize); ctx.lineTo(mapWidth * tileSize, y * tileSize); ctx.stroke();
+ }
}
+ // ==================== ZOOM ====================
+
+ function applyZoom() {
+ const canvas = document.getElementById('mapCanvas');
+ const entityLayer = document.getElementById('entityLayer');
+ canvas.style.transform = `scale(${zoom})`;
+ canvas.style.transformOrigin = 'top left';
+ entityLayer.style.transform = `scale(${zoom})`;
+ entityLayer.style.transformOrigin = 'top left';
+ document.getElementById('zoomLevel').textContent = Math.round(zoom * 100) + '%';
+ }
+
+ 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);
+ applyZoom();
+ }
+
+ // ==================== CANVAS EVENTS ====================
+
function setupCanvasEvents(canvas) {
canvas.oncontextmenu = (e) => {
e.preventDefault();
- const rect = canvas.getBoundingClientRect();
- const x = Math.floor((e.clientX - rect.left) / mapScale) * tileSize + tileSize / 2;
- const y = Math.floor((e.clientY - rect.top) / mapScale) * tileSize + tileSize / 2;
- document.getElementById('spawnX').value = Math.round(x);
- document.getElementById('spawnY').value = Math.round(y);
+ 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) => {
if (e.button !== 0) return;
- const rect = canvas.getBoundingClientRect();
- const tileX = Math.floor((e.clientX - rect.left) / mapScale);
- const tileY = Math.floor((e.clientY - rect.top) / mapScale);
+ const pos = getTilePos(e);
if (teleportMode && selectedPlayerId) {
- teleportPlayer(tileX * tileSize + tileSize / 2, tileY * tileSize + tileSize / 2);
+ teleportPlayer(pos.x * tileSize + tileSize/2, pos.y * tileSize + tileSize/2);
teleportMode = false;
document.getElementById('teleportBtn').classList.remove('btn-primary');
- document.getElementById('teleportBtn').classList.add('btn-secondary');
return;
}
if (editMode === 'none') return;
-
- if (editMode === 'fill') {
- fillStartX = tileX;
- fillStartY = tileY;
- isDrawing = true;
- } else {
- isDrawing = true;
- paintTile(tileX, tileY);
- }
+ isDrawing = true;
+ paintTile(pos.x, pos.y);
};
canvas.onmousemove = (e) => {
- if (!isDrawing) return;
- const rect = canvas.getBoundingClientRect();
- const tileX = Math.floor((e.clientX - rect.left) / mapScale);
- const tileY = Math.floor((e.clientY - rect.top) / mapScale);
-
- if (editMode === 'fill') {
- showFillPreview(fillStartX, fillStartY, tileX, tileY);
- } else if (editMode !== 'none') {
- paintTile(tileX, tileY);
- }
+ if (!isDrawing || editMode === 'none') return;
+ const pos = getTilePos(e);
+ paintTile(pos.x, pos.y);
};
- canvas.onmouseup = (e) => {
- if (!isDrawing) return;
- isDrawing = false;
-
- if (editMode === 'fill' && fillStartX >= 0) {
- const rect = canvas.getBoundingClientRect();
- const tileX = Math.floor((e.clientX - rect.left) / mapScale);
- const tileY = Math.floor((e.clientY - rect.top) / mapScale);
- fillRect(fillStartX, fillStartY, tileX, tileY);
- hideFillPreview();
- fillStartX = -1;
- fillStartY = -1;
- }
- };
-
- canvas.onmouseleave = () => {
- isDrawing = false;
- hideFillPreview();
+ 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))
};
}
+ // ==================== TILE EDITING ====================
+
function setEditMode(mode) {
editMode = mode;
- document.querySelectorAll('.tool-btn').forEach(b => b.classList.remove('active'));
- document.getElementById('edit' + mode.charAt(0).toUpperCase() + mode.slice(1))?.classList.add('active');
+ 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 canvas = document.getElementById('mapCanvas');
- canvas.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] || '';
}
async function paintTile(x, y) {
if (x < 0 || x >= mapWidth || y < 0 || y >= mapHeight) return;
- const walkable = editMode === 'floor';
- try {
- const resp = await fetch(`/admin/dungeons/view?handler=SetTile&id=${dungeonId}&x=${x}&y=${y}&walkable=${walkable}`, {
- method: 'POST',
- headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
- });
- if (resp.ok) {
- walkableData[y * mapWidth + x] = walkable;
- const ctx = document.getElementById('mapCanvas').getContext('2d');
- ctx.fillStyle = walkable ? '#1e3a5f' : '#1a1a2e';
- ctx.fillRect(x * mapScale, y * mapScale, mapScale, mapScale);
- }
- } catch (e) { console.error('Paint failed:', e); }
+ let body = { id: dungeonId, x, y };
+ let handler = '';
+
+ if (editMode === 'floor') {
+ handler = 'SetTile';
+ body.walkable = true;
+ walkableData[y * mapWidth + x] = true;
+ } else if (editMode === 'wall') {
+ handler = 'SetTile';
+ body.walkable = false;
+ walkableData[y * mapWidth + x] = false;
+ } else if (editMode === 'tile') {
+ 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);
+ } 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 }
+ });
}
- async function fillRect(x1, y1, x2, y2) {
- const walkable = editMode === 'fill' ? true : editMode === 'floor';
- try {
- const resp = await fetch(`/admin/dungeons/view?handler=FillRect&id=${dungeonId}&x1=${x1}&y1=${y1}&x2=${x2}&y2=${y2}&walkable=${walkable}`, {
- method: 'POST',
- headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
- });
- if (resp.ok) {
- // Update local data and redraw
- const minX = Math.min(x1, x2), maxX = Math.max(x1, x2);
- const minY = Math.min(y1, y2), maxY = Math.max(y1, y2);
- const ctx = document.getElementById('mapCanvas').getContext('2d');
- for (let x = minX; x <= maxX; x++) {
- for (let y = minY; y <= maxY; y++) {
- if (x >= 0 && x < mapWidth && y >= 0 && y < mapHeight) {
- walkableData[y * mapWidth + x] = walkable;
- ctx.fillStyle = walkable ? '#1e3a5f' : '#1a1a2e';
- ctx.fillRect(x * mapScale, y * mapScale, mapScale, mapScale);
- }
- }
- }
- }
- } catch (e) { console.error('Fill failed:', e); }
+ // ==================== TILE PICKER ====================
+
+ function openTilePicker() {
+ document.getElementById('tilePickerModal').classList.remove('hidden');
+ const list = document.getElementById('sheetList');
+ list.innerHTML = tileSheets.map(s =>
+ `
${s.name || 'Sheet ' + s.id}
`
+ ).join('');
+ if (selectedSheetId > 0) showSheetTiles(selectedSheetId);
}
- function showFillPreview(x1, y1, x2, y2) {
- const preview = document.getElementById('editPreview');
- const minX = Math.min(x1, x2), maxX = Math.max(x1, x2);
- const minY = Math.min(y1, y2), maxY = Math.max(y1, y2);
- preview.style.left = (minX * mapScale) + 'px';
- preview.style.top = (minY * mapScale) + 'px';
- preview.style.width = ((maxX - minX + 1) * mapScale) + 'px';
- preview.style.height = ((maxY - minY + 1) * mapScale) + 'px';
- preview.classList.remove('hidden');
+ function closeTilePicker() {
+ document.getElementById('tilePickerModal').classList.add('hidden');
}
- function hideFillPreview() {
- document.getElementById('editPreview').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 = `
`;
+ for (let i = 0; i < cols * rows; i++) {
+ html += ``;
+ }
+ html += '
';
+ 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;
- const overlay = document.getElementById('entityOverlay');
- overlay.innerHTML = '';
- overlay.style.pointerEvents = 'none';
+ 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 / tileSize * mapScale) + 'px';
- div.style.top = (p.y / tileSize * mapScale) + 'px';
- div.style.pointerEvents = 'auto';
+ div.style.left = p.x + 'px';
+ div.style.top = p.y + 'px';
div.title = p.name;
- div.onclick = (e) => { e.stopPropagation(); selectPlayer(p); };
- overlay.appendChild(div);
+ div.onclick = () => selectPlayer(p);
+ layer.appendChild(div);
});
- mobs.forEach(m => {
- if (!m.alive) return;
+ 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 / tileSize * mapScale) + 'px';
- div.style.top = (m.y / tileSize * mapScale) + 'px';
- div.style.pointerEvents = 'auto';
+ div.style.left = m.x + 'px';
+ div.style.top = m.y + 'px';
div.title = m.name;
- div.onclick = (e) => { e.stopPropagation(); selectMob(m); };
- overlay.appendChild(div);
+ div.onclick = () => selectMob(m);
+ layer.appendChild(div);
});
}
- // Player inspection
- function selectPlayer(player) {
- selectedPlayerId = player.id;
- selectedMobId = null;
- closeMobInspector();
-
+ // ==================== PLAYER/MOB INSPECTION (simplified) ====================
+
+ function selectPlayer(p) {
+ selectedPlayerId = p.id; selectedMobId = null; closeMobInspector();
document.getElementById('playerInspector').classList.remove('hidden');
- document.getElementById('playerInspectorName').textContent = player.name;
-
- const healthPct = player.maxHealth > 0 ? Math.round(player.health / player.maxHealth * 100) : 0;
+ document.getElementById('playerInspectorName').textContent = p.name;
document.getElementById('playerInspectorContent').innerHTML = `
-
ID${player.id}
-
Health${Math.round(player.health)} / ${Math.round(player.maxHealth)} (${healthPct}%)
-
Mana${Math.round(player.mana || 0)} / ${Math.round(player.maxMana || 0)}
-
Position${Math.round(player.x)}, ${Math.round(player.y)}
-
Alive${player.isAlive ? 'Yes' : 'No'}
-
In Combat${player.isInCombat ? 'Yes' : 'No'}
- `;
-
+
Health${Math.round(p.health)}/${Math.round(p.maxHealth)}
+
Position${Math.round(p.x)}, ${Math.round(p.y)}
`;
updateEntities(currentPlayers, currentMobs);
}
- function selectPlayerById(id) {
- const player = currentPlayers.find(p => p.id == id);
- if (player) selectPlayer(player);
- }
+ function closePlayerInspector() { selectedPlayerId = null; document.getElementById('playerInspector').classList.add('hidden'); updateEntities(currentPlayers, currentMobs); }
- function closePlayerInspector() {
- selectedPlayerId = null;
- document.getElementById('playerInspector').classList.add('hidden');
+ function selectMob(m) {
+ selectedMobId = m.id; selectedPlayerId = null; closePlayerInspector();
+ document.getElementById('mobInspector').classList.remove('hidden');
+ document.getElementById('mobInspectorName').textContent = m.name;
+ document.getElementById('mobInspectorContent').innerHTML = `
+
Health${m.health}/${m.maxHealth}
+
Position${Math.round(m.x)}, ${Math.round(m.y)}
+
State${m.state}
`;
updateEntities(currentPlayers, currentMobs);
}
+ function closeMobInspector() { selectedMobId = null; document.getElementById('mobInspector').classList.add('hidden'); updateEntities(currentPlayers, currentMobs); }
+
async function healSelectedPlayer() {
if (!selectedPlayerId) return;
- try {
- await fetch(`/admin/dungeons/view?handler=HealPlayer&id=${dungeonId}&playerId=${selectedPlayerId}`, {
- method: 'POST',
- headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
- });
- fetchUpdate();
- } catch (e) { alert('Failed to heal player'); }
+ await fetch(`/admin/dungeons/view?handler=HealPlayer&id=${dungeonId}&playerId=${selectedPlayerId}`, {
+ method: 'POST', headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
+ });
}
- function teleportPlayerToClick() {
- if (!selectedPlayerId) return;
- teleportMode = true;
- document.getElementById('teleportBtn').classList.add('btn-primary');
- document.getElementById('teleportBtn').classList.remove('btn-secondary');
- alert('Click on the map to teleport player');
- }
+ function teleportPlayerToClick() { teleportMode = true; document.getElementById('teleportBtn').classList.add('btn-primary'); }
async function teleportPlayer(x, y) {
- if (!selectedPlayerId) return;
- try {
- await fetch(`/admin/dungeons/view?handler=TeleportPlayer&id=${dungeonId}&playerId=${selectedPlayerId}&x=${x}&y=${y}`, {
- method: 'POST',
- headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
- });
- fetchUpdate();
- } catch (e) { alert('Failed to teleport'); }
+ await fetch(`/admin/dungeons/view?handler=TeleportPlayer&id=${dungeonId}&playerId=${selectedPlayerId}&x=${x}&y=${y}`, {
+ method: 'POST', headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
+ });
}
async function toggleGodMode() {
- if (!selectedPlayerId) return;
godModeEnabled = !godModeEnabled;
- try {
- 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 Mode ON' : '🛡️ God Mode';
- document.getElementById('godModeBtn').classList.toggle('btn-primary', godModeEnabled);
- } catch (e) { alert('Failed to toggle god mode'); }
+ 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';
}
async function killSelectedPlayer() {
- if (!selectedPlayerId || !confirm('Kill this player?')) return;
- try {
- await fetch(`/admin/dungeons/view?handler=KillPlayer&id=${dungeonId}&playerId=${selectedPlayerId}`, {
- method: 'POST',
- headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
- });
- closePlayerInspector();
- fetchUpdate();
- } catch (e) { alert('Failed to kill player'); }
- }
-
- // Mob inspection
- function selectMob(mob) {
- selectedMobId = mob.id;
- selectedPlayerId = null;
+ if (!confirm('Kill player?')) return;
+ await fetch(`/admin/dungeons/view?handler=KillPlayer&id=${dungeonId}&playerId=${selectedPlayerId}`, {
+ method: 'POST', headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
+ });
closePlayerInspector();
-
- document.getElementById('mobInspector').classList.remove('hidden');
- document.getElementById('mobInspectorName').textContent = mob.name + (mob.isBoss ? ' ⭐' : '');
- document.getElementById('mobInspectorContent').innerHTML = `
-
ID${mob.id}
-
Health${mob.health} / ${mob.maxHealth}
-
Position${Math.round(mob.x)}, ${Math.round(mob.y)}
-
State${mob.state}
-
Type${mob.type}
- `;
- updateEntities(currentPlayers, currentMobs);
- }
-
- function closeMobInspector() {
- selectedMobId = null;
- document.getElementById('mobInspector').classList.add('hidden');
- updateEntities(currentPlayers, currentMobs);
}
async function killSelectedMob() {
- if (!selectedMobId) return;
- try {
- await fetch(`/admin/dungeons/view?handler=KillMob&id=${dungeonId}&mobId=${selectedMobId}`, {
- method: 'POST',
- headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
- });
- closeMobInspector();
- fetchUpdate();
- } catch (e) { alert('Failed to kill mob'); }
+ await fetch(`/admin/dungeons/view?handler=KillMob&id=${dungeonId}&mobId=${selectedMobId}`, {
+ method: 'POST', headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
+ });
+ closeMobInspector();
}
function copyMobPosition() {
- const mob = currentMobs.find(m => m.id == selectedMobId);
- if (mob) {
- navigator.clipboard.writeText(`${Math.round(mob.x)}, ${Math.round(mob.y)}`);
- }
+ const m = currentMobs.find(m => m.id == selectedMobId);
+ if (m) navigator.clipboard.writeText(`${Math.round(m.x)}, ${Math.round(m.y)}`);
}
async function spawnMob() {
const mobDefId = document.getElementById('spawnMobSelect').value;
const x = document.getElementById('spawnX').value;
const y = document.getElementById('spawnY').value;
- if (!mobDefId) { alert('Select a mob'); return; }
-
- try {
- const resp = await fetch(`/admin/dungeons/view?handler=SpawnMob&id=${dungeonId}&mobDefId=${mobDefId}&x=${x}&y=${y}`, {
- method: 'POST',
- headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
- });
- if (resp.ok) fetchUpdate();
- else alert('Failed to spawn mob');
- } catch (e) { alert('Error spawning mob'); }
+ if (!mobDefId) return alert('Select a mob');
+ 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() {
+ await fetch(`/admin/dungeons/view?handler=BroadcastTiles&id=${dungeonId}`, {
+ method: 'POST', headers: { 'RequestVerificationToken': document.querySelector('[name="__RequestVerificationToken"]').value }
+ });
+ alert('Tile update broadcast sent!');
+ }
+
+ // ==================== AUTO REFRESH ====================
+
async function fetchUpdate() {
try {
const resp = await fetch(`/admin/dungeons/view?handler=Status&id=${dungeonId}`);
@@ -710,16 +686,6 @@ else
document.getElementById('mobCount').textContent = data.mobsAlive;
document.getElementById('duration').textContent = data.duration;
updateEntities(data.players, data.mobs);
-
- if (selectedPlayerId) {
- const p = data.players.find(x => x.id == selectedPlayerId);
- if (p) selectPlayer(p);
- }
- if (selectedMobId) {
- const m = data.mobs.find(x => x.id == selectedMobId);
- if (m && m.alive) selectMob(m);
- else closeMobInspector();
- }
}
} catch (e) { console.error('Update failed:', e); }
}
@@ -731,14 +697,12 @@ else
else clearInterval(refreshInterval);
}
+ // ==================== INIT ====================
+
document.addEventListener('DOMContentLoaded', () => {
initMap();
- const initialPlayers = @Html.Raw(Model.PlayersJson);
- const initialMobs = @Html.Raw(Model.MobsJson);
- updateEntities(initialPlayers, initialMobs);
+ updateEntities(@Html.Raw(Model.PlayersJson), @Html.Raw(Model.MobsJson));
refreshInterval = setInterval(fetchUpdate, 500);
});
-
- window.addEventListener('resize', initMap);
}
diff --git a/Services/Admin/Pages/Dungeons/View.cshtml.cs b/Services/Admin/Pages/Dungeons/View.cshtml.cs
index 847c8a3..48ef955 100644
--- a/Services/Admin/Pages/Dungeons/View.cshtml.cs
+++ b/Services/Admin/Pages/Dungeons/View.cshtml.cs
@@ -20,12 +20,14 @@ public class ViewModel : AdminPageModel
public GameServer.Dungeon.DungeonInstance? Dungeon { get; set; }
public string Duration { get; set; } = "";
- public int RoomCount { get; set; }
public int MapWidth { get; set; }
public int MapHeight { get; set; }
public string WalkableJson { get; set; } = "[]";
public string PlayersJson { get; set; } = "[]";
public string MobsJson { get; set; } = "[]";
+ public string VisualTilesJson { get; set; } = "[]";
+ public string TileSheetsJson { get; set; } = "[]";
+ public int VisualTileCount { get; set; }
public List
MobDefinitions { get; set; } = new();
public async Task OnGetAsync(Guid id)
@@ -33,14 +35,11 @@ public class ViewModel : AdminPageModel
Dungeon = _dungeonHandler.GetDungeon(id);
MobDefinitions = await _db.DungeonMobDefinitions
- .Where(m => m.IsEnabled)
- .OrderBy(m => m.Name)
- .ToListAsync();
+ .Where(m => m.IsEnabled).OrderBy(m => m.Name).ToListAsync();
if (Dungeon == null) return;
Duration = FormatDuration(DateTime.UtcNow - Dungeon.CreatedAt);
- RoomCount = Dungeon.LayoutV2?.Rooms?.Count ?? Dungeon.Simulation.Layout.Rooms.Count;
var layout = Dungeon.LayoutV2;
if (layout != null)
@@ -53,203 +52,139 @@ public class ViewModel : AdminPageModel
for (int x = 0; x < layout.Width; x++)
walkable.Add(layout.Walkable[x, y]);
WalkableJson = JsonSerializer.Serialize(walkable);
+
+ VisualTileCount = layout.TileDetails.Count;
+ VisualTilesJson = JsonSerializer.Serialize(layout.TileDetails.Select(t => new {
+ 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;
- WalkableJson = "[]";
- }
+ else { MapWidth = 100; MapHeight = 100; }
- PlayersJson = JsonSerializer.Serialize(
- Dungeon.Simulation.Players.Values.Select(p => new
- {
- id = p.CharacterId.ToString(),
- name = p.CharacterName,
- x = p.X,
- y = p.Y,
- health = p.Health,
- maxHealth = p.MaxHealth,
- mana = p.Mana,
- maxMana = p.MaxMana,
- isAlive = p.IsAlive,
- isInCombat = p.IsInCombat
- })
- );
+ PlayersJson = JsonSerializer.Serialize(Dungeon.Simulation.Players.Values.Select(p => new {
+ id = p.CharacterId.ToString(), name = p.CharacterName, x = p.X, y = p.Y,
+ health = p.Health, maxHealth = p.MaxHealth, isAlive = p.IsAlive
+ }));
- MobsJson = JsonSerializer.Serialize(
- Dungeon.Simulation.Mobs.Values.Select(m => new
- {
- id = m.Id,
- name = m.Name,
- x = m.X,
- y = m.Y,
- health = m.Health,
- maxHealth = m.MaxHealth,
- alive = m.IsAlive,
- isBoss = m.Type == DataServer.Data.Enums.MobType.Boss,
- type = m.Type.ToString(),
- state = m.State.ToString(),
- definitionId = m.DefinitionId
- })
- );
+ MobsJson = JsonSerializer.Serialize(Dungeon.Simulation.Mobs.Values.Select(m => new {
+ id = m.Id, name = m.Name, x = m.X, y = m.Y, health = m.Health, maxHealth = m.MaxHealth,
+ alive = m.IsAlive, isBoss = m.Type == DataServer.Data.Enums.MobType.Boss, state = m.State.ToString()
+ }));
}
public IActionResult OnGetStatus(Guid id)
{
var dungeon = _dungeonHandler.GetDungeon(id);
- if (dungeon == null)
- return new JsonResult(new { error = "Not found" }) { StatusCode = 404 };
+ if (dungeon == null) return new JsonResult(new { error = "Not found" }) { StatusCode = 404 };
- return new JsonResult(new
- {
+ return new JsonResult(new {
playerCount = dungeon.Simulation.Players.Count,
mobsAlive = dungeon.Simulation.Mobs.Values.Count(m => m.IsAlive),
duration = FormatDuration(DateTime.UtcNow - dungeon.CreatedAt),
- players = dungeon.Simulation.Players.Values.Select(p => new
- {
- id = p.CharacterId.ToString(),
- name = p.CharacterName,
- x = p.X,
- y = p.Y,
- health = p.Health,
- maxHealth = p.MaxHealth,
- mana = p.Mana,
- maxMana = p.MaxMana,
- isAlive = p.IsAlive,
- isInCombat = p.IsInCombat
+ players = dungeon.Simulation.Players.Values.Select(p => new {
+ id = p.CharacterId.ToString(), name = p.CharacterName, x = p.X, y = p.Y,
+ health = p.Health, maxHealth = p.MaxHealth
}),
- mobs = dungeon.Simulation.Mobs.Values.Select(m => new
- {
- id = m.Id,
- name = m.Name,
- x = m.X,
- y = m.Y,
- health = m.Health,
- maxHealth = m.MaxHealth,
- alive = m.IsAlive,
- isBoss = m.Type == DataServer.Data.Enums.MobType.Boss,
- type = m.Type.ToString(),
- state = m.State.ToString(),
- definitionId = m.DefinitionId
+ mobs = dungeon.Simulation.Mobs.Values.Select(m => new {
+ id = m.Id, name = m.Name, x = m.X, y = m.Y, health = m.Health, maxHealth = m.MaxHealth,
+ alive = m.IsAlive, isBoss = m.Type == DataServer.Data.Enums.MobType.Boss, state = m.State.ToString()
})
});
}
- // ==================== MOB HANDLERS ====================
+ public IActionResult OnPostSetTile(Guid id, int x, int y, bool walkable)
+ {
+ return new JsonResult(new { success = _dungeonHandler.SetTileWalkable(id, x, y, walkable) });
+ }
+
+ public IActionResult OnPostPlaceVisualTile(Guid id, int x, int y, int sheetId, int frameIndex, int layer = 0, bool walkable = true)
+ {
+ return new JsonResult(new { success = _dungeonHandler.PlaceVisualTile(id, x, y, sheetId, frameIndex, layer, walkable) });
+ }
+
+ public IActionResult OnPostRemoveTile(Guid id, int x, int y, int? layer = null)
+ {
+ return new JsonResult(new { success = _dungeonHandler.RemoveTile(id, x, y, layer) });
+ }
+
+ public IActionResult OnPostFillRect(Guid id, int x1, int y1, int x2, int y2, bool walkable)
+ {
+ return new JsonResult(new { success = _dungeonHandler.FillTileRect(id, x1, y1, x2, y2, walkable) > 0 });
+ }
+
+ public IActionResult OnPostBroadcastTiles(Guid id)
+ {
+ var dungeon = _dungeonHandler.GetDungeon(id);
+ if (dungeon == null) return new JsonResult(new { error = "Not found" }) { StatusCode = 404 };
+ dungeon.HasPendingTileUpdates = true;
+ return new JsonResult(new { success = true });
+ }
public IActionResult OnPostKillMob(Guid id, int mobId)
{
var dungeon = _dungeonHandler.GetDungeon(id);
- if (dungeon == null)
- return new JsonResult(new { error = "Dungeon not found" }) { StatusCode = 404 };
-
- if (dungeon.Simulation.Mobs.TryGetValue(mobId, out var mob))
+ if (dungeon?.Simulation.Mobs.TryGetValue(mobId, out var mob) == true)
{
- mob.Health = 0;
- mob.IsAlive = false;
+ mob.Health = 0; mob.IsAlive = false;
return new JsonResult(new { success = true });
}
-
- return new JsonResult(new { error = "Mob not found" }) { StatusCode = 404 };
+ return new JsonResult(new { error = "Not found" }) { StatusCode = 404 };
}
public IActionResult OnPostSpawnMob(Guid id, int mobDefId, float x, float y)
{
var mob = _dungeonHandler.SpawnMobInDungeon(id, mobDefId, x, y);
- if (mob == null)
- return new JsonResult(new { error = "Failed to spawn mob" }) { StatusCode = 400 };
- return new JsonResult(new { success = true, mobId = mob.Id });
+ return mob != null
+ ? new JsonResult(new { success = true, mobId = mob.Id })
+ : new JsonResult(new { error = "Failed" }) { StatusCode = 400 };
}
public IActionResult OnPostKillAllMobs(Guid id)
{
var dungeon = _dungeonHandler.GetDungeon(id);
if (dungeon != null)
- {
- foreach (var mob in dungeon.Simulation.Mobs.Values)
- {
- mob.Health = 0;
- mob.IsAlive = false;
- }
- }
+ foreach (var mob in dungeon.Simulation.Mobs.Values) { mob.Health = 0; mob.IsAlive = false; }
return RedirectToPage(new { id });
}
- // ==================== TILE EDITING HANDLERS ====================
-
- public IActionResult OnPostSetTile(Guid id, int x, int y, bool walkable)
- {
- var result = _dungeonHandler.SetTileWalkable(id, x, y, walkable);
- return new JsonResult(new { success = result });
- }
-
- public IActionResult OnPostFillRect(Guid id, int x1, int y1, int x2, int y2, bool walkable)
- {
- var count = _dungeonHandler.FillTileRect(id, x1, y1, x2, y2, walkable);
- return new JsonResult(new { success = count > 0, count });
- }
-
- // ==================== PLAYER HANDLERS ====================
-
public IActionResult OnPostHealPlayer(Guid id, string playerId)
{
- if (!ulong.TryParse(playerId, out var charId))
- return new JsonResult(new { error = "Invalid player ID" }) { StatusCode = 400 };
-
- var result = _dungeonHandler.HealPlayer(id, charId);
- return new JsonResult(new { success = result });
+ if (!ulong.TryParse(playerId, out var charId)) return new JsonResult(new { error = "Invalid ID" }) { StatusCode = 400 };
+ return new JsonResult(new { success = _dungeonHandler.HealPlayer(id, charId) });
}
public IActionResult OnPostTeleportPlayer(Guid id, string playerId, float x, float y)
{
- if (!ulong.TryParse(playerId, out var charId))
- return new JsonResult(new { error = "Invalid player ID" }) { StatusCode = 400 };
-
- var result = _dungeonHandler.TeleportPlayer(id, charId, x, y);
- return new JsonResult(new { success = result });
+ if (!ulong.TryParse(playerId, out var charId)) return new JsonResult(new { error = "Invalid ID" }) { StatusCode = 400 };
+ return new JsonResult(new { success = _dungeonHandler.TeleportPlayer(id, charId, x, y) });
}
public IActionResult OnPostKillPlayer(Guid id, string playerId)
{
- if (!ulong.TryParse(playerId, out var charId))
- return new JsonResult(new { error = "Invalid player ID" }) { StatusCode = 400 };
-
- var result = _dungeonHandler.KillPlayer(id, charId);
- return new JsonResult(new { success = result });
+ if (!ulong.TryParse(playerId, out var charId)) return new JsonResult(new { error = "Invalid ID" }) { StatusCode = 400 };
+ return new JsonResult(new { success = _dungeonHandler.KillPlayer(id, charId) });
}
public IActionResult OnPostSetGodMode(Guid id, string playerId, bool enabled)
{
- if (!ulong.TryParse(playerId, out var charId))
- return new JsonResult(new { error = "Invalid player ID" }) { StatusCode = 400 };
-
- var result = _dungeonHandler.SetPlayerInvulnerable(id, charId, enabled);
- return new JsonResult(new { success = result });
+ if (!ulong.TryParse(playerId, out var charId)) return new JsonResult(new { error = "Invalid ID" }) { StatusCode = 400 };
+ return new JsonResult(new { success = _dungeonHandler.SetPlayerInvulnerable(id, charId, enabled) });
}
- // ==================== DUNGEON HANDLERS ====================
-
public IActionResult OnPostCompleteDungeon(Guid id)
{
var dungeon = _dungeonHandler.GetDungeon(id);
- if (dungeon != null)
- dungeon.Simulation.ForceComplete();
+ dungeon?.Simulation.ForceComplete();
return RedirectToPage(new { id });
}
- public IActionResult OnPostDelete(Guid id)
- {
- _dungeonHandler.ForceCloseDungeon(id);
- return RedirectToPage("/Dungeons/Index");
- }
-
- private static string FormatDuration(TimeSpan duration)
- {
- if (duration.TotalHours >= 1)
- return $"{(int)duration.TotalHours}h {duration.Minutes}m";
- if (duration.TotalMinutes >= 1)
- return $"{(int)duration.TotalMinutes}m {duration.Seconds}s";
- return $"{(int)duration.TotalSeconds}s";
- }
+ private static string FormatDuration(TimeSpan d) =>
+ d.TotalHours >= 1 ? $"{(int)d.TotalHours}h {d.Minutes}m" :
+ d.TotalMinutes >= 1 ? $"{(int)d.TotalMinutes}m {d.Seconds}s" : $"{(int)d.TotalSeconds}s";
}