Add overworld region-zone-chunk data model and admin live world editor

This commit is contained in:
dingo
2026-02-14 13:52:36 -05:00
parent 189e5fcff4
commit 18d6fe683b
9 changed files with 6017 additions and 22 deletions
@@ -0,0 +1,532 @@
@page "/admin/worldeditor"
@model GameServices.Admin.Pages.WorldEditor.IndexModel
@using System.Text.Json
@{
ViewData["Title"] = "World Editor";
var regionsJson = JsonSerializer.Serialize(Model.Regions.Select(r => new
{
id = r.Id,
name = r.Name,
zonesX = r.ZonesPerRegionX,
zonesY = r.ZonesPerRegionY,
chunksPerZoneX = r.ChunksPerZoneX,
chunksPerZoneY = r.ChunksPerZoneY,
chunkWidthTiles = r.ChunkWidthTiles,
chunkHeightTiles = r.ChunkHeightTiles
}));
var sheetsJson = JsonSerializer.Serialize(Model.TileSheets.Select(s => new
{
id = s.Id,
name = s.Name,
path = s.CdnPath,
tileW = s.TileWidth,
tileH = s.TileHeight,
cols = s.Columns,
sheetW = s.SheetWidth,
sheetH = s.SheetHeight
}));
var objectsJson = JsonSerializer.Serialize(Model.ObjectDefinitions.Select(o => new { id = o.Id, name = o.Name }));
var npcsJson = JsonSerializer.Serialize(Model.NpcDefinitions.Select(n => new { id = n.Id, name = n.Name }));
}
<div class="space-y-6">
<div class="flex items-center justify-between">
<div>
<h1 class="text-3xl font-bold text-white">World Editor</h1>
<p class="text-gray-400 mt-1">Live chunk editing for tiles, objects, and NPC spawns</p>
</div>
</div>
<form id="af-form" method="post" class="hidden">
@Html.AntiForgeryToken()
</form>
<div class="grid grid-cols-1 xl:grid-cols-12 gap-6">
<div class="xl:col-span-3 space-y-4">
<div class="card p-4 space-y-3">
<h2 class="text-lg font-semibold text-white">Selection</h2>
<div>
<label class="label">Region</label>
<select id="regionId" class="input"></select>
</div>
<div class="grid grid-cols-2 gap-3">
<div>
<label class="label">Zone X</label>
<input id="zoneX" type="number" class="input" min="0" value="@Model.SelectedZoneX" />
</div>
<div>
<label class="label">Zone Y</label>
<input id="zoneY" type="number" class="input" min="0" value="@Model.SelectedZoneY" />
</div>
<div>
<label class="label">Chunk X</label>
<input id="chunkX" type="number" class="input" min="0" value="@Model.SelectedChunkX" />
</div>
<div>
<label class="label">Chunk Y</label>
<input id="chunkY" type="number" class="input" min="0" value="@Model.SelectedChunkY" />
</div>
</div>
<div class="flex gap-2">
<button type="button" class="btn btn-primary" onclick="loadChunk()">Load Chunk</button>
<button type="button" class="btn btn-secondary" onclick="loadZone()">Load Zone</button>
</div>
</div>
<div class="card p-4 space-y-3">
<h2 class="text-lg font-semibold text-white">Paint Mode</h2>
<div>
<label class="label">Mode</label>
<select id="paintMode" class="input" onchange="renderChunk()">
<option value="tile">Tile</option>
<option value="object">Object</option>
<option value="npc">NPC</option>
<option value="erase">Erase</option>
</select>
</div>
<div id="eraseTargetWrap" class="hidden">
<label class="label">Erase Target</label>
<select id="eraseTarget" class="input">
<option value="tile">Tile</option>
<option value="object">Object</option>
<option value="npc">NPC</option>
</select>
</div>
</div>
<div class="card p-4 space-y-3">
<h2 class="text-lg font-semibold text-white">Tile Tool</h2>
<div>
<label class="label">Sprite Sheet</label>
<select id="sheetId" class="input" onchange="onSheetChanged()"></select>
</div>
<div>
<label class="label">Frame Index</label>
<input id="frameIndex" type="number" class="input" min="0" value="0" />
</div>
<div class="grid grid-cols-1 gap-2">
<label class="flex items-center gap-2 text-gray-300 cursor-pointer">
<input id="isWalkable" type="checkbox" checked class="w-4 h-4 rounded border-gray-600 bg-gray-800 text-indigo-600" />
Walkable
</label>
<label class="flex items-center gap-2 text-gray-300 cursor-pointer">
<input id="isInvisiblePaywall" type="checkbox" class="w-4 h-4 rounded border-gray-600 bg-gray-800 text-indigo-600" />
Invisible Paywall
</label>
</div>
<a id="tileDefLink" href="/admin/tilemaps/tiles/edit" class="text-sm text-indigo-400 hover:underline">Edit Tile Definition</a>
</div>
<div class="card p-4 space-y-3">
<h2 class="text-lg font-semibold text-white">Object Tool</h2>
<label class="label">Object</label>
<select id="objectDefinitionId" class="input"></select>
</div>
<div class="card p-4 space-y-3">
<h2 class="text-lg font-semibold text-white">NPC Tool</h2>
<label class="label">NPC</label>
<select id="npcDefinitionId" class="input"></select>
</div>
</div>
<div class="xl:col-span-9 space-y-4">
<div class="grid grid-cols-1 lg:grid-cols-2 gap-4">
<div class="card p-4">
<h2 class="text-lg font-semibold text-white mb-2">Region Minimap</h2>
<canvas id="regionCanvas" width="360" height="240" class="w-full rounded border border-gray-700 bg-gray-900"></canvas>
</div>
<div class="card p-4">
<h2 class="text-lg font-semibold text-white mb-2">Zone Chunk Map</h2>
<canvas id="zoneCanvas" width="360" height="240" class="w-full rounded border border-gray-700 bg-gray-900"></canvas>
</div>
</div>
<div class="card p-4">
<div class="flex items-center justify-between mb-2">
<h2 class="text-lg font-semibold text-white">Chunk Canvas</h2>
<div id="chunkMeta" class="text-sm text-gray-400">No chunk loaded</div>
</div>
<canvas id="chunkCanvas" width="768" height="768" class="w-full rounded border border-gray-700 bg-gray-900 cursor-crosshair"></canvas>
</div>
</div>
</div>
</div>
@section Scripts {
<script>
const regions = @Html.Raw(regionsJson);
const sheets = @Html.Raw(sheetsJson);
const objectDefs = @Html.Raw(objectsJson);
const npcDefs = @Html.Raw(npcsJson);
let currentRegion = null;
let currentZoneChunks = [];
let currentChunk = null;
let currentTiles = new Map();
let currentObjects = [];
let currentNpcs = [];
let pollTimer = null;
const regionCanvas = document.getElementById('regionCanvas');
const regionCtx = regionCanvas.getContext('2d');
const zoneCanvas = document.getElementById('zoneCanvas');
const zoneCtx = zoneCanvas.getContext('2d');
const chunkCanvas = document.getElementById('chunkCanvas');
const chunkCtx = chunkCanvas.getContext('2d');
function token() {
return document.querySelector('#af-form input[name="__RequestVerificationToken"]').value;
}
function key(x, y) { return `${x},${y}`; }
function initSelectors() {
const regionSel = document.getElementById('regionId');
regionSel.innerHTML = regions.map(r => `<option value="${r.id}">${r.name}</option>`).join('');
regionSel.value = '@Model.SelectedRegionId';
regionSel.addEventListener('change', () => {
loadRegion();
});
const sheetSel = document.getElementById('sheetId');
sheetSel.innerHTML = sheets.map(s => `<option value="${s.id}">${s.name}</option>`).join('');
if (sheets.length) sheetSel.value = sheets[0].id;
onSheetChanged();
document.getElementById('objectDefinitionId').innerHTML = objectDefs.map(o => `<option value="${o.id}">${o.name}</option>`).join('');
document.getElementById('npcDefinitionId').innerHTML = npcDefs.map(n => `<option value="${n.id}">${n.name}</option>`).join('');
}
async function getJson(url) {
const res = await fetch(url);
return await res.json();
}
async function postJson(url, body) {
const params = new URLSearchParams();
for (const k of Object.keys(body)) {
const v = body[k];
if (v === undefined || v === null) continue;
params.set(k, String(v));
}
const res = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
'RequestVerificationToken': token()
},
body: params.toString()
});
return await res.json();
}
function selection() {
return {
regionId: parseInt(document.getElementById('regionId').value, 10) || 0,
zoneX: parseInt(document.getElementById('zoneX').value, 10) || 0,
zoneY: parseInt(document.getElementById('zoneY').value, 10) || 0,
chunkX: parseInt(document.getElementById('chunkX').value, 10) || 0,
chunkY: parseInt(document.getElementById('chunkY').value, 10) || 0
};
}
async function loadRegion() {
const s = selection();
const data = await getJson(`/admin/worldeditor?handler=Region&regionId=${s.regionId}`);
if (!data.success) return;
currentRegion = data.region;
renderRegionMap();
await loadZone();
}
async function loadZone() {
const s = selection();
const data = await getJson(`/admin/worldeditor?handler=Zone&regionId=${s.regionId}&zoneX=${s.zoneX}&zoneY=${s.zoneY}`);
if (!data.success) return;
currentZoneChunks = data.chunks || [];
renderZoneMap();
}
async function loadChunk() {
const s = selection();
const data = await getJson(`/admin/worldeditor?handler=Chunk&regionId=${s.regionId}&zoneX=${s.zoneX}&zoneY=${s.zoneY}&chunkX=${s.chunkX}&chunkY=${s.chunkY}`);
if (!data.success) return;
currentChunk = data.chunk;
currentTiles = new Map();
for (const t of data.tiles) currentTiles.set(key(t.x, t.y), t);
currentObjects = data.objects || [];
currentNpcs = data.npcs || [];
document.getElementById('chunkMeta').textContent = `Chunk ${s.zoneX}:${s.zoneY}:${s.chunkX}:${s.chunkY} v${currentChunk.version} (${currentChunk.width}x${currentChunk.height})`;
renderChunk();
if (pollTimer) clearInterval(pollTimer);
pollTimer = setInterval(checkChunkVersion, 2000);
}
async function checkChunkVersion() {
if (!currentChunk) return;
const s = selection();
const data = await getJson(`/admin/worldeditor?handler=Chunk&regionId=${s.regionId}&zoneX=${s.zoneX}&zoneY=${s.zoneY}&chunkX=${s.chunkX}&chunkY=${s.chunkY}`);
if (!data.success) return;
if (data.chunk.version !== currentChunk.version) {
currentChunk = data.chunk;
currentTiles = new Map();
for (const t of data.tiles) currentTiles.set(key(t.x, t.y), t);
currentObjects = data.objects || [];
currentNpcs = data.npcs || [];
document.getElementById('chunkMeta').textContent = `Chunk ${s.zoneX}:${s.zoneY}:${s.chunkX}:${s.chunkY} v${currentChunk.version} (${currentChunk.width}x${currentChunk.height})`;
renderChunk();
loadZone();
}
}
function renderRegionMap() {
regionCtx.clearRect(0, 0, regionCanvas.width, regionCanvas.height);
if (!currentRegion) return;
const cellW = regionCanvas.width / currentRegion.zonesX;
const cellH = regionCanvas.height / currentRegion.zonesY;
const sx = parseInt(document.getElementById('zoneX').value, 10) || 0;
const sy = parseInt(document.getElementById('zoneY').value, 10) || 0;
for (let y = 0; y < currentRegion.zonesY; y++) {
for (let x = 0; x < currentRegion.zonesX; x++) {
const px = x * cellW;
const py = y * cellH;
regionCtx.fillStyle = (x === sx && y === sy) ? '#4338ca' : '#1f2937';
regionCtx.fillRect(px + 1, py + 1, cellW - 2, cellH - 2);
regionCtx.strokeStyle = '#374151';
regionCtx.strokeRect(px + 1, py + 1, cellW - 2, cellH - 2);
regionCtx.fillStyle = '#9ca3af';
regionCtx.font = '12px monospace';
regionCtx.fillText(`${x},${y}`, px + 6, py + 16);
}
}
}
function renderZoneMap() {
zoneCtx.clearRect(0, 0, zoneCanvas.width, zoneCanvas.height);
if (!currentRegion) return;
const w = currentRegion.chunksPerZoneX;
const h = currentRegion.chunksPerZoneY;
const cellW = zoneCanvas.width / w;
const cellH = zoneCanvas.height / h;
const sx = parseInt(document.getElementById('chunkX').value, 10) || 0;
const sy = parseInt(document.getElementById('chunkY').value, 10) || 0;
const versionByPos = new Map();
for (const c of currentZoneChunks) versionByPos.set(key(c.chunkX, c.chunkY), c.version);
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
const px = x * cellW;
const py = y * cellH;
const v = versionByPos.get(key(x, y));
zoneCtx.fillStyle = (x === sx && y === sy) ? '#4338ca' : (v ? '#14532d' : '#1f2937');
zoneCtx.fillRect(px + 1, py + 1, cellW - 2, cellH - 2);
zoneCtx.strokeStyle = '#374151';
zoneCtx.strokeRect(px + 1, py + 1, cellW - 2, cellH - 2);
}
}
}
function renderChunk() {
chunkCtx.clearRect(0, 0, chunkCanvas.width, chunkCanvas.height);
if (!currentChunk) return;
const tileSize = Math.max(6, Math.floor(Math.min(chunkCanvas.width / currentChunk.width, chunkCanvas.height / currentChunk.height)));
const drawW = currentChunk.width * tileSize;
const drawH = currentChunk.height * tileSize;
chunkCtx.fillStyle = '#111827';
chunkCtx.fillRect(0, 0, drawW, drawH);
for (const t of currentTiles.values()) {
const px = t.x * tileSize;
const py = t.y * tileSize;
if (t.isInvisiblePaywall) {
chunkCtx.fillStyle = '#7c2d12';
} else if (t.isWalkable) {
chunkCtx.fillStyle = '#1d4ed8';
} else {
chunkCtx.fillStyle = '#334155';
}
chunkCtx.fillRect(px, py, tileSize, tileSize);
}
chunkCtx.strokeStyle = 'rgba(148,163,184,0.16)';
chunkCtx.lineWidth = 1;
for (let x = 0; x <= currentChunk.width; x++) {
chunkCtx.beginPath();
chunkCtx.moveTo(x * tileSize + 0.5, 0);
chunkCtx.lineTo(x * tileSize + 0.5, drawH);
chunkCtx.stroke();
}
for (let y = 0; y <= currentChunk.height; y++) {
chunkCtx.beginPath();
chunkCtx.moveTo(0, y * tileSize + 0.5);
chunkCtx.lineTo(drawW, y * tileSize + 0.5);
chunkCtx.stroke();
}
for (const o of currentObjects) {
const px = o.x * tileSize + tileSize / 2;
const py = o.y * tileSize + tileSize / 2;
chunkCtx.fillStyle = '#f59e0b';
chunkCtx.beginPath();
chunkCtx.arc(px, py, Math.max(2, tileSize * 0.25), 0, Math.PI * 2);
chunkCtx.fill();
}
for (const n of currentNpcs) {
const px = n.x * tileSize + tileSize / 2;
const py = n.y * tileSize + tileSize / 2;
chunkCtx.fillStyle = '#22c55e';
chunkCtx.beginPath();
chunkCtx.rect(px - Math.max(2, tileSize * 0.2), py - Math.max(2, tileSize * 0.2), Math.max(4, tileSize * 0.4), Math.max(4, tileSize * 0.4));
chunkCtx.fill();
}
const mode = document.getElementById('paintMode').value;
document.getElementById('eraseTargetWrap').classList.toggle('hidden', mode !== 'erase');
}
function canvasTile(e) {
if (!currentChunk) return null;
const rect = chunkCanvas.getBoundingClientRect();
const scaleX = chunkCanvas.width / rect.width;
const scaleY = chunkCanvas.height / rect.height;
const cx = (e.clientX - rect.left) * scaleX;
const cy = (e.clientY - rect.top) * scaleY;
const tileSize = Math.max(6, Math.floor(Math.min(chunkCanvas.width / currentChunk.width, chunkCanvas.height / currentChunk.height)));
const x = Math.floor(cx / tileSize);
const y = Math.floor(cy / tileSize);
if (x < 0 || y < 0 || x >= currentChunk.width || y >= currentChunk.height) return null;
return { x, y };
}
async function handleChunkPaint(e) {
const pos = canvasTile(e);
if (!pos) return;
const s = selection();
const mode = document.getElementById('paintMode').value;
if (mode === 'tile') {
const sheetId = parseInt(document.getElementById('sheetId').value, 10) || 0;
const frameIndex = parseInt(document.getElementById('frameIndex').value, 10) || 0;
const isWalkable = document.getElementById('isWalkable').checked;
const isInvisiblePaywall = document.getElementById('isInvisiblePaywall').checked;
const data = await postJson('/admin/worldeditor?handler=UpsertTile', {
...s,
x: pos.x,
y: pos.y,
sheetId,
frameIndex,
isWalkable,
isInvisiblePaywall
});
if (data.success) {
currentChunk.version = data.chunkVersion;
currentTiles.set(key(pos.x, pos.y), {
x: pos.x, y: pos.y, sheetId, frameIndex, isWalkable, isInvisiblePaywall
});
}
} else if (mode === 'object') {
const objectDefinitionId = parseInt(document.getElementById('objectDefinitionId').value, 10) || 0;
const data = await postJson('/admin/worldeditor?handler=UpsertObject', {
...s,
objectDefinitionId,
x: pos.x,
y: pos.y,
rotation: 0
});
if (data.success) {
currentChunk.version = data.chunkVersion;
const idx = currentObjects.findIndex(o => o.id === data.op.id);
if (idx >= 0) currentObjects[idx] = { ...currentObjects[idx], ...data.op };
else currentObjects.push(data.op);
}
} else if (mode === 'npc') {
const npcDefinitionId = parseInt(document.getElementById('npcDefinitionId').value, 10) || 0;
const data = await postJson('/admin/worldeditor?handler=UpsertNpc', {
...s,
npcDefinitionId,
x: pos.x,
y: pos.y,
rotation: 0
});
if (data.success) {
currentChunk.version = data.chunkVersion;
const idx = currentNpcs.findIndex(n => n.id === data.op.id);
if (idx >= 0) currentNpcs[idx] = { ...currentNpcs[idx], ...data.op };
else currentNpcs.push(data.op);
}
} else if (mode === 'erase') {
const eraseTarget = document.getElementById('eraseTarget').value;
if (eraseTarget === 'tile') {
const data = await postJson('/admin/worldeditor?handler=RemoveTile', { ...s, x: pos.x, y: pos.y });
if (data.success) {
currentChunk.version = data.chunkVersion;
currentTiles.delete(key(pos.x, pos.y));
}
} else if (eraseTarget === 'object') {
const hit = currentObjects.find(o => o.x === pos.x && o.y === pos.y);
if (hit) {
const data = await postJson('/admin/worldeditor?handler=RemoveObject', { ...s, id: hit.id });
if (data.success) {
currentChunk.version = data.chunkVersion;
currentObjects = currentObjects.filter(o => o.id !== hit.id);
}
}
} else if (eraseTarget === 'npc') {
const hit = currentNpcs.find(n => n.x === pos.x && n.y === pos.y);
if (hit) {
const data = await postJson('/admin/worldeditor?handler=RemoveNpc', { ...s, id: hit.id });
if (data.success) {
currentChunk.version = data.chunkVersion;
currentNpcs = currentNpcs.filter(n => n.id !== hit.id);
}
}
}
}
renderChunk();
loadZone();
}
function onSheetChanged() {
const sheetId = parseInt(document.getElementById('sheetId').value, 10) || 0;
const frameIndex = parseInt(document.getElementById('frameIndex').value, 10) || 0;
document.getElementById('tileDefLink').href = `/admin/tilemaps/tiles/edit?sheetId=${sheetId}&frameIndex=${frameIndex}`;
}
document.getElementById('frameIndex').addEventListener('input', onSheetChanged);
chunkCanvas.addEventListener('click', handleChunkPaint);
zoneCanvas.addEventListener('click', (e) => {
if (!currentRegion) return;
const rect = zoneCanvas.getBoundingClientRect();
const x = Math.floor((e.clientX - rect.left) / (rect.width / currentRegion.chunksPerZoneX));
const y = Math.floor((e.clientY - rect.top) / (rect.height / currentRegion.chunksPerZoneY));
document.getElementById('chunkX').value = x;
document.getElementById('chunkY').value = y;
renderZoneMap();
});
regionCanvas.addEventListener('click', (e) => {
if (!currentRegion) return;
const rect = regionCanvas.getBoundingClientRect();
const x = Math.floor((e.clientX - rect.left) / (rect.width / currentRegion.zonesX));
const y = Math.floor((e.clientY - rect.top) / (rect.height / currentRegion.zonesY));
document.getElementById('zoneX').value = x;
document.getElementById('zoneY').value = y;
renderRegionMap();
loadZone();
});
initSelectors();
loadRegion().then(loadChunk);
</script>
}