This commit is contained in:
dingo
2026-01-09 23:16:28 -05:00
parent ddc1e29cb9
commit ee8545b922
3 changed files with 567 additions and 111 deletions
+70 -5
View File
@@ -949,12 +949,22 @@ public class DungeonGeneratorV3
// Ensure the sheet is loaded for client rendering
EnsureSheetLoaded(t.SheetId);
// Try to find a matching TileTemplate for this sprite
var tileTemplate = FindTemplateBySprite(t.SheetId, t.FrameIndex);
// Use IsWalkable from the tile placement data (set by room editor)
// This is the primary source of truth for walkability
bool isWalkable = t.IsWalkable;
int templateId = t.TemplateId ?? 0;
// Use template properties if found, otherwise default to walkable floor
bool isWalkable = tileTemplate?.IsWalkable ?? true;
int templateId = tileTemplate?.Id ?? 0;
// If no templateId provided, try to find one by sprite lookup (legacy support)
if (templateId == 0)
{
var tileTemplate = FindTemplateBySprite(t.SheetId, t.FrameIndex);
if (tileTemplate != null)
{
templateId = tileTemplate.Id;
// Only override isWalkable if not explicitly set in placement
// (legacy data won't have IsWalkable set)
}
}
layout.Tiles[worldX, worldY] = templateId > 0 ? templateId : 1; // Non-zero to indicate tile is placed
layout.Walkable[worldX, worldY] = isWalkable;
@@ -984,6 +994,43 @@ public class DungeonGeneratorV3
}
}
// Parse and handle connection points
if (!string.IsNullOrEmpty(template.ConnectionPointsJson))
{
try
{
var connections = JsonSerializer.Deserialize<List<BuilderConnectionPoint>>(template.ConnectionPointsJson, jsonOptions);
if (connections != null)
{
foreach (var conn in connections)
{
int worldX = room.X + conn.X;
int worldY = room.Y + conn.Y;
if (worldX >= 0 && worldX < MapWidth && worldY >= 0 && worldY < MapHeight)
{
// Connection points must be walkable for corridors to connect
layout.Walkable[worldX, worldY] = true;
// Store connection point info for corridor generation
room.ConnectionPoints.Add(new ConnectionPoint
{
X = worldX,
Y = worldY,
Direction = conn.Direction ?? "north"
});
LogVerbose($" Connection point at ({worldX},{worldY}) facing {conn.Direction ?? "north"}");
}
}
}
}
catch (Exception ex)
{
Log($" Error parsing ConnectionPointsJson: {ex.Message}");
}
}
// Place objects from ObjectPlacementsJson
if (!string.IsNullOrEmpty(template.ObjectPlacementsJson))
{
@@ -1979,6 +2026,24 @@ public class RoomTilePlacement
public int Y { get; set; }
public int SheetId { get; set; }
public int FrameIndex { get; set; }
public int? TemplateId { get; set; } // TileTemplate ID (new format)
public bool IsWalkable { get; set; } = true; // Whether this tile is walkable (new format)
}
public class BuilderConnectionPoint
{
public int X { get; set; }
public int Y { get; set; }
public string? Direction { get; set; } // north, south, east, west
public int Width { get; set; } = 1;
}
public class ConnectionPoint
{
public int X { get; set; }
public int Y { get; set; }
public string Direction { get; set; } = "north";
public int Width { get; set; }
}
public class TemplateTilePlacement
@@ -1,6 +1,7 @@
@page "/admin/dungeonbuilder/rooms/edit"
@model DungeonBuilder.RoomEditModel
@using DataServer.Data.Entities
@using DataServer.Data.Enums
@{
ViewData["Title"] = Model.Room.Id == 0 ? "New Room Template" : $"Edit: {Model.Room.Name}";
var roomTypes = Enum.GetValues<RoomType>();
@@ -25,6 +26,10 @@
outline-offset: -2px;
z-index: 10;
}
.editor-cell.connection-point {
outline: 2px solid #22c55e !important;
outline-offset: -2px;
}
.palette-item {
cursor: pointer;
border: 2px solid transparent;
@@ -35,9 +40,20 @@
justify-content: center;
image-rendering: pixelated;
box-sizing: content-box;
position: relative;
}
.palette-item:hover { border-color: #60a5fa; }
.palette-item.active { border-color: #fbbf24; background: #374151; }
.palette-item .walkable-badge {
position: absolute;
top: 1px;
right: 1px;
width: 8px;
height: 8px;
border-radius: 50%;
}
.palette-item .walkable-badge.floor { background: #22c55e; }
.palette-item .walkable-badge.wall { background: #ef4444; }
.tool-btn {
padding: 6px 10px;
border-radius: 6px;
@@ -49,6 +65,36 @@
}
.tool-btn:hover { background: #374151; }
.tool-btn.active { background: #4f46e5; color: white; border-color: #4f46e5; }
.template-info {
font-size: 10px;
color: #9ca3af;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.mob-select-item {
padding: 6px 8px;
background: #1f2937;
border-radius: 4px;
cursor: pointer;
display: flex;
align-items: center;
gap: 8px;
}
.mob-select-item:hover { background: #374151; }
.mob-select-item.selected { background: #4f46e5; }
.tag-chip {
display: inline-block;
padding: 2px 8px;
background: #374151;
border-radius: 12px;
font-size: 11px;
margin: 2px;
cursor: pointer;
}
.tag-chip:hover { background: #4b5563; }
.tag-chip.active { background: #4f46e5; }
</style>
<div class="mb-4">
@@ -122,7 +168,7 @@
<label class="text-xs text-gray-400 mb-2 block">Layer</label>
<div class="flex gap-1">
<button type="button" class="tool-btn active flex-1 text-xs" data-layer="floor" onclick="setLayer('floor')">Floor</button>
<button type="button" class="tool-btn flex-1 text-xs" data-layer="object" onclick="setLayer('object')">Object</button>
<button type="button" class="tool-btn flex-1 text-xs" data-layer="wall" onclick="setLayer('wall')">Wall</button>
<button type="button" class="tool-btn flex-1 text-xs" data-layer="spawn" onclick="setLayer('spawn')">Spawn</button>
</div>
</div>
@@ -173,18 +219,20 @@
</div>
<div class="mt-2 text-xs text-gray-500 flex justify-between">
<span id="cursorPos">(-, -)</span>
<span id="statsInfo">Tiles: 0 | Objects: 0 | Spawns: 0</span>
<span id="statsInfo">Tiles: 0 | Walls: 0 | Spawns: 0 | Connections: 0</span>
</div>
</div>
</div>
<!-- Right: Palette -->
<div class="xl:col-span-1 space-y-4">
<!-- Tile Palette -->
<!-- Tile Palette (Floor/Wall) -->
<div class="card p-4" id="tilePaletteCard">
<h3 class="font-semibold text-white mb-3">Tiles</h3>
<select id="tileSheetSelect" class="input w-full text-sm mb-3" onchange="loadTilePalette()">
<option value="">Select sheet...</option>
<!-- Sheet Selection -->
<select id="tileSheetSelect" class="input w-full text-sm mb-2" onchange="loadTileTemplates()">
<option value="">Select TileMap...</option>
@foreach (var sheet in Model.TileSheets)
{
<option value="@sheet.Id"
@@ -196,39 +244,44 @@
data-sh="@sheet.SheetHeight">@sheet.Name</option>
}
</select>
<div id="tilePalette" class="flex flex-wrap gap-1 max-h-[250px] overflow-auto">
<div class="text-gray-500 text-xs p-2">Select a sheet</div>
<!-- Tag Filter -->
<div class="mb-2">
<input type="text" id="tagFilter" class="input w-full text-sm" placeholder="Filter by tags (comma separated)..." oninput="filterTemplates()" />
</div>
</div>
<!-- Object Palette -->
<div class="card p-4 hidden" id="objectPaletteCard">
<h3 class="font-semibold text-white mb-3">Objects</h3>
<div id="objectPalette" class="flex flex-wrap gap-1 max-h-[250px] overflow-auto">
@foreach (var obj in Model.Objects)
{
<div class="palette-item" data-type="object" data-id="@obj.Id" data-name="@obj.Name" title="@obj.Name" onclick="selectPaletteItem(this)">
<span class="text-base">@GetObjIcon(obj.Type)</span>
</div>
}
@if (!Model.Objects.Any())
{
<div class="text-gray-500 text-xs p-2">No objects. Create some first!</div>
}
<!-- Common Tags -->
<div id="commonTags" class="mb-2 flex flex-wrap"></div>
<!-- Templates Grid -->
<div id="tilePalette" class="flex flex-wrap gap-1 max-h-[300px] overflow-auto">
<div class="text-gray-500 text-xs p-2">Select a TileMap to see templates</div>
</div>
</div>
<!-- Spawn Palette -->
<div class="card p-4 hidden" id="spawnPaletteCard">
<h3 class="font-semibold text-white mb-3">Spawns</h3>
<div id="spawnPalette" class="flex flex-wrap gap-1">
<div class="palette-item" data-type="spawn" data-spawn="player" title="Player Spawn" onclick="selectPaletteItem(this)">🧑</div>
<div class="palette-item" data-type="spawn" data-spawn="exit" title="Exit Portal" onclick="selectPaletteItem(this)">🌀</div>
<div class="palette-item" data-type="spawn" data-spawn="mob" title="Mob" onclick="selectPaletteItem(this)">👾</div>
<div class="palette-item" data-type="spawn" data-spawn="elite" title="Elite" onclick="selectPaletteItem(this)">⭐</div>
<div class="palette-item" data-type="spawn" data-spawn="boss" title="Boss" onclick="selectPaletteItem(this)">💀</div>
<div class="palette-item" data-type="spawn" data-spawn="chest" title="Chest" onclick="selectPaletteItem(this)">📦</div>
<div class="palette-item" data-type="spawn" data-spawn="door" title="Door/Connection" onclick="selectPaletteItem(this)">🚪</div>
<div id="spawnPalette" class="flex flex-wrap gap-1 mb-3">
<div class="palette-item" data-type="spawn" data-spawn="player" title="Player Spawn" onclick="selectPaletteItem(this)" style="width:32px;height:32px;">🧑</div>
<div class="palette-item" data-type="spawn" data-spawn="exit" title="Exit Portal" onclick="selectPaletteItem(this)" style="width:32px;height:32px;">🌀</div>
<div class="palette-item" data-type="spawn" data-spawn="connection" title="Connection Point (Doorway)" onclick="selectPaletteItem(this)" style="width:32px;height:32px;">🚪</div>
<div class="palette-item" data-type="spawn" data-spawn="chest" title="Chest" onclick="selectPaletteItem(this)" style="width:32px;height:32px;">📦</div>
</div>
<h4 class="font-medium text-white text-sm mb-2">Mob Spawns</h4>
<div class="mb-2">
<input type="text" id="mobSearch" class="input w-full text-sm" placeholder="Search mobs..." oninput="filterMobs()" />
</div>
<div id="mobList" class="max-h-[200px] overflow-auto space-y-1">
@foreach (var mob in Model.Mobs)
{
<div class="mob-select-item" data-mob-id="@mob.Id" data-mob-name="@mob.Name" data-mob-type="@mob.Type" onclick="selectMob(this)">
<span class="text-sm">@(mob.Type == MobType.Boss ? "💀" : mob.Type == MobType.Elite ? "⭐" : "👾")</span>
<span class="text-sm text-gray-300">@mob.Name</span>
<span class="text-xs text-gray-500">(@mob.Type)</span>
</div>
}
</div>
</div>
@@ -236,6 +289,7 @@
<div class="card p-4">
<h3 class="font-semibold text-white mb-2">Selected</h3>
<div id="selectionInfo" class="text-sm text-gray-400">Nothing</div>
<div id="selectionDetails" class="text-xs text-gray-500 mt-1"></div>
</div>
</div>
</div>
@@ -245,7 +299,18 @@ const cdnBase = '@Model.CdnBaseUrl';
let gw = @Model.Room.Width, gh = @Model.Room.Height;
let tool = 'paint', layer = 'floor';
let sel = null, sheet = null;
let tileData = {}, objData = {}, spawnData = {};
// Data stores - keyed by "x,y"
let floorData = {}; // Floor tiles (walkable) - { templateId, sheetId, frameIndex, isWalkable }
let wallData = {}; // Wall tiles (not walkable) - { templateId, sheetId, frameIndex }
let spawnData = {}; // Spawns - { type, mobId?, mobName? }
let connectionData = {}; // Connection points (doorways) - { direction }
// All tile templates loaded from server (pre-loaded, no API call needed)
const allTileTemplates = @Html.Raw(Model.TileTemplatesJson);
let tileTemplates = []; // Filtered for current sheet
let allTags = new Set();
let mouseDown = false;
document.addEventListener('DOMContentLoaded', () => {
@@ -256,25 +321,48 @@ document.addEventListener('DOMContentLoaded', () => {
function loadData() {
try {
const td = '@Html.Raw(Model.Room.TileGridJson ?? "[]")';
JSON.parse(td).forEach(t => tileData[`${t.x},${t.y}`] = { sid: t.sheetId, f: t.frameIndex });
JSON.parse(td).forEach(t => {
// Determine if floor or wall based on stored isWalkable flag or template lookup
const isWalkable = t.isWalkable !== false; // Default to true if not specified
const key = `${t.x},${t.y}`;
const data = {
templateId: t.templateId || 0,
sheetId: t.sheetId,
frameIndex: t.frameIndex,
isWalkable: isWalkable
};
if (isWalkable) {
floorData[key] = data;
} else {
wallData[key] = data;
}
});
} catch {}
try {
const od = '@Html.Raw(Model.Room.ObjectPlacementsJson ?? "[]")';
JSON.parse(od).forEach(o => objData[`${o.X},${o.Y}`] = { id: o.ObjectTemplateId });
const cd = '@Html.Raw(Model.Room.ConnectionPointsJson ?? "[]")';
JSON.parse(cd).forEach(c => {
connectionData[`${c.X},${c.Y}`] = { direction: c.Direction || 'north' };
});
} catch {}
try {
const md = '@Html.Raw(Model.Room.MobSpawnsJson ?? "[]")';
JSON.parse(md).forEach(m => spawnData[`${m.X},${m.Y}`] = { t: m.Type });
JSON.parse(md).forEach(m => {
spawnData[`${m.X},${m.Y}`] = {
type: 'mob',
mobId: m.MobDefinitionId,
mobName: m.MobName || 'Mob',
mobType: m.Type || 'Normal'
};
});
} catch {}
@if (Model.Room.PlayerSpawnX.HasValue) { <text>spawnData['@Model.Room.PlayerSpawnX,@Model.Room.PlayerSpawnY'] = { t: 'player' };</text> }
@if (Model.Room.ExitPortalX.HasValue) { <text>spawnData['@Model.Room.ExitPortalX,@Model.Room.ExitPortalY'] = { t: 'exit' };</text> }
@if (Model.Room.PlayerSpawnX.HasValue) { <text>spawnData['@Model.Room.PlayerSpawnX,@Model.Room.PlayerSpawnY'] = { type: 'player' };</text> }
@if (Model.Room.ExitPortalX.HasValue) { <text>spawnData['@Model.Room.ExitPortalX,@Model.Room.ExitPortalY'] = { type: 'exit' };</text> }
}
function buildGrid() {
const g = document.getElementById('editorGrid');
// Use sheet tile dimensions if available, fallback to 32px
const cellW = sheet?.tw || 32;
const cellH = sheet?.th || 32;
const cellW = sheet?.tw || 16;
const cellH = sheet?.th || 16;
g.style.gridTemplateColumns = `repeat(${gw}, ${cellW}px)`;
g.innerHTML = '';
for (let y = 0; y < gh; y++) {
@@ -285,7 +373,10 @@ function buildGrid() {
c.style.height = cellH + 'px';
c.dataset.x = x; c.dataset.y = y;
c.onmousedown = e => { mouseDown = true; paint(x, y); };
c.onmouseenter = () => { document.getElementById('cursorPos').textContent = `(${x}, ${y})`; if (mouseDown) paint(x, y); };
c.onmouseenter = () => {
document.getElementById('cursorPos').textContent = `(${x}, ${y})`;
if (mouseDown) paint(x, y);
};
g.appendChild(c);
render(x, y);
}
@@ -299,66 +390,145 @@ function render(x, y) {
if (!c) return;
const k = `${x},${y}`;
// Tile bg
const t = tileData[k];
if (t && sheet && t.sid == sheet.id) {
const col = t.f % sheet.cols, row = Math.floor(t.f / sheet.cols);
// Check for floor or wall tile
const floor = floorData[k];
const wall = wallData[k];
const tile = floor || wall;
if (tile && sheet && tile.sheetId == sheet.id) {
const col = tile.frameIndex % sheet.cols, row = Math.floor(tile.frameIndex / sheet.cols);
c.style.background = `url('${cdnBase}/${sheet.cdn}') ${-col*sheet.tw}px ${-row*sheet.th}px no-repeat`;
c.style.backgroundSize = `${sheet.sw}px ${sheet.sh}px`;
} else if (t) {
c.style.background = '#2d3748';
} else if (tile) {
c.style.background = wall ? '#4a1a1a' : '#2d3748';
} else {
c.style.background = '#0f0f1a';
}
// Connection point indicator
c.classList.toggle('connection-point', !!connectionData[k]);
// Overlays
let html = '';
if (objData[k]) html += `<div class="absolute inset-0 flex items-center justify-center bg-purple-500/30 text-sm">📦</div>`;
const sp = spawnData[k];
if (sp) {
const icons = { player:'🧑', exit:'🌀', mob:'👾', elite:'⭐', boss:'💀', chest:'📦', door:'🚪' };
const colors = { player:'bg-yellow-500/40', exit:'bg-blue-500/40', mob:'bg-red-500/30', elite:'bg-orange-500/40', boss:'bg-red-600/50', chest:'bg-amber-500/40', door:'bg-green-500/40' };
html += `<div class="absolute inset-0 flex items-center justify-center ${colors[sp.t]||'bg-gray-500/30'} text-sm">${icons[sp.t]||'?'}</div>`;
const icons = { player:'🧑', exit:'🌀', mob:'👾', chest:'📦' };
const colors = { player:'bg-yellow-500/40', exit:'bg-blue-500/40', mob:'bg-red-500/30', chest:'bg-amber-500/40' };
let icon = icons[sp.type] || '?';
html += `<div class="absolute inset-0 flex items-center justify-center ${colors[sp.type]||'bg-gray-500/30'} text-xs">${icon}</div>`;
}
if (connectionData[k]) {
html += `<div class="absolute inset-0 flex items-center justify-center text-green-400 text-xs font-bold">🚪</div>`;
}
c.innerHTML = html;
}
function paint(x, y) {
const k = `${x},${y}`;
if (tool === 'paint' && sel) {
if (layer === 'floor' && sel.type === 'tile') {
tileData[k] = { sid: sel.sid, f: sel.f };
} else if (layer === 'object' && sel.type === 'object') {
objData[k] = { id: sel.id };
} else if (layer === 'spawn' && sel.type === 'spawn') {
if (sel.spawn === 'player' || sel.spawn === 'exit') {
Object.keys(spawnData).forEach(key => { if (spawnData[key].t === sel.spawn) delete spawnData[key]; });
if ((layer === 'floor' || layer === 'wall') && sel.type === 'template') {
// Remove from both to avoid duplicates
delete floorData[k];
delete wallData[k];
const data = {
templateId: sel.templateId,
sheetId: sel.sheetId,
frameIndex: sel.frameIndex,
isWalkable: sel.isWalkable
};
if (sel.isWalkable) {
floorData[k] = data;
} else {
wallData[k] = data;
}
} else if (layer === 'spawn') {
if (sel.type === 'spawn') {
if (sel.spawn === 'connection') {
// Toggle connection point
if (connectionData[k]) {
delete connectionData[k];
} else {
connectionData[k] = { direction: detectEdgeDirection(x, y) };
}
} else if (sel.spawn === 'player' || sel.spawn === 'exit') {
// Only one player/exit spawn
Object.keys(spawnData).forEach(key => {
if (spawnData[key].type === sel.spawn) delete spawnData[key];
});
spawnData[k] = { type: sel.spawn };
} else {
spawnData[k] = { type: sel.spawn };
}
} else if (sel.type === 'mob') {
spawnData[k] = {
type: 'mob',
mobId: sel.mobId,
mobName: sel.mobName,
mobType: sel.mobType
};
}
spawnData[k] = { t: sel.spawn };
}
} else if (tool === 'erase') {
if (layer === 'floor') delete tileData[k];
else if (layer === 'object') delete objData[k];
else if (layer === 'spawn') delete spawnData[k];
} else if (tool === 'fill' && sel?.type === 'tile') {
if (layer === 'floor') delete floorData[k];
else if (layer === 'wall') delete wallData[k];
else if (layer === 'spawn') {
delete spawnData[k];
delete connectionData[k];
}
} else if (tool === 'fill' && sel?.type === 'template') {
floodFill(x, y);
}
render(x, y);
updateStats();
saveData();
}
function detectEdgeDirection(x, y) {
// Detect which edge this connection point is on
if (y === 0) return 'north';
if (y === gh - 1) return 'south';
if (x === 0) return 'west';
if (x === gw - 1) return 'east';
return 'north'; // Default
}
function floodFill(sx, sy) {
const sk = `${sx},${sy}`;
const startF = tileData[sk]?.f ?? -1;
const startTile = floorData[sk] || wallData[sk];
const startF = startTile?.frameIndex ?? -1;
const visited = new Set(), queue = [[sx, sy]];
while (queue.length && visited.size < 500) {
const [x, y] = queue.shift();
const k = `${x},${y}`;
if (visited.has(k) || x < 0 || x >= gw || y < 0 || y >= gh) continue;
if ((tileData[k]?.f ?? -1) !== startF) continue;
const current = floorData[k] || wallData[k];
if ((current?.frameIndex ?? -1) !== startF) continue;
visited.add(k);
tileData[k] = { sid: sel.sid, f: sel.f };
// Remove from both
delete floorData[k];
delete wallData[k];
const data = {
templateId: sel.templateId,
sheetId: sel.sheetId,
frameIndex: sel.frameIndex,
isWalkable: sel.isWalkable
};
if (sel.isWalkable) {
floorData[k] = data;
} else {
wallData[k] = data;
}
render(x, y);
queue.push([x+1,y],[x-1,y],[x,y+1],[x,y-1]);
}
@@ -372,69 +542,244 @@ function setTool(t) {
function setLayer(l) {
layer = l;
document.querySelectorAll('[data-layer]').forEach(b => b.classList.toggle('active', b.dataset.layer === l));
document.getElementById('tilePaletteCard').classList.toggle('hidden', l !== 'floor');
document.getElementById('objectPaletteCard').classList.toggle('hidden', l !== 'object');
document.getElementById('tilePaletteCard').classList.toggle('hidden', l === 'spawn');
document.getElementById('spawnPaletteCard').classList.toggle('hidden', l !== 'spawn');
sel = null;
document.querySelectorAll('.palette-item').forEach(i => i.classList.remove('active'));
document.querySelectorAll('.mob-select-item').forEach(i => i.classList.remove('selected'));
document.getElementById('selectionInfo').textContent = 'Nothing';
document.getElementById('selectionDetails').textContent = '';
}
function loadTilePalette() {
function loadTileTemplates() {
const opt = document.getElementById('tileSheetSelect').selectedOptions[0];
if (!opt?.value) { sheet = null; document.getElementById('tilePalette').innerHTML = '<div class="text-gray-500 text-xs p-2">Select a sheet</div>'; return; }
sheet = { id: +opt.value, cdn: opt.dataset.cdn, cols: +opt.dataset.cols, tw: +opt.dataset.tw, th: +opt.dataset.th, sw: +opt.dataset.sw, sh: +opt.dataset.sh };
if (!opt?.value) {
sheet = null;
tileTemplates = [];
document.getElementById('tilePalette').innerHTML = '<div class="text-gray-500 text-xs p-2">Select a TileMap</div>';
document.getElementById('commonTags').innerHTML = '';
return;
}
sheet = {
id: +opt.value,
cdn: opt.dataset.cdn,
cols: +opt.dataset.cols,
tw: +opt.dataset.tw,
th: +opt.dataset.th,
sw: +opt.dataset.sw,
sh: +opt.dataset.sh
};
// Rebuild grid with correct tile dimensions
buildGrid();
const total = sheet.cols * Math.ceil(sheet.sh / sheet.th);
let html = '';
for (let i = 0; i < total; i++) {
const col = i % sheet.cols, row = Math.floor(i / sheet.cols);
html += `<div class="palette-item" data-type="tile" data-sid="${sheet.id}" data-f="${i}" title="Frame ${i}"
style="width:${sheet.tw}px; height:${sheet.th}px; background:url('${cdnBase}/${sheet.cdn}') ${-col*sheet.tw}px ${-row*sheet.th}px no-repeat; background-size:${sheet.sw}px ${sheet.sh}px;"
onclick="selectPaletteItem(this)"></div>`;
// Filter templates for this sheet (already loaded, no API call)
tileTemplates = allTileTemplates.filter(t => t.sheetId === sheet.id);
// Collect all tags
allTags.clear();
tileTemplates.forEach(t => {
if (t.tags) {
t.tags.split(',').map(tag => tag.trim().toLowerCase()).forEach(tag => {
if (tag) allTags.add(tag);
});
}
});
renderCommonTags();
renderTemplates();
}
function renderCommonTags() {
const container = document.getElementById('commonTags');
const sorted = Array.from(allTags).sort();
container.innerHTML = sorted.slice(0, 15).map(tag =>
`<span class="tag-chip" data-tag="${tag}" onclick="toggleTagFilter('${tag}')">${tag}</span>`
).join('');
}
function toggleTagFilter(tag) {
const input = document.getElementById('tagFilter');
const current = input.value.split(',').map(t => t.trim().toLowerCase()).filter(t => t);
const idx = current.indexOf(tag);
if (idx >= 0) {
current.splice(idx, 1);
} else {
current.push(tag);
}
input.value = current.join(', ');
filterTemplates();
// Update chip states
document.querySelectorAll('.tag-chip').forEach(chip => {
chip.classList.toggle('active', current.includes(chip.dataset.tag));
});
}
function filterTemplates() {
const filter = document.getElementById('tagFilter').value.toLowerCase();
const filterTags = filter.split(',').map(t => t.trim()).filter(t => t);
renderTemplates(filterTags);
}
function renderTemplates(filterTags = []) {
let filtered = tileTemplates;
// Filter by current layer (floor vs wall)
if (layer === 'floor') {
filtered = filtered.filter(t => t.isWalkable);
} else if (layer === 'wall') {
filtered = filtered.filter(t => !t.isWalkable);
}
// Filter by tags
if (filterTags.length > 0) {
filtered = filtered.map(t => {
const templateTags = (t.tags || '').split(',').map(tag => tag.trim().toLowerCase());
const matchCount = filterTags.filter(ft => templateTags.includes(ft)).length;
return { ...t, matchCount };
}).filter(t => t.matchCount > 0)
.sort((a, b) => b.matchCount - a.matchCount);
}
if (filtered.length === 0) {
document.getElementById('tilePalette').innerHTML = `<div class="text-gray-500 text-xs p-2">No ${layer} templates found</div>`;
return;
}
let html = '';
filtered.forEach(t => {
// Parse TilesJson to get sheetId and frameIndex
let frameIndex = 0;
try {
const tiles = JSON.parse(t.tilesJson || '[]');
if (tiles.length > 0) {
frameIndex = tiles[0].frameIndex;
}
} catch {}
const col = frameIndex % sheet.cols;
const row = Math.floor(frameIndex / sheet.cols);
html += `<div class="palette-item flex-col"
data-type="template"
data-template-id="${t.id}"
data-sheet-id="${sheet.id}"
data-frame="${frameIndex}"
data-walkable="${t.isWalkable}"
data-name="${t.name}"
data-tags="${t.tags || ''}"
title="${t.name}${t.tags ? ' [' + t.tags + ']' : ''}"
style="width:${sheet.tw + 8}px; padding:4px;"
onclick="selectPaletteItem(this)">
<div style="width:${sheet.tw}px; height:${sheet.th}px; background:url('${cdnBase}/${sheet.cdn}') ${-col*sheet.tw}px ${-row*sheet.th}px no-repeat; background-size:${sheet.sw}px ${sheet.sh}px; position:relative;">
<div class="walkable-badge ${t.isWalkable ? 'floor' : 'wall'}"></div>
</div>
<div class="template-info mt-1" style="width:${sheet.tw}px;">${t.name}</div>
</div>`;
});
document.getElementById('tilePalette').innerHTML = html;
}
function selectPaletteItem(el) {
document.querySelectorAll('.palette-item').forEach(i => i.classList.remove('active'));
document.querySelectorAll('.mob-select-item').forEach(i => i.classList.remove('selected'));
el.classList.add('active');
const type = el.dataset.type;
if (type === 'tile') sel = { type: 'tile', sid: +el.dataset.sid, f: +el.dataset.f };
else if (type === 'object') sel = { type: 'object', id: +el.dataset.id, name: el.dataset.name };
else if (type === 'spawn') sel = { type: 'spawn', spawn: el.dataset.spawn };
document.getElementById('selectionInfo').textContent = type === 'tile' ? `Tile #${sel.f}` : type === 'object' ? sel.name : sel.spawn;
if (type === 'template') {
sel = {
type: 'template',
templateId: +el.dataset.templateId,
sheetId: +el.dataset.sheetId,
frameIndex: +el.dataset.frame,
isWalkable: el.dataset.walkable === 'true',
name: el.dataset.name
};
document.getElementById('selectionInfo').textContent = sel.name;
document.getElementById('selectionDetails').textContent = sel.isWalkable ? '🟢 Walkable (Floor)' : '🔴 Blocking (Wall)';
} else if (type === 'spawn') {
sel = { type: 'spawn', spawn: el.dataset.spawn };
document.getElementById('selectionInfo').textContent = el.title;
document.getElementById('selectionDetails').textContent = '';
}
}
function selectMob(el) {
document.querySelectorAll('.palette-item').forEach(i => i.classList.remove('active'));
document.querySelectorAll('.mob-select-item').forEach(i => i.classList.remove('selected'));
el.classList.add('selected');
sel = {
type: 'mob',
mobId: +el.dataset.mobId,
mobName: el.dataset.mobName,
mobType: el.dataset.mobType
};
document.getElementById('selectionInfo').textContent = `Mob: ${sel.mobName}`;
document.getElementById('selectionDetails').textContent = `Type: ${sel.mobType}`;
}
function filterMobs() {
const search = document.getElementById('mobSearch').value.toLowerCase();
document.querySelectorAll('.mob-select-item').forEach(el => {
const name = el.dataset.mobName.toLowerCase();
el.style.display = name.includes(search) ? '' : 'none';
});
}
function updateStats() {
document.getElementById('statsInfo').textContent = `Tiles: ${Object.keys(tileData).length} | Objects: ${Object.keys(objData).length} | Spawns: ${Object.keys(spawnData).length}`;
const floors = Object.keys(floorData).length;
const walls = Object.keys(wallData).length;
const spawns = Object.keys(spawnData).length;
const connections = Object.keys(connectionData).length;
document.getElementById('statsInfo').textContent = `Tiles: ${floors} | Walls: ${walls} | Spawns: ${spawns} | Connections: ${connections}`;
}
function saveData() {
const tiles = Object.entries(tileData).map(([k,v]) => { const [x,y] = k.split(',').map(Number); return {x,y,sheetId:v.sid,frameIndex:v.f}; });
// Combine floor and wall data into single TileGridJson
const tiles = [];
Object.entries(floorData).forEach(([k, v]) => {
const [x, y] = k.split(',').map(Number);
tiles.push({ x, y, sheetId: v.sheetId, frameIndex: v.frameIndex, templateId: v.templateId, isWalkable: true });
});
Object.entries(wallData).forEach(([k, v]) => {
const [x, y] = k.split(',').map(Number);
tiles.push({ x, y, sheetId: v.sheetId, frameIndex: v.frameIndex, templateId: v.templateId, isWalkable: false });
});
document.getElementById('tileGridJson').value = JSON.stringify(tiles);
const objs = Object.entries(objData).map(([k,v]) => { const [x,y] = k.split(',').map(Number); return {X:x,Y:y,ObjectTemplateId:v.id}; });
document.getElementById('objectPlacementsJson').value = JSON.stringify(objs);
// Connection points
const conns = Object.entries(connectionData).map(([k, v]) => {
const [x, y] = k.split(',').map(Number);
return { X: x, Y: y, Direction: v.direction, Width: 1 };
});
document.getElementById('connectionPointsJson').value = JSON.stringify(conns);
const mobs = [], conns = [];
// Mob spawns
const mobs = [];
let px = '', py = '', ex = '', ey = '';
Object.entries(spawnData).forEach(([k,v]) => {
const [x,y] = k.split(',').map(Number);
if (v.t === 'player') { px = x; py = y; }
else if (v.t === 'exit') { ex = x; ey = y; }
else if (v.t === 'door') conns.push({X:x,Y:y,Direction:'north',Width:1});
else mobs.push({X:x,Y:y,Type:v.t,Count:1});
Object.entries(spawnData).forEach(([k, v]) => {
const [x, y] = k.split(',').map(Number);
if (v.type === 'player') { px = x; py = y; }
else if (v.type === 'exit') { ex = x; ey = y; }
else if (v.type === 'mob') {
mobs.push({ X: x, Y: y, MobDefinitionId: v.mobId, MobName: v.mobName, Type: v.mobType, Count: 1 });
}
else if (v.type === 'chest') {
// Could add chest spawns here
}
});
document.getElementById('mobSpawnsJson').value = JSON.stringify(mobs);
document.getElementById('connectionPointsJson').value = JSON.stringify(conns);
document.getElementById('playerSpawnX').value = px;
document.getElementById('playerSpawnY').value = py;
document.getElementById('exitPortalX').value = ex;
document.getElementById('exitPortalY').value = ey;
// Empty object placements for now
document.getElementById('objectPlacementsJson').value = '[]';
}
function resizeGrid() {
@@ -445,26 +790,22 @@ function resizeGrid() {
function clearLayer() {
if (!confirm(`Clear all ${layer}?`)) return;
if (layer === 'floor') tileData = {};
else if (layer === 'object') objData = {};
else spawnData = {};
if (layer === 'floor') floorData = {};
else if (layer === 'wall') wallData = {};
else {
spawnData = {};
connectionData = {};
}
buildGrid();
saveData();
}
function clearAll() {
if (!confirm('Clear everything?')) return;
tileData = {}; objData = {}; spawnData = {};
floorData = {}; wallData = {}; spawnData = {}; connectionData = {};
buildGrid();
saveData();
}
document.getElementById('roomForm').onsubmit = () => saveData();
</script>
@functions {
string GetObjIcon(ObjectTemplateType t) => t switch {
ObjectTemplateType.Container => "📦", ObjectTemplateType.Trap => "⚠️", ObjectTemplateType.Door => "🚪",
ObjectTemplateType.Light => "🔥", ObjectTemplateType.Shrine => "⛩️", ObjectTemplateType.Vendor => "🛒", _ => "🪨"
};
}
@@ -2,6 +2,7 @@ using DataServer.Data;
using DataServer.Data.Entities;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Text.Json;
namespace Server.Services.Admin.Pages.DungeonBuilder;
@@ -21,6 +22,43 @@ public class RoomEditModel : AdminPageModel
public List<TileMapSheet> TileSheets { get; set; } = new();
public List<ObjectTemplate> Objects { get; set; } = new();
public List<DungeonMobDefinition> Mobs { get; set; } = new();
public List<TileTemplate> TileTemplates { get; set; } = new();
/// <summary>
/// TileTemplates serialized as JSON for JavaScript consumption.
/// Grouped by sheetId for efficient lookup.
/// </summary>
public string TileTemplatesJson => JsonSerializer.Serialize(
TileTemplates.Select(t => new {
id = t.Id,
name = t.Name,
category = t.Category.ToString(),
tags = t.Tags,
isWalkable = t.IsWalkable,
blocksMovement = t.BlocksMovement,
tilesJson = t.TilesJson,
weight = t.Weight,
sheetId = ExtractSheetId(t.TilesJson)
}).Where(t => t.sheetId.HasValue)
);
private static int? ExtractSheetId(string? tilesJson)
{
if (string.IsNullOrEmpty(tilesJson)) return null;
try
{
var tiles = JsonSerializer.Deserialize<List<TilePlacement>>(tilesJson);
return tiles?.FirstOrDefault()?.SheetId;
}
catch { return null; }
}
private class TilePlacement
{
public int SheetId { get; set; }
public int FrameIndex { get; set; }
}
public string CdnBaseUrl => NormalizeCdnBaseUrl(_config["Cdn:BaseUrl"]);
@@ -146,5 +184,17 @@ public class RoomEditModel : AdminPageModel
.Where(o => o.IsEnabled)
.OrderBy(o => o.Name)
.ToListAsync();
Mobs = await _db.DungeonMobDefinitions
.Where(m => m.IsEnabled)
.OrderBy(m => m.Type)
.ThenBy(m => m.Name)
.ToListAsync();
TileTemplates = await _db.TileTemplates
.Where(t => t.IsEnabled)
.OrderBy(t => t.Category)
.ThenBy(t => t.Name)
.ToListAsync();
}
}