Files

1068 lines
49 KiB
Plaintext

@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, interactionType = o.InteractionType.ToString() }));
var npcsJson = JsonSerializer.Serialize(Model.NpcDefinitions.Select(n => new { id = n.Id, name = n.Name }));
var mobsJson = JsonSerializer.Serialize(Model.MobDefinitions.Select(m => new { id = m.Id, name = m.Name }));
var tileDefsJson = JsonSerializer.Serialize(Model.TileDefinitions.Select(t => new
{
id = t.Id,
sheetId = t.TileMapSheetId,
frameIndex = t.FrameIndex,
name = t.Name,
type = t.Type.ToString(),
isWalkable = t.IsWalkable
}));
}
<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, NPC spawns, and mob 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 class="grid grid-cols-2 gap-2">
<button type="button" class="btn btn-secondary" onclick="clearChunk()">Clear Chunk</button>
<button type="button" class="btn btn-secondary" onclick="deleteChunk()">Delete Chunk</button>
</div>
</div>
<div class="card p-4 space-y-3">
<h2 class="text-lg font-semibold text-white">Region Management</h2>
<div>
<label class="label">Name</label>
<input id="newRegionName" type="text" class="input" placeholder="New Region Name" />
</div>
<div class="grid grid-cols-2 gap-2">
<div>
<label class="label">Zones X</label>
<input id="newZonesX" type="number" class="input" min="1" value="4" />
</div>
<div>
<label class="label">Zones Y</label>
<input id="newZonesY" type="number" class="input" min="1" value="4" />
</div>
<div>
<label class="label">Chunks X</label>
<input id="newChunksX" type="number" class="input" min="1" value="8" />
</div>
<div>
<label class="label">Chunks Y</label>
<input id="newChunksY" type="number" class="input" min="1" value="8" />
</div>
<div>
<label class="label">Chunk W</label>
<input id="newChunkW" type="number" class="input" min="8" value="64" />
</div>
<div>
<label class="label">Chunk H</label>
<input id="newChunkH" type="number" class="input" min="8" value="64" />
</div>
</div>
<button type="button" class="btn btn-primary w-full" onclick="createRegion()">Create Region</button>
</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="portal">Portal</option>
<option value="npc">NPC</option>
<option value="mob">Mob</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>
<option value="mob">Mob</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">Tile Picker</label>
<div class="rounded border border-gray-700 bg-gray-900 p-2 overflow-auto max-h-64">
<canvas id="sheetPickerCanvas" class="block max-w-none" style="image-rendering: pixelated;"></canvas>
</div>
<div id="sheetPickerMeta" class="mt-2 text-xs text-gray-400">No sheet selected</div>
</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">Portal Tool</h2>
<label class="label">Portal Object</label>
<select id="portalObjectDefinitionId" class="input"></select>
<label class="label">Destination Type</label>
<select id="portalDestinationType" class="input" onchange="onPortalDestinationTypeChanged()">
<option value="world">World Coords</option>
<option value="dungeon_random">Random Dungeon</option>
<option value="dungeon_specific">Specific Dungeon</option>
</select>
<div id="portalWorldCoords" class="grid grid-cols-2 gap-2">
<div><label class="label">Target Region</label><input id="portalTargetRegionId" type="number" class="input" min="1" value="@Model.SelectedRegionId" /></div>
<div><label class="label">Target Zone X</label><input id="portalTargetZoneX" type="number" class="input" min="0" value="@Model.SelectedZoneX" /></div>
<div><label class="label">Target Zone Y</label><input id="portalTargetZoneY" type="number" class="input" min="0" value="@Model.SelectedZoneY" /></div>
<div><label class="label">Target Chunk X</label><input id="portalTargetChunkX" type="number" class="input" min="0" value="@Model.SelectedChunkX" /></div>
<div><label class="label">Target Chunk Y</label><input id="portalTargetChunkY" type="number" class="input" min="0" value="@Model.SelectedChunkY" /></div>
<div><label class="label">Target Tile X</label><input id="portalTargetTileX" type="number" class="input" min="0" value="0" /></div>
<div><label class="label">Target Tile Y</label><input id="portalTargetTileY" type="number" class="input" min="0" value="0" /></div>
</div>
<div id="portalDungeonRandom" class="grid grid-cols-2 gap-2 hidden">
<div><label class="label">Tier</label><input id="portalRandomTier" type="number" class="input" min="1" value="1" /></div>
<div><label class="label">Bracket Min</label><input id="portalBracketMin" type="number" class="input" min="1" value="1" /></div>
<div><label class="label">Bracket Max</label><input id="portalBracketMax" type="number" class="input" min="1" value="10" /></div>
</div>
<div id="portalDungeonSpecific" class="grid grid-cols-1 gap-2 hidden">
<div><label class="label">Dungeon Template Id</label><input id="portalDungeonTemplateId" type="number" class="input" min="1" value="1" /></div>
</div>
</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 class="card p-4 space-y-3">
<h2 class="text-lg font-semibold text-white">Mob Tool</h2>
<label class="label">Mob</label>
<select id="mobDefinitionId" class="input"></select>
<div class="grid grid-cols-2 gap-2">
<div>
<label class="label">Spawn Count</label>
<input id="mobSpawnCount" type="number" class="input" min="1" value="1" />
</div>
<div>
<label class="label">Respawn Sec</label>
<input id="mobRespawnSeconds" type="number" class="input" min="0" step="1" value="30" />
</div>
</div>
</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 class="flex items-center gap-2">
<button type="button" class="btn btn-secondary px-2 py-1 text-xs" onclick="adjustZoom(-0.25)">-</button>
<input id="zoomLevel" type="range" min="0.5" max="4" step="0.25" value="1" onchange="onZoomChanged()" class="w-28" />
<button type="button" class="btn btn-secondary px-2 py-1 text-xs" onclick="adjustZoom(0.25)">+</button>
<button type="button" class="btn btn-secondary px-2 py-1 text-xs" onclick="resetZoom()">Reset</button>
<div id="chunkMeta" class="text-sm text-gray-400 ml-2">No chunk loaded</div>
</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>
let regions = @Html.Raw(regionsJson);
const sheets = @Html.Raw(sheetsJson);
const objectDefs = @Html.Raw(objectsJson);
const npcDefs = @Html.Raw(npcsJson);
const mobDefs = @Html.Raw(mobsJson);
const tileDefs = @Html.Raw(tileDefsJson);
const cdnBaseUrl = '@Model.CdnBaseUrl';
let currentRegion = null;
let currentZoneChunks = [];
let currentChunk = null;
let currentTiles = new Map();
let currentObjects = [];
let currentNpcs = [];
let currentMobs = [];
let eventSource = null;
let chunkZoom = 1;
const tileDefBySprite = {};
const sheetImageCache = new Map();
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');
const sheetPickerCanvas = document.getElementById('sheetPickerCanvas');
const sheetPickerCtx = sheetPickerCanvas.getContext('2d');
const sheetPickerMeta = document.getElementById('sheetPickerMeta');
const sheetPickerImage = new Image();
let sheetPickerLoadedSheetId = 0;
function token() {
return document.querySelector('#af-form input[name="__RequestVerificationToken"]').value;
}
function key(x, y) { return `${x},${y}`; }
function initSelectors() {
for (const def of tileDefs) {
tileDefBySprite[`${def.sheetId}:${def.frameIndex}`] = def;
}
const regionSel = document.getElementById('regionId');
refreshRegionSelect('@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('');
const portalDefs = objectDefs.filter(o => (o.interactionType || '').toLowerCase() === 'teleport');
document.getElementById('portalObjectDefinitionId').innerHTML = (portalDefs.length ? portalDefs : 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('');
document.getElementById('mobDefinitionId').innerHTML = mobDefs.map(m => `<option value="${m.id}">${m.name}</option>`).join('');
onPortalDestinationTypeChanged();
}
function refreshRegionSelect(selectedId) {
const regionSel = document.getElementById('regionId');
regionSel.innerHTML = regions.map(r => `<option value="${r.id}">${r.name}</option>`).join('');
if (selectedId !== undefined && selectedId !== null && selectedId !== '') {
regionSel.value = String(selectedId);
} else if (regions.length) {
regionSel.value = String(regions[0].id);
}
}
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);
for (const t of data.tiles) preloadSheetImage(t.sheetId);
currentObjects = data.objects || [];
currentNpcs = data.npcs || [];
currentMobs = data.mobs || [];
document.getElementById('chunkMeta').textContent = `Chunk ${s.zoneX}:${s.zoneY}:${s.chunkX}:${s.chunkY} v${currentChunk.version} (${currentChunk.width}x${currentChunk.height})`;
renderChunk();
startStream();
}
function startStream() {
if (!currentChunk) return;
if (eventSource) {
eventSource.close();
eventSource = null;
}
const s = selection();
const url = `/admin/worldeditor?handler=Stream&regionId=${s.regionId}&zoneX=${s.zoneX}&zoneY=${s.zoneY}&chunkX=${s.chunkX}&chunkY=${s.chunkY}`;
eventSource = new EventSource(url);
eventSource.onmessage = (evt) => {
if (!evt.data) return;
try {
const delta = JSON.parse(evt.data);
applyDelta(delta);
} catch {
// ignore malformed stream payload
}
};
}
function applyDelta(delta) {
if (!currentChunk || !delta || delta.kind !== 'chunk_delta' || !delta.op) return;
if (delta.toVersion <= currentChunk.version) return;
if (delta.fromVersion !== currentChunk.version) {
loadChunk();
return;
}
const op = delta.op;
if (op.type === 'tile_upsert') {
currentTiles.set(key(op.x, op.y), {
x: op.x,
y: op.y,
sheetId: op.sheetId,
frameIndex: op.frameIndex,
isWalkable: op.isWalkable,
isInvisiblePaywall: op.isInvisiblePaywall
});
} else if (op.type === 'tile_remove') {
currentTiles.delete(key(op.x, op.y));
} else if (op.type === 'object_upsert') {
const idx = currentObjects.findIndex(o => o.id === op.id);
if (idx >= 0) currentObjects[idx] = { ...currentObjects[idx], ...op };
else currentObjects.push({ ...op });
} else if (op.type === 'object_remove') {
currentObjects = currentObjects.filter(o => o.id !== op.id);
} else if (op.type === 'npc_upsert') {
const idx = currentNpcs.findIndex(n => n.id === op.id);
if (idx >= 0) currentNpcs[idx] = { ...currentNpcs[idx], ...op };
else currentNpcs.push({ ...op });
} else if (op.type === 'npc_remove') {
currentNpcs = currentNpcs.filter(n => n.id !== op.id);
} else if (op.type === 'mob_upsert') {
const idx = currentMobs.findIndex(m => m.id === op.id);
if (idx >= 0) currentMobs[idx] = { ...currentMobs[idx], ...op };
else currentMobs.push({ ...op });
} else if (op.type === 'mob_remove') {
currentMobs = currentMobs.filter(m => m.id !== op.id);
} else if (op.type === 'chunk_clear') {
currentTiles.clear();
currentObjects = [];
currentNpcs = [];
currentMobs = [];
} else if (op.type === 'chunk_deleted') {
currentChunk = null;
currentTiles.clear();
currentObjects = [];
currentNpcs = [];
currentMobs = [];
chunkCtx.clearRect(0, 0, chunkCanvas.width, chunkCanvas.height);
document.getElementById('chunkMeta').textContent = 'Chunk deleted';
loadZone();
return;
} else {
loadChunk();
return;
}
currentChunk.version = delta.toVersion;
const s = selection();
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 baseTileSize = Math.max(6, Math.floor(Math.min(chunkCanvas.width / currentChunk.width, chunkCanvas.height / currentChunk.height)));
const tileSize = Math.max(2, Math.floor(baseTileSize * chunkZoom));
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;
const sheet = sheets.find(s => s.id === t.sheetId);
const img = sheet ? sheetImageCache.get(sheet.id) : null;
const canDrawSprite = !!sheet && !!img && img.complete && sheet.tileW > 0 && sheet.tileH > 0 && sheet.cols > 0;
if (canDrawSprite) {
const col = t.frameIndex % sheet.cols;
const row = Math.floor(t.frameIndex / sheet.cols);
const sx = col * sheet.tileW;
const sy = row * sheet.tileH;
chunkCtx.imageSmoothingEnabled = false;
chunkCtx.drawImage(img, sx, sy, sheet.tileW, sheet.tileH, px, py, tileSize, tileSize);
} else {
if (t.isInvisiblePaywall) {
chunkCtx.fillStyle = '#7c2d12';
} else if (t.isWalkable) {
chunkCtx.fillStyle = '#1d4ed8';
} else {
chunkCtx.fillStyle = '#334155';
}
chunkCtx.fillRect(px, py, tileSize, tileSize);
}
if (t.isInvisiblePaywall) {
chunkCtx.fillStyle = 'rgba(127,29,29,0.45)';
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;
const isPortal = (o.interactionType || '').toLowerCase() === 'teleport' || (o.metadataJson || '').includes('portalType');
chunkCtx.fillStyle = isPortal ? '#a855f7' : '#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();
}
for (const m of currentMobs) {
const px = m.x * tileSize + tileSize / 2;
const py = m.y * tileSize + tileSize / 2;
chunkCtx.fillStyle = '#ef4444';
chunkCtx.beginPath();
chunkCtx.moveTo(px, py - Math.max(3, tileSize * 0.28));
chunkCtx.lineTo(px + Math.max(3, tileSize * 0.28), py + Math.max(3, tileSize * 0.28));
chunkCtx.lineTo(px - Math.max(3, tileSize * 0.28), py + Math.max(3, tileSize * 0.28));
chunkCtx.closePath();
chunkCtx.fill();
}
const mode = document.getElementById('paintMode').value;
document.getElementById('eraseTargetWrap').classList.toggle('hidden', mode !== 'erase');
}
function onPortalDestinationTypeChanged() {
const mode = document.getElementById('portalDestinationType').value;
document.getElementById('portalWorldCoords').classList.toggle('hidden', mode !== 'world');
document.getElementById('portalDungeonRandom').classList.toggle('hidden', mode !== 'dungeon_random');
document.getElementById('portalDungeonSpecific').classList.toggle('hidden', mode !== 'dungeon_specific');
}
function buildPortalMetadata() {
const destinationType = document.getElementById('portalDestinationType').value;
if (destinationType === 'world') {
return JSON.stringify({
portalType: 'world',
targetRegionId: parseInt(document.getElementById('portalTargetRegionId').value, 10) || 1,
targetZoneX: parseInt(document.getElementById('portalTargetZoneX').value, 10) || 0,
targetZoneY: parseInt(document.getElementById('portalTargetZoneY').value, 10) || 0,
targetChunkX: parseInt(document.getElementById('portalTargetChunkX').value, 10) || 0,
targetChunkY: parseInt(document.getElementById('portalTargetChunkY').value, 10) || 0,
targetTileX: parseInt(document.getElementById('portalTargetTileX').value, 10) || 0,
targetTileY: parseInt(document.getElementById('portalTargetTileY').value, 10) || 0
});
}
if (destinationType === 'dungeon_random') {
return JSON.stringify({
portalType: 'dungeon_random',
randomTier: parseInt(document.getElementById('portalRandomTier').value, 10) || 1,
levelBracketMin: parseInt(document.getElementById('portalBracketMin').value, 10) || 1,
levelBracketMax: parseInt(document.getElementById('portalBracketMax').value, 10) || 10
});
}
return JSON.stringify({
portalType: 'dungeon_specific',
dungeonTemplateId: parseInt(document.getElementById('portalDungeonTemplateId').value, 10) || 1
});
}
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 baseTileSize = Math.max(6, Math.floor(Math.min(chunkCanvas.width / currentChunk.width, chunkCanvas.height / currentChunk.height)));
const tileSize = Math.max(2, Math.floor(baseTileSize * chunkZoom));
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 def = tileDefBySprite[`${sheetId}:${frameIndex}`];
const isWalkable = def ? !!def.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: data.op?.isWalkable ?? 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 === 'portal') {
const objectDefinitionId = parseInt(document.getElementById('portalObjectDefinitionId').value, 10) || 0;
const metadataJson = buildPortalMetadata();
const data = await postJson('/admin/worldeditor?handler=UpsertObject', {
...s,
objectDefinitionId,
x: pos.x,
y: pos.y,
rotation: 0,
metadataJson
});
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 === 'mob') {
const mobDefinitionId = parseInt(document.getElementById('mobDefinitionId').value, 10) || 0;
const spawnCount = parseInt(document.getElementById('mobSpawnCount').value, 10) || 1;
const respawnSeconds = parseFloat(document.getElementById('mobRespawnSeconds').value) || 30;
const data = await postJson('/admin/worldeditor?handler=UpsertMob', {
...s,
mobDefinitionId,
x: pos.x,
y: pos.y,
rotation: 0,
spawnCount,
respawnSeconds
});
if (data.success) {
currentChunk.version = data.chunkVersion;
const idx = currentMobs.findIndex(m => m.id === data.op.id);
if (idx >= 0) currentMobs[idx] = { ...currentMobs[idx], ...data.op };
else currentMobs.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);
}
}
} else if (eraseTarget === 'mob') {
const hit = currentMobs.find(m => m.x === pos.x && m.y === pos.y);
if (hit) {
const data = await postJson('/admin/worldeditor?handler=RemoveMob', { ...s, id: hit.id });
if (data.success) {
currentChunk.version = data.chunkVersion;
currentMobs = currentMobs.filter(m => m.id !== hit.id);
}
}
}
}
renderChunk();
loadZone();
}
function onSheetChanged() {
const sheetId = parseInt(document.getElementById('sheetId').value, 10) || 0;
let frameIndex = parseInt(document.getElementById('frameIndex').value, 10) || 0;
const sheet = sheets.find(s => s.id === sheetId);
const totalFrames = sheet ? (sheet.cols * Math.max(1, Math.floor(sheet.sheetH / Math.max(1, sheet.tileH)))) : 1;
frameIndex = Math.max(0, Math.min(totalFrames - 1, frameIndex));
document.getElementById('frameIndex').value = frameIndex;
document.getElementById('tileDefLink').href = `/admin/tilemaps/tiles/edit?sheetId=${sheetId}&frameIndex=${frameIndex}`;
applySelectedTileDefinition();
preloadSheetImage(sheetId);
renderSheetPicker();
}
function applySelectedTileDefinition() {
const sheetId = parseInt(document.getElementById('sheetId').value, 10) || 0;
const frameIndex = parseInt(document.getElementById('frameIndex').value, 10) || 0;
const def = tileDefBySprite[`${sheetId}:${frameIndex}`];
const walkableBox = document.getElementById('isWalkable');
if (def) {
walkableBox.checked = !!def.isWalkable;
}
}
function resolveSheetImageUrl(sheet) {
if (!sheet || !sheet.path) return '';
if (sheet.path.startsWith('http://') || sheet.path.startsWith('https://')) return sheet.path;
const trimmed = sheet.path.replace(/^\/+/, '');
return trimmed.startsWith('downloads/')
? `${cdnBaseUrl.replace(/\/downloads$/i, '')}/${trimmed}`
: `${cdnBaseUrl}/${trimmed}`;
}
function renderSheetPicker() {
const sheetId = parseInt(document.getElementById('sheetId').value, 10) || 0;
const frameIndex = parseInt(document.getElementById('frameIndex').value, 10) || 0;
const sheet = sheets.find(s => s.id === sheetId);
const imageUrl = resolveSheetImageUrl(sheet);
if (!sheet || !imageUrl) {
sheetPickerCanvas.width = 1;
sheetPickerCanvas.height = 1;
sheetPickerCtx.clearRect(0, 0, 1, 1);
sheetPickerMeta.textContent = 'No sheet selected';
return;
}
const drawSelectedFrame = () => {
const width = Math.max(1, sheet.sheetW);
const height = Math.max(1, sheet.sheetH);
sheetPickerCanvas.width = width;
sheetPickerCanvas.height = height;
sheetPickerCtx.imageSmoothingEnabled = false;
sheetPickerCtx.clearRect(0, 0, width, height);
sheetPickerCtx.drawImage(sheetPickerImage, 0, 0, width, height);
const tileW = Math.max(1, sheet.tileW);
const tileH = Math.max(1, sheet.tileH);
sheetPickerCtx.strokeStyle = 'rgba(148,163,184,0.3)';
sheetPickerCtx.lineWidth = 1;
for (let x = tileW; x < width; x += tileW) {
sheetPickerCtx.beginPath();
sheetPickerCtx.moveTo(x + 0.5, 0);
sheetPickerCtx.lineTo(x + 0.5, height);
sheetPickerCtx.stroke();
}
for (let y = tileH; y < height; y += tileH) {
sheetPickerCtx.beginPath();
sheetPickerCtx.moveTo(0, y + 0.5);
sheetPickerCtx.lineTo(width, y + 0.5);
sheetPickerCtx.stroke();
}
const cols = Math.max(1, sheet.cols);
const col = frameIndex % cols;
const row = Math.floor(frameIndex / cols);
sheetPickerCtx.strokeStyle = '#f59e0b';
sheetPickerCtx.lineWidth = 2;
sheetPickerCtx.strokeRect(col * tileW + 1, row * tileH + 1, tileW - 2, tileH - 2);
sheetPickerMeta.textContent = `${sheet.name} | Frame ${frameIndex} (col ${col}, row ${row})`;
};
if (sheetPickerLoadedSheetId === sheet.id && sheetPickerImage.complete) {
drawSelectedFrame();
return;
}
sheetPickerImage.onload = () => {
sheetPickerLoadedSheetId = sheet.id;
drawSelectedFrame();
};
sheetPickerImage.onerror = () => {
sheetPickerCanvas.width = 1;
sheetPickerCanvas.height = 1;
sheetPickerCtx.clearRect(0, 0, 1, 1);
sheetPickerMeta.textContent = `Failed to load sheet image: ${sheet.name}`;
};
sheetPickerImage.src = imageUrl;
}
function preloadSheetImage(sheetId) {
if (!sheetId || sheetImageCache.has(sheetId)) return;
const sheet = sheets.find(s => s.id === sheetId);
if (!sheet) return;
const url = resolveSheetImageUrl(sheet);
if (!url) return;
const img = new Image();
img.onload = () => renderChunk();
img.src = url;
sheetImageCache.set(sheetId, img);
}
function onZoomChanged() {
const value = parseFloat(document.getElementById('zoomLevel').value);
chunkZoom = Number.isFinite(value) ? Math.max(0.5, Math.min(4, value)) : 1;
renderChunk();
}
function adjustZoom(delta) {
const slider = document.getElementById('zoomLevel');
const current = parseFloat(slider.value) || 1;
const next = Math.max(0.5, Math.min(4, Math.round((current + delta) * 4) / 4));
slider.value = String(next);
onZoomChanged();
}
function resetZoom() {
document.getElementById('zoomLevel').value = '1';
onZoomChanged();
}
async function clearChunk() {
if (!currentChunk) return;
const s = selection();
const data = await postJson('/admin/worldeditor?handler=ClearChunk', s);
if (!data.success) return;
currentChunk.version = data.chunkVersion;
currentTiles.clear();
currentObjects = [];
currentNpcs = [];
currentMobs = [];
renderChunk();
loadZone();
}
async function deleteChunk() {
if (!currentChunk) return;
if (!confirm('Delete this chunk and all contained tiles/objects/NPC spawns/mob spawns?')) return;
const s = selection();
const data = await postJson('/admin/worldeditor?handler=DeleteChunk', s);
if (!data.success) return;
currentChunk = null;
currentTiles.clear();
currentObjects = [];
currentNpcs = [];
currentMobs = [];
chunkCtx.clearRect(0, 0, chunkCanvas.width, chunkCanvas.height);
document.getElementById('chunkMeta').textContent = 'Chunk deleted';
loadZone();
}
async function createRegion() {
const name = document.getElementById('newRegionName').value.trim();
if (!name) return;
const payload = {
name,
zonesPerRegionX: parseInt(document.getElementById('newZonesX').value, 10) || 4,
zonesPerRegionY: parseInt(document.getElementById('newZonesY').value, 10) || 4,
chunksPerZoneX: parseInt(document.getElementById('newChunksX').value, 10) || 8,
chunksPerZoneY: parseInt(document.getElementById('newChunksY').value, 10) || 8,
chunkWidthTiles: parseInt(document.getElementById('newChunkW').value, 10) || 64,
chunkHeightTiles: parseInt(document.getElementById('newChunkH').value, 10) || 64
};
const data = await postJson('/admin/worldeditor?handler=CreateRegion', payload);
if (!data.success || !data.region) return;
regions.push(data.region);
regions = regions.sort((a, b) => a.id - b.id);
refreshRegionSelect(data.region.id);
document.getElementById('zoneX').value = 0;
document.getElementById('zoneY').value = 0;
document.getElementById('chunkX').value = 0;
document.getElementById('chunkY').value = 0;
document.getElementById('newRegionName').value = '';
await loadRegion();
await loadChunk();
}
document.getElementById('frameIndex').addEventListener('input', onSheetChanged);
sheetPickerCanvas.addEventListener('click', (e) => {
const sheetId = parseInt(document.getElementById('sheetId').value, 10) || 0;
const sheet = sheets.find(s => s.id === sheetId);
if (!sheet) return;
const rect = sheetPickerCanvas.getBoundingClientRect();
if (rect.width <= 0 || rect.height <= 0) return;
const scaleX = sheetPickerCanvas.width / rect.width;
const scaleY = sheetPickerCanvas.height / rect.height;
const px = (e.clientX - rect.left) * scaleX;
const py = (e.clientY - rect.top) * scaleY;
const tileW = Math.max(1, sheet.tileW);
const tileH = Math.max(1, sheet.tileH);
const col = Math.floor(px / tileW);
const row = Math.floor(py / tileH);
if (col < 0 || row < 0) return;
const frame = row * Math.max(1, sheet.cols) + col;
document.getElementById('frameIndex').value = String(frame);
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();
});
window.addEventListener('beforeunload', () => {
if (eventSource) {
eventSource.close();
eventSource = null;
}
});
initSelectors();
loadRegion().then(loadChunk);
</script>
}