TileBuildChanges

This commit is contained in:
dingo
2026-01-09 07:08:41 -05:00
parent a12c4d5264
commit e803dafaea
9 changed files with 3835 additions and 61 deletions
@@ -180,49 +180,49 @@
<p class="text-xs text-gray-500 mt-2">Click cells to paint with selected tile. First tile placed becomes the primary.</p>
</div>
<!-- Socket Configuration -->
<!-- Socket Configuration (NEW) -->
<div class="card p-4">
<h3 class="font-semibold text-white mb-3">Edge Sockets</h3>
<p class="text-xs text-gray-500 mb-3">Sockets control how this template connects to neighbors.</p>
<p class="text-xs text-gray-500 mb-3">
Configure sockets for each edge. Multi-tile templates have one socket per edge cell.
<br/>Tiles connect when sockets match: Open↔Open, Closed↔Closed, Custom:name↔Custom:name
</p>
<div class="grid grid-cols-2 gap-4">
<div>
<label class="text-xs text-gray-400">North</label>
<select asp-for="Tile.SocketN" class="input w-full text-sm">
@foreach (var s in socketTypes) { <option value="@s">@s</option> }
</select>
</div>
<div>
<label class="text-xs text-gray-400">East</label>
<select asp-for="Tile.SocketE" class="input w-full text-sm">
@foreach (var s in socketTypes) { <option value="@s">@s</option> }
</select>
</div>
<div>
<label class="text-xs text-gray-400">South</label>
<select asp-for="Tile.SocketS" class="input w-full text-sm">
@foreach (var s in socketTypes) { <option value="@s">@s</option> }
</select>
</div>
<div>
<label class="text-xs text-gray-400">West</label>
<select asp-for="Tile.SocketW" class="input w-full text-sm">
@foreach (var s in socketTypes) { <option value="@s">@s</option> }
</select>
</div>
<input type="hidden" name="SocketConfigJson" id="socketConfigJson" value="@Model.SocketConfigJson" />
<!-- Socket Visual Editor -->
<div id="socketEditor" class="bg-gray-900 rounded p-4 mb-3">
<!-- Will be populated by JavaScript -->
</div>
<div class="mt-3">
<label class="text-xs text-gray-400">Custom Socket Names (comma-separated: N,E,S,W)</label>
<input type="text" asp-for="Tile.SocketCustom" class="input w-full text-sm" placeholder="wall-edge,wall-edge,open,open" />
<!-- Quick Actions -->
<div class="flex gap-2 mb-3">
<button type="button" onclick="setAllSocketsNew('Open')" class="btn btn-ghost text-xs flex-1">All Open</button>
<button type="button" onclick="setAllSocketsNew('Closed')" class="btn btn-ghost text-xs flex-1">All Closed</button>
<button type="button" onclick="autoSocketsNew()" class="btn btn-ghost text-xs flex-1">Auto</button>
</div>
<div class="flex gap-2 mt-3">
<button type="button" onclick="setAllSockets('Open')" class="btn btn-ghost text-xs flex-1">All Open</button>
<button type="button" onclick="setAllSockets('Closed')" class="btn btn-ghost text-xs flex-1">All Closed</button>
<button type="button" onclick="autoSockets()" class="btn btn-ghost text-xs flex-1">Auto</button>
<!-- Custom Socket Name Input with Autocomplete -->
<div class="relative" id="customNameContainer" style="display: none;">
<label class="text-xs text-gray-400">Custom Socket Name</label>
<input type="text" id="customNameInput" class="input w-full text-sm"
placeholder="Type to search or create..."
oninput="filterSocketNames(this.value)"
onfocus="showSocketDropdown()"
autocomplete="off" />
<div id="socketNameDropdown" class="absolute z-50 w-full bg-gray-800 border border-gray-600 rounded-b max-h-48 overflow-auto hidden">
<!-- Autocomplete options populated by JS -->
</div>
<p class="text-xs text-gray-500 mt-1">Names are stored lowercase. Click a suggestion or press Enter to create new.</p>
</div>
</div>
<!-- Legacy Socket Fields (hidden, for backward compatibility) -->
<input type="hidden" asp-for="Tile.SocketN" id="legacySocketN" />
<input type="hidden" asp-for="Tile.SocketE" id="legacySocketE" />
<input type="hidden" asp-for="Tile.SocketS" id="legacySocketS" />
<input type="hidden" asp-for="Tile.SocketW" id="legacySocketW" />
<input type="hidden" asp-for="Tile.SocketCustom" id="legacySocketCustom" />
</div>
<!-- Right: Tile Palette -->
@@ -457,32 +457,314 @@ function fillBorder() {
saveData();
}
function setAllSockets(type) {
document.querySelector('[name="Tile.SocketN"]').value = type;
document.querySelector('[name="Tile.SocketE"]').value = type;
document.querySelector('[name="Tile.SocketS"]').value = type;
document.querySelector('[name="Tile.SocketW"]').value = type;
// ============================================================
// NEW SOCKET EDITOR
// ============================================================
// All existing socket names for autocomplete (from server)
const allSocketNames = @Html.Raw(System.Text.Json.JsonSerializer.Serialize(Model.AllSocketNames));
// Current socket configuration
let socketConfig = { north: [], east: [], south: [], west: [] };
// Currently editing socket (for custom name input)
let editingSocket = null;
// Initialize socket config from hidden field
function initSocketConfig() {
const json = document.getElementById('socketConfigJson').value;
if (json) {
try {
socketConfig = JSON.parse(json);
} catch (e) {
console.error('Failed to parse socket config:', e);
}
}
// Ensure arrays exist and have correct length for current dimensions
resizeSocketConfig();
renderSocketEditor();
}
function autoSockets() {
const cat = document.querySelector('[name="Tile.Category"]').value;
if (cat === 'Floor' || cat === 'Decoration') {
setAllSockets('Open');
document.getElementById('isWalkable').checked = true;
} else if (cat === 'Wall') {
setAllSockets('Closed');
document.getElementById('isWalkable').checked = false;
} else if (cat === 'Door') {
// Vertical door default
document.querySelector('[name="Tile.SocketN"]').value = 'Open';
document.querySelector('[name="Tile.SocketS"]').value = 'Open';
document.querySelector('[name="Tile.SocketE"]').value = 'Closed';
document.querySelector('[name="Tile.SocketW"]').value = 'Closed';
// Resize socket arrays when template dimensions change
function resizeSocketConfig() {
const dirs = ['north', 'south', 'east', 'west'];
dirs.forEach(dir => {
if (!socketConfig[dir]) socketConfig[dir] = [];
});
// North and South have 'tw' sockets (width)
while (socketConfig.north.length < tw) socketConfig.north.push({ type: 'Open', customName: null });
while (socketConfig.north.length > tw) socketConfig.north.pop();
while (socketConfig.south.length < tw) socketConfig.south.push({ type: 'Open', customName: null });
while (socketConfig.south.length > tw) socketConfig.south.pop();
// East and West have 'th' sockets (height)
while (socketConfig.east.length < th) socketConfig.east.push({ type: 'Open', customName: null });
while (socketConfig.east.length > th) socketConfig.east.pop();
while (socketConfig.west.length < th) socketConfig.west.push({ type: 'Open', customName: null });
while (socketConfig.west.length > th) socketConfig.west.pop();
}
// Render the visual socket editor
function renderSocketEditor() {
const container = document.getElementById('socketEditor');
const cellSize = 40;
const socketSize = 12;
// Calculate grid dimensions
const gridW = tw * cellSize;
const gridH = th * cellSize;
const padding = 30; // Space for socket indicators
let html = `<div style="position: relative; width: ${gridW + padding*2}px; height: ${gridH + padding*2}px; margin: 0 auto;">`;
// Draw the template grid representation
html += `<div style="position: absolute; left: ${padding}px; top: ${padding}px; width: ${gridW}px; height: ${gridH}px;
background: #1a1a2e; border: 2px solid #374151; display: grid;
grid-template-columns: repeat(${tw}, 1fr); gap: 1px;">`;
for (let i = 0; i < tw * th; i++) {
html += `<div style="background: #0f0f1a;"></div>`;
}
html += `</div>`;
// North sockets (top edge)
for (let i = 0; i < tw; i++) {
const s = socketConfig.north[i];
const x = padding + (i + 0.5) * cellSize - socketSize/2;
const y = padding - socketSize - 4;
html += renderSocketButton('north', i, s, x, y);
}
// South sockets (bottom edge)
for (let i = 0; i < tw; i++) {
const s = socketConfig.south[i];
const x = padding + (i + 0.5) * cellSize - socketSize/2;
const y = padding + gridH + 4;
html += renderSocketButton('south', i, s, x, y);
}
// East sockets (right edge)
for (let i = 0; i < th; i++) {
const s = socketConfig.east[i];
const x = padding + gridW + 4;
const y = padding + (i + 0.5) * cellSize - socketSize/2;
html += renderSocketButton('east', i, s, x, y);
}
// West sockets (left edge)
for (let i = 0; i < th; i++) {
const s = socketConfig.west[i];
const x = padding - socketSize - 4;
const y = padding + (i + 0.5) * cellSize - socketSize/2;
html += renderSocketButton('west', i, s, x, y);
}
html += `</div>`;
// Legend
html += `<div class="flex gap-4 justify-center mt-3 text-xs">
<span class="flex items-center gap-1"><span class="w-3 h-3 rounded bg-green-500"></span> Open</span>
<span class="flex items-center gap-1"><span class="w-3 h-3 rounded bg-red-500"></span> Closed</span>
<span class="flex items-center gap-1"><span class="w-3 h-3 rounded bg-yellow-500"></span> Custom</span>
</div>`;
container.innerHTML = html;
}
function renderSocketButton(direction, index, socket, x, y) {
const colors = { 'Open': '#4ade80', 'Closed': '#f87171', 'Custom': '#facc15' };
const color = colors[socket?.type] || colors['Open'];
const title = socket?.type === 'Custom' ? `Custom: ${socket.customName || '(none)'}` : socket?.type || 'Open';
return `<button type="button"
onclick="cycleSocket('${direction}', ${index})"
oncontextmenu="editCustomSocket('${direction}', ${index}); return false;"
style="position: absolute; left: ${x}px; top: ${y}px; width: 12px; height: 12px;
background: ${color}; border: 1px solid rgba(255,255,255,0.3); border-radius: 2px;
cursor: pointer; font-size: 8px; line-height: 10px; text-align: center;"
title="${title} (click to cycle, right-click for custom)">
${socket?.type === 'Custom' ? 'C' : ''}
</button>`;
}
// Cycle through socket types: Open -> Closed -> Custom -> Open
function cycleSocket(direction, index) {
const socket = socketConfig[direction][index];
const types = ['Open', 'Closed', 'Custom'];
const currentIdx = types.indexOf(socket?.type || 'Open');
const nextType = types[(currentIdx + 1) % types.length];
socketConfig[direction][index] = {
type: nextType,
customName: nextType === 'Custom' ? (socket?.customName || '') : null
};
if (nextType === 'Custom') {
editCustomSocket(direction, index);
}
renderSocketEditor();
saveSocketConfig();
}
// Open custom name editor for a socket
function editCustomSocket(direction, index) {
editingSocket = { direction, index };
const socket = socketConfig[direction][index];
document.getElementById('customNameContainer').style.display = 'block';
const input = document.getElementById('customNameInput');
input.value = socket?.customName || '';
input.focus();
input.select();
// Update socket to Custom type if not already
if (socket?.type !== 'Custom') {
socketConfig[direction][index] = { type: 'Custom', customName: socket?.customName || '' };
renderSocketEditor();
}
}
// Filter socket names dropdown based on input
function filterSocketNames(query) {
const dropdown = document.getElementById('socketNameDropdown');
query = query.toLowerCase().trim();
let matches = allSocketNames.filter(name => name.includes(query));
// If query doesn't match anything exactly, allow creating new
const exactMatch = allSocketNames.includes(query);
let html = '';
if (query && !exactMatch) {
html += `<div class="px-3 py-2 hover:bg-gray-700 cursor-pointer text-yellow-400"
onclick="selectSocketName('${query.replace(/'/g, "\\'")}')">
Create: "${query}"
</div>`;
}
matches.slice(0, 15).forEach(name => {
html += `<div class="px-3 py-2 hover:bg-gray-700 cursor-pointer"
onclick="selectSocketName('${name.replace(/'/g, "\\'")}')">
${name}
</div>`;
});
if (!html) {
html = '<div class="px-3 py-2 text-gray-500">No matches</div>';
}
dropdown.innerHTML = html;
dropdown.classList.remove('hidden');
}
function showSocketDropdown() {
filterSocketNames(document.getElementById('customNameInput').value);
}
function hideSocketDropdown() {
setTimeout(() => {
document.getElementById('socketNameDropdown').classList.add('hidden');
}, 200);
}
function selectSocketName(name) {
name = name.toLowerCase().trim();
if (editingSocket) {
socketConfig[editingSocket.direction][editingSocket.index].customName = name;
renderSocketEditor();
saveSocketConfig();
}
document.getElementById('customNameInput').value = name;
document.getElementById('socketNameDropdown').classList.add('hidden');
// Add to local list if new
if (!allSocketNames.includes(name)) {
allSocketNames.push(name);
allSocketNames.sort();
}
}
// Handle Enter key in custom name input
document.addEventListener('DOMContentLoaded', () => {
const input = document.getElementById('customNameInput');
if (input) {
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
selectSocketName(input.value);
} else if (e.key === 'Escape') {
document.getElementById('customNameContainer').style.display = 'none';
editingSocket = null;
}
});
input.addEventListener('blur', hideSocketDropdown);
}
});
// Set all sockets to a type
function setAllSocketsNew(type) {
['north', 'south', 'east', 'west'].forEach(dir => {
socketConfig[dir].forEach((s, i) => {
socketConfig[dir][i] = { type: type, customName: null };
});
});
renderSocketEditor();
saveSocketConfig();
}
// Auto-configure sockets based on category
function autoSocketsNew() {
const cat = document.querySelector('[name="Tile.Category"]').value;
if (cat === 'Floor' || cat === 'Decoration') {
setAllSocketsNew('Open');
document.getElementById('isWalkable').checked = true;
} else if (cat === 'Wall') {
setAllSocketsNew('Closed');
document.getElementById('isWalkable').checked = false;
} else if (cat === 'Door') {
// Doors: Open on N/S, Closed on E/W
socketConfig.north.forEach((s, i) => socketConfig.north[i] = { type: 'Open', customName: null });
socketConfig.south.forEach((s, i) => socketConfig.south[i] = { type: 'Open', customName: null });
socketConfig.east.forEach((s, i) => socketConfig.east[i] = { type: 'Closed', customName: null });
socketConfig.west.forEach((s, i) => socketConfig.west[i] = { type: 'Closed', customName: null });
renderSocketEditor();
saveSocketConfig();
}
}
// Save socket config to hidden field
function saveSocketConfig() {
document.getElementById('socketConfigJson').value = JSON.stringify(socketConfig);
}
// Override resize to also resize sockets
const originalResizeTemplate = resizeTemplate;
function resizeTemplate() {
tw = +document.getElementById('tileWidth').value || 1;
th = +document.getElementById('tileHeight').value || 1;
tw = Math.max(1, Math.min(10, tw));
th = Math.max(1, Math.min(10, th));
buildTemplateGrid();
resizeSocketConfig();
renderSocketEditor();
saveSocketConfig();
}
// Legacy functions (keep for backward compatibility)
function setAllSockets(type) {
setAllSocketsNew(type);
}
function autoSockets() {
autoSocketsNew();
}
function onCategoryChange() {
autoSockets();
autoSocketsNew();
}
function saveData() {
@@ -491,7 +773,13 @@ function saveData() {
return { x, y, sheetId: v.sheetId, frameIndex: v.frameIndex, tileDefId: v.tileDefId };
});
document.getElementById('tilesJson').value = JSON.stringify(tiles);
saveSocketConfig();
}
document.getElementById('tileForm').onsubmit = () => saveData();
// Initialize socket editor on page load
document.addEventListener('DOMContentLoaded', () => {
initSocketConfig();
});
document.getElementById('tileForm').onsubmit = () => { saveData(); saveSocketConfig(); };
</script>
@@ -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;
@@ -9,6 +10,12 @@ public class TileEditModel : AdminPageModel
{
private readonly GameDbContext _db;
private readonly IConfiguration _config;
private static readonly JsonSerializerOptions _jsonOptions = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true
};
public TileEditModel(GameDbContext db, IConfiguration config)
{
@@ -19,8 +26,14 @@ public class TileEditModel : AdminPageModel
[BindProperty]
public TileTemplate Tile { get; set; } = new();
[BindProperty]
public string? SocketConfigJson { get; set; }
public List<TileMapSheet> TileSheets { get; set; } = new();
/// <summary>All existing socket names for autocomplete</summary>
public List<string> AllSocketNames { get; set; } = new();
public string CdnBaseUrl => NormalizeCdnBaseUrl(_config["Cdn:BaseUrl"]);
private string NormalizeCdnBaseUrl(string? baseUrl)
@@ -51,11 +64,19 @@ public class TileEditModel : AdminPageModel
if (tile != null)
{
Tile = tile;
SocketConfigJson = tile.SocketConfigJson;
// If no new config but has legacy data, migrate it
if (string.IsNullOrEmpty(SocketConfigJson))
{
var config = MigrateLegacySockets(tile);
SocketConfigJson = JsonSerializer.Serialize(config, _jsonOptions);
}
}
}
else
{
// Defaults
// Defaults for new template
Tile.IsEnabled = true;
Tile.Width = 1;
Tile.Height = 1;
@@ -66,6 +87,10 @@ public class TileEditModel : AdminPageModel
Tile.SocketE = SocketType.Open;
Tile.SocketS = SocketType.Open;
Tile.SocketW = SocketType.Open;
// Create default socket configuration
var defaultConfig = SocketConfiguration.CreateDefault(1, 1);
SocketConfigJson = JsonSerializer.Serialize(defaultConfig, _jsonOptions);
}
}
@@ -88,6 +113,36 @@ public class TileEditModel : AdminPageModel
Tile.PrimaryTileDefinitionId = null;
}
// Process socket configuration
if (!string.IsNullOrEmpty(SocketConfigJson))
{
Tile.SocketConfigJson = SocketConfigJson;
// Extract any new custom socket names and add to database
await ExtractAndSaveSocketNames(SocketConfigJson);
// Update legacy fields for backward compatibility
try
{
var config = JsonSerializer.Deserialize<SocketConfiguration>(SocketConfigJson, _jsonOptions);
if (config != null)
{
Tile.SocketN = config.North.FirstOrDefault()?.Type ?? SocketType.Open;
Tile.SocketE = config.East.FirstOrDefault()?.Type ?? SocketType.Open;
Tile.SocketS = config.South.FirstOrDefault()?.Type ?? SocketType.Open;
Tile.SocketW = config.West.FirstOrDefault()?.Type ?? SocketType.Open;
// Store first custom name found (legacy compatibility)
var customName = config.North.FirstOrDefault(s => s.Type == SocketType.Custom)?.CustomName
?? config.East.FirstOrDefault(s => s.Type == SocketType.Custom)?.CustomName
?? config.South.FirstOrDefault(s => s.Type == SocketType.Custom)?.CustomName
?? config.West.FirstOrDefault(s => s.Type == SocketType.Custom)?.CustomName;
Tile.SocketCustom = customName;
}
}
catch { /* Ignore parse errors, keep existing values */ }
}
if (Tile.Id == 0)
{
Tile.CreatedAt = DateTime.UtcNow;
@@ -122,6 +177,7 @@ public class TileEditModel : AdminPageModel
existing.SocketS = Tile.SocketS;
existing.SocketW = Tile.SocketW;
existing.SocketCustom = Tile.SocketCustom;
existing.SocketConfigJson = Tile.SocketConfigJson;
existing.Weight = Tile.Weight;
existing.MinTier = Tile.MinTier;
existing.MaxTier = Tile.MaxTier;
@@ -136,11 +192,111 @@ public class TileEditModel : AdminPageModel
return RedirectToPage(new { id = Tile.Id });
}
/// <summary>
/// API endpoint to get socket names for autocomplete
/// </summary>
public async Task<IActionResult> OnGetSocketNamesAsync(string? query)
{
var names = await _db.SocketNames
.Where(s => string.IsNullOrEmpty(query) || s.Name.Contains(query.ToLower()))
.OrderByDescending(s => s.UsageCount)
.ThenBy(s => s.Name)
.Take(20)
.Select(s => s.Name)
.ToListAsync();
return new JsonResult(names);
}
private async Task LoadReferenceData()
{
TileSheets = await _db.TileMapSheets
.Where(s => s.IsEnabled)
.OrderBy(s => s.Name)
.ToListAsync();
AllSocketNames = await _db.SocketNames
.OrderByDescending(s => s.UsageCount)
.ThenBy(s => s.Name)
.Select(s => s.Name)
.ToListAsync();
}
/// <summary>
/// Migrate legacy socket fields to new JSON format
/// </summary>
private SocketConfiguration MigrateLegacySockets(TileTemplate tile)
{
var config = SocketConfiguration.CreateDefault(tile.Width, tile.Height);
// Set first socket of each edge from legacy fields
if (config.North.Count > 0)
{
config.North[0].Type = tile.SocketN;
if (tile.SocketN == SocketType.Custom)
config.North[0].CustomName = tile.SocketCustom?.ToLower();
}
if (config.East.Count > 0)
{
config.East[0].Type = tile.SocketE;
if (tile.SocketE == SocketType.Custom)
config.East[0].CustomName = tile.SocketCustom?.ToLower();
}
if (config.South.Count > 0)
{
config.South[0].Type = tile.SocketS;
if (tile.SocketS == SocketType.Custom)
config.South[0].CustomName = tile.SocketCustom?.ToLower();
}
if (config.West.Count > 0)
{
config.West[0].Type = tile.SocketW;
if (tile.SocketW == SocketType.Custom)
config.West[0].CustomName = tile.SocketCustom?.ToLower();
}
return config;
}
/// <summary>
/// Extract custom socket names from config and add new ones to database
/// </summary>
private async Task ExtractAndSaveSocketNames(string configJson)
{
try
{
var config = JsonSerializer.Deserialize<SocketConfiguration>(configJson, _jsonOptions);
if (config == null) return;
var allSockets = config.North
.Concat(config.East)
.Concat(config.South)
.Concat(config.West);
var customNames = allSockets
.Where(s => s.Type == SocketType.Custom && !string.IsNullOrWhiteSpace(s.CustomName))
.Select(s => s.CustomName!.ToLower().Trim())
.Distinct()
.ToList();
foreach (var name in customNames)
{
var existing = await _db.SocketNames.FirstOrDefaultAsync(s => s.Name == name);
if (existing != null)
{
existing.UsageCount++;
}
else
{
_db.SocketNames.Add(new SocketName
{
Name = name,
UsageCount = 1,
CreatedAt = DateTime.UtcNow
});
}
}
}
catch { /* Ignore parse errors */ }
}
}