Dungeon Builder Change

This commit is contained in:
dingo
2026-01-31 18:51:45 -05:00
parent f7e60cf947
commit 739c624b71
28 changed files with 2575 additions and 18 deletions
+201 -1
View File
@@ -31,6 +31,11 @@ public class DungeonGeneratorV3
/// compatibility with neighboring tiles' sockets.
/// </summary>
public static bool UseSocketMatching { get; set; } = true;
/// <summary>
/// Enable bucket-based adjacency rules (allow-lists).
/// </summary>
public static bool UseBucketMatching { get; set; } = true;
// ============================================================
// DEPENDENCIES
@@ -99,6 +104,15 @@ public class DungeonGeneratorV3
// Tile data cache
private Dictionary<int, TileDefinition> _tileDefinitions = new();
private Dictionary<int, TileMapSheet> _tileSheets = new();
// Bucket rules and tile bucket assignments
private Dictionary<int, HashSet<int>> _tileBucketsByDefinitionId = new();
private Dictionary<int, HashSet<int>> _bucketRules = new();
private Dictionary<int, string> _bucketNames = new();
private Dictionary<int, string?> _bucketTypes = new();
private HashSet<int> _paletteAllowedBuckets = new();
private bool _enforceBiomeBuckets = false;
private string? _paletteBiome = null;
// Generation parameters (from palette or defaults)
private int _minRooms = 5;
@@ -275,6 +289,10 @@ public class DungeonGeneratorV3
Log($" Room Size: {_palette.MinRoomWidth}-{_palette.MaxRoomWidth} x {_palette.MinRoomHeight}-{_palette.MaxRoomHeight}");
Log($" Corridor Width: {_palette.MinCorridorWidth}-{_palette.MaxCorridorWidth}");
Log($" Densities: Decor={_palette.DecorationDensity}%, Trap={_palette.TrapDensity}%, Container={_palette.ContainerDensity}%");
_paletteAllowedBuckets = ParseIds(_palette.AllowedBucketIdsJson).ToHashSet();
_enforceBiomeBuckets = _palette.EnforceBiomeBuckets;
_paletteBiome = _palette.Biome;
// Apply palette generation parameters
_minRooms = _palette.MinRooms;
@@ -523,6 +541,9 @@ public class DungeonGeneratorV3
var walkable = _tileDefinitions.Values.Count(t => t.IsWalkable);
var nonWalkable = _tileDefinitions.Values.Count(t => !t.IsWalkable);
Log($" Walkable: {walkable}, Non-walkable: {nonWalkable}");
await LoadBucketDataAsync();
ApplyBucketFilters();
}
private async Task<List<DungeonRoomV2>> GenerateRoomsAsync(DungeonLayoutV2 layout)
@@ -926,6 +947,120 @@ public class DungeonGeneratorV3
return new List<int>();
}
}
private async Task LoadBucketDataAsync()
{
_tileBucketsByDefinitionId.Clear();
_bucketRules.Clear();
_bucketNames.Clear();
_bucketTypes.Clear();
var buckets = await _db.TileBuckets
.Where(b => b.IsEnabled)
.ToListAsync();
foreach (var b in buckets)
{
_bucketNames[b.Id] = b.Name.ToLower();
_bucketTypes[b.Id] = b.BucketType?.ToLower();
}
var rules = await _db.TileBucketRules.ToListAsync();
foreach (var rule in rules)
{
if (!_bucketRules.TryGetValue(rule.SourceBucketId, out var targets))
{
targets = new HashSet<int>();
_bucketRules[rule.SourceBucketId] = targets;
}
targets.Add(rule.TargetBucketId);
}
var links = await _db.TileDefinitionBuckets
.ToListAsync();
foreach (var link in links)
{
if (!_tileBucketsByDefinitionId.TryGetValue(link.TileDefinitionId, out var bucketSet))
{
bucketSet = new HashSet<int>();
_tileBucketsByDefinitionId[link.TileDefinitionId] = bucketSet;
}
bucketSet.Add(link.TileBucketId);
}
Log($"Loaded bucket rules: {_bucketRules.Count} source buckets, tile bucket links: {_tileBucketsByDefinitionId.Count}");
}
private void ApplyBucketFilters()
{
if (_paletteAllowedBuckets.Count == 0 && !_enforceBiomeBuckets)
{
return;
}
_floorTemplates = _floorTemplates.Where(TemplateMatchesBucketFilters).ToList();
_wallTemplates = _wallTemplates.Where(TemplateMatchesBucketFilters).ToList();
_doorTemplates = _doorTemplates.Where(TemplateMatchesBucketFilters).ToList();
Log($"Bucket filtering applied: floors={_floorTemplates.Count}, walls={_wallTemplates.Count}, doors={_doorTemplates.Count}");
ParseSocketConfigurations();
BuildSpriteToTemplateLookup();
}
private bool TemplateMatchesBucketFilters(TileTemplate template)
{
var buckets = GetTemplateBucketIds(template);
if (_paletteAllowedBuckets.Count > 0)
{
if (buckets.Count == 0) return false;
if (!buckets.Overlaps(_paletteAllowedBuckets)) return false;
}
if (_enforceBiomeBuckets && !string.IsNullOrWhiteSpace(_paletteBiome))
{
if (!TemplateMatchesBiomeBucket(buckets)) return false;
}
return true;
}
private bool TemplateMatchesBiomeBucket(HashSet<int> bucketIds)
{
if (bucketIds.Count == 0) return false;
var biome = _paletteBiome?.Trim().ToLower();
if (string.IsNullOrEmpty(biome)) return true;
foreach (var id in bucketIds)
{
if (_bucketNames.TryGetValue(id, out var name))
{
if (name == biome || name == $"biome_{biome}")
{
return true;
}
}
if (_bucketTypes.TryGetValue(id, out var type) && type == "biome" && _bucketNames.TryGetValue(id, out var n2) && n2 == biome)
{
return true;
}
}
return false;
}
private HashSet<int> GetTemplateBucketIds(TileTemplate template)
{
if (template.PrimaryTileDefinitionId.HasValue &&
_tileBucketsByDefinitionId.TryGetValue(template.PrimaryTileDefinitionId.Value, out var buckets))
{
return buckets;
}
return new HashSet<int>();
}
private async Task StampRoomTemplateAsync(DungeonLayoutV2 layout, DungeonRoomV2 room, BuilderRoomTemplate template)
{
Log($" Stamping room template '{template.Name}' at ({room.X},{room.Y})");
@@ -1762,6 +1897,7 @@ public class DungeonGeneratorV3
/// </summary>
private bool IsSocketCompatible(TileTemplate template, int x, int y, DungeonLayoutV2 layout)
{
if (!IsBucketCompatible(template, x, y, layout)) return false;
if (!UseSocketMatching) return true;
if (!_templateSocketConfigs.TryGetValue(template.Id, out var config)) return true;
@@ -1837,6 +1973,70 @@ public class DungeonGeneratorV3
return true;
}
private bool IsBucketCompatible(TileTemplate template, int x, int y, DungeonLayoutV2 layout)
{
if (!UseBucketMatching || _bucketRules.Count == 0) return true;
var sourceBuckets = GetTemplateBucketIds(template);
if (sourceBuckets.Count == 0) return true;
if (y > 0 && _placedTemplates.TryGetValue($"{x},{y-1}", out var northTemplateId))
{
if (!TemplatesBucketsCompatible(sourceBuckets, GetTemplateBucketIdsById(northTemplateId)))
return false;
}
if (y < layout.Height - 1 && _placedTemplates.TryGetValue($"{x},{y+1}", out var southTemplateId))
{
if (!TemplatesBucketsCompatible(sourceBuckets, GetTemplateBucketIdsById(southTemplateId)))
return false;
}
if (x < layout.Width - 1 && _placedTemplates.TryGetValue($"{x+1},{y}", out var eastTemplateId))
{
if (!TemplatesBucketsCompatible(sourceBuckets, GetTemplateBucketIdsById(eastTemplateId)))
return false;
}
if (x > 0 && _placedTemplates.TryGetValue($"{x-1},{y}", out var westTemplateId))
{
if (!TemplatesBucketsCompatible(sourceBuckets, GetTemplateBucketIdsById(westTemplateId)))
return false;
}
return true;
}
private HashSet<int> GetTemplateBucketIdsById(int templateId)
{
var template = _floorTemplates.FirstOrDefault(t => t.Id == templateId)
?? _wallTemplates.FirstOrDefault(t => t.Id == templateId)
?? _doorTemplates.FirstOrDefault(t => t.Id == templateId);
return template == null ? new HashSet<int>() : GetTemplateBucketIds(template);
}
private bool TemplatesBucketsCompatible(HashSet<int> sourceBuckets, HashSet<int> targetBuckets)
{
if (_bucketRules.Count == 0) return true;
if (sourceBuckets.Count == 0 || targetBuckets.Count == 0) return true;
var anyRule = false;
foreach (var source in sourceBuckets)
{
if (_bucketRules.TryGetValue(source, out var allowed))
{
anyRule = true;
if (allowed.Overlaps(targetBuckets))
{
return true;
}
}
}
return !anyRule;
}
/// <summary>
/// Calculate a socket compatibility score for a template at a given position.
@@ -2073,4 +2273,4 @@ public class TemplateTilePlacement
public int FrameIndex { get; set; }
public int? TileDefId { get; set; }
public int Layer { get; set; }
}
}
+196
View File
@@ -0,0 +1,196 @@
# REVAMP Notes: Current Dungeon Builder, TileMaps, and DungeonSimulation
This document describes how the current systems work (no code), based on the admin pages and the runtime simulation.
## 1) Dungeon Builder (Admin UI)
### 1.1 Overview Page
- The Dungeon Builder landing page shows counts of Tile Templates, Object Templates, Room Templates, and Palettes.
- It provides navigation to each editor and a “Test Generator” preview tool.
- Recent items are pulled from each template type and displayed with edit links.
### 1.2 Tile Templates
**Where:** `/admin/dungeonbuilder/tiles` and `/admin/dungeonbuilder/tiles/edit`
**What a Tile Template is:**
- A reusable multi-tile pattern (size width/height) composed of tilemap frames.
- It has metadata (name, category, biome, tags, weight, tier gating) and tile properties (walkable/blocking flags).
- It stores a JSON array of placed cells (`TilesJson`) which maps template grid cells to a sprite sheet frame.
**Category and properties:**
- Categories include floor/wall/door/etc. (used for filtering and palette grouping).
- Properties include: walkable, blocks movement, blocks projectiles, blocks line of sight.
**Sockets:**
- Each template has edge sockets used for matching/connection during procedural placement.
- The editor exposes a socket grid with per-edge cells and three socket types: Open / Closed / Custom.
- Socket configuration is stored in JSON (new format) with legacy fields also maintained for backward compatibility.
- There is autocomplete for custom socket names, with storage in a dedicated socket names table.
**Editor workflow:**
- Select a tile sheet, pick a frame, then paint cells in the template grid.
- The first tile placed becomes the primary tile definition.
- You can resize the template (1x1 up to 10x10), fill all, fill border, or clear.
- Tile placements are serialized back to JSON on save.
### 1.3 Room Templates
**Where:** `/admin/dungeonbuilder/rooms` and `/admin/dungeonbuilder/rooms/edit`
**What a Room Template is:**
- A fixed room layout (width/height) containing floor/wall tiles, spawns, and connection points.
- Stored as JSON arrays for tile placements, spawns, and connection points.
**Editor workflow:**
- Grid editor with tools: paint, erase, fill.
- Layers: floor, wall, spawn.
- Tile palette is built from Tile Templates filtered by selected tilemap sheet and tags.
- Floor/wall choice is driven by the selected template’s walkable flag.
- Spawn layer supports: player spawn, exit portal, door connection points, chests, and mob spawns.
**Data stored:**
- TileGridJson: combined floor+wall placements with isWalkable flag.
- ConnectionPointsJson: doorways on grid edges with a direction.
- MobSpawnsJson: per-cell mob spawns with mob definition id and count.
- Player/exit spawn coordinates stored separately.
- Object placements exist but are currently stored as empty JSON (not placed in UI).
### 1.4 Object Templates
**Where:** `/admin/dungeonbuilder/objects` and `/admin/dungeonbuilder/objects/edit`
**What an Object Template is:**
- A placeable object (decoration, container, trap, door, vendor, etc.) with sprite, size, interaction, and loot settings.
**Key properties:**
- Sprite sheet + frame index or a direct CDN image path.
- Blocking: movement, projectiles, line of sight.
- Animation: isAnimated, frame count, fps, loops, states JSON.
- Interaction: interactable, triggered by walk, interaction type/state/cooldown.
- Rewards: loot table, gold, XP; trap/hazard damage with damage type.
- Generation: weight, tier limits, max per room, placement type.
**Editor workflow:**
- Pick a sprite sheet and frame; live preview shows selected frame.
- Configure animation and interaction settings.
- Set generation constraints.
### 1.5 Palettes
**Where:** `/admin/dungeonbuilder/palettes` and `/admin/dungeonbuilder/palettes/edit`
**What a Palette is:**
- A themed collection of templates and rules used by the dungeon generator.
**Palette contents:**
- Lists of Tile Templates: floors, walls, doors.
- Lists of Object Templates: decorations, containers, traps.
- List of Room Templates.
**Palette settings:**
- Room count min/max and room size ranges.
- Corridor width ranges.
- Density sliders for decorations/containers/traps.
- Biome/tags and enabled flag.
### 1.6 Test Generator
**Where:** `/admin/dungeonbuilder/testgen`
**What it does:**
- Generates a simple dungeon preview with rooms and corridors.
- Uses palette settings if selected, otherwise uses override values.
- Produces a grid visualization with cell types (floor, wall, door, spawns, mobs, etc.).
- Tracks and displays generation stats but does not fully integrate tile templates or sockets.
**Generation style:**
- Randomly places rectangular rooms with padding.
- Connects rooms using L-shaped corridors.
- Assigns entrance/exit, places mobs, chests, and decoration cells.
## 2) TileMaps (Admin UI)
### 2.1 TileMap Sheets
**Where:** `/admin/tilemaps`
**What a TileMap Sheet is:**
- A sprite sheet definition with size, tile size, and CDN path.
- Includes metadata (name, tags, enabled).
- Shows preview image and counts of defined tiles.
### 2.2 TileMap Editor
**Where:** `/admin/tilemaps/edit`
**What it does:**
- Defines a sheet (dimensions, tile size, CDN path) and renders a grid overlay preview.
- Allows per-frame tile definitions (TileDefinition) to be created/edited.
**TileDefinition fields:**
- Name, type, tags, walkable, blocks projectiles, blocks LOS, render layer.
- Socket fields: N/E/S/W with optional custom names.
**Bulk tools:**
- Auto-generate definitions for all frames.
- Auto-configure sockets based on type.
- Bulk set sockets to a specific type.
**CDN integration:**
- A CDN browser lists textures and can auto-fill the sheet path.
## 3) DungeonSimulation (Runtime)
### 3.1 Inputs
- Accepts a `DungeonLayout` with:
- Rooms (with type and positions)
- Walkability grid
- Mob spawns, chest spawns
- Tile details for visuals (handled elsewhere for rendering)
### 3.2 Initialization
- Spawns mobs at layout mob spawn points.
- If a specific MobDefinition is set, uses it; otherwise selects by spawn type (normal/elite/boss).
- Uses bracket-aware stat scaling from MobDefinition.
- Loads abilities from MobDefinition assignments if available, otherwise creates a basic attack.
- Spawns chests at layout chest spawns.
- Spawns an exit portal in the entrance room (prefers corners away from hallways).
### 3.3 Tick Loop
- Runs at 20 ticks/sec.
- If dungeon phase is Active:
- Updates mobs (AI), processes abilities/attacks.
- Updates projectiles and hazard zones.
- Always updates players (movement, status effects, regeneration).
- Handles corpse cleanup after loot is emptied (when cleared).
- Marks dungeon cleared when all mobs are dead and spawns an exit.
### 3.4 Combat and Movement
- Movement uses the layout walkability grid (`Layout.IsWalkable`).
- Mob AI uses abilities with range checks and cooldowns.
- Damage is calculated using CombatCalculator (armor, resistances, etc.).
- Status effects and DOT damage are processed each tick.
### 3.5 Events
- Generates lists of damage, death, ability, projectile events during tick.
- These are returned via TickResult for networking/client updates.
### 3.6 Summoning
- Supports runtime mob summoning (queued then spawned at end of tick).
## Observations (Current Couplings)
- Tile Templates and TileMap TileDefinitions overlap in “tile properties” but are separate systems.
- Room Editor uses Tile Templates, not TileDefinitions, for floor/wall selection.
- Tile sockets exist both in TileDefinitions (TileMaps) and TileTemplates (Builder), but with different data shapes.
- Test generator uses palette rules but does not apply template sockets or per-tile metadata.
- DungeonSimulation only reads the final layout walkability grid and spawn lists; it does not interpret template or tile metadata at runtime.
## Likely Revamp Touchpoints (Non-Prescriptive)
- Consolidate tile metadata into a single definition model used by:
- TileMaps (definition),
- Builder (authoring),
- Live editor (runtime overrides).
- Replace/retire template socket logic or re-platform it to the unified tile model.
- Update Room editor to use unified tile definitions and decoration overlays.
- Update generation pipeline to interpret the new tile metadata (walkability, LOS, projectile blocking, interactables).
- Keep DungeonSimulation driven by resolved layout (walkability + overlays) rather than editor-specific concepts.
## Decisions / Direction (from discussion)
- **Connection rules must support 1->many, many<->many, and 1->1**. The bucket model should allow explicit allow-lists (and optional weights) so a single bucket can target many, many buckets can target many, or exact 1-1 can be enforced.
- **Rules are global** (not per-palette), so one consistent connectivity grammar applies across dungeon + overworld. Palettes should filter which buckets/tiles are allowed in a given theme.
- **Biome is a bucket**. Biome membership should be expressible as bucket assignment (e.g., `biome_forest`, `biome_tundra`) and used in the same connectivity system.
- **Multi-tile patterns are undecided**. Keep open whether to retain “stamps” / patterns in Builder or simplify to single-tile defs + paint tools.
@@ -0,0 +1,84 @@
@page "/admin/dungeonbuilder/buckets/edit"
@model DungeonBuilder.Buckets.EditModel
@{
ViewData["Title"] = Model.Bucket.Id == 0 ? "New Bucket" : $"Edit Bucket: {Model.Bucket.Name}";
}
<div class="mb-4">
<a href="/admin/dungeonbuilder/buckets" class="text-blue-400 hover:text-blue-300 text-sm">&larr; Back to Buckets</a>
</div>
<h1 class="text-2xl font-bold text-white mb-6">@ViewData["Title"]</h1>
@if (!string.IsNullOrEmpty(Model.Message))
{
<div class="mb-4 p-3 rounded @(Model.IsError ? "bg-red-900/50 text-red-300" : "bg-green-900/50 text-green-300")">
@Model.Message
</div>
}
<form method="post">
@Html.AntiForgeryToken()
<input type="hidden" asp-for="Bucket.Id" />
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
<div class="card p-4 space-y-3">
<h3 class="font-semibold text-white">Bucket</h3>
<div>
<label class="text-xs text-gray-400">Name *</label>
<input type="text" asp-for="Bucket.Name" class="input w-full text-sm" required />
</div>
<div>
<label class="text-xs text-gray-400">Type</label>
<input type="text" asp-for="Bucket.BucketType" class="input w-full text-sm" placeholder="biome / floor / wall / decor" />
</div>
<div>
<label class="text-xs text-gray-400">Description</label>
<textarea asp-for="Bucket.Description" rows="3" class="input w-full text-sm"></textarea>
</div>
<div class="flex items-center gap-2">
<input type="checkbox" asp-for="Bucket.IsEnabled" class="rounded" />
<label class="text-sm text-gray-300">Enabled</label>
</div>
</div>
<div class="card p-4 space-y-3">
<h3 class="font-semibold text-white">Allow-List Rules</h3>
<p class="text-xs text-gray-500">Select which buckets this bucket can connect to.</p>
<input type="text" id="bucketFilter" class="input w-full text-sm" placeholder="Type to filter buckets..." oninput="filterBuckets()" />
<div class="max-h-64 overflow-auto border border-gray-700 rounded p-2 space-y-1" id="bucketList">
@foreach (var b in Model.AllBuckets)
{
if (b.Id == Model.Bucket.Id) { continue; }
<label class="flex items-center gap-2 text-sm text-gray-300 bucket-item" data-name="@b.Name.ToLower()">
<input type="checkbox" name="allowedBucketIds" value="@b.Id" class="rounded"
@(Model.AllowedBucketIds.Contains(b.Id) ? "checked" : "") />
<span>@b.Name</span>
@if (!string.IsNullOrWhiteSpace(b.BucketType))
{
<span class="text-xs text-gray-500 ml-auto">@b.BucketType</span>
}
</label>
}
</div>
</div>
</div>
<div class="flex justify-end gap-4 mt-6">
<a href="/admin/dungeonbuilder/buckets" class="btn btn-ghost">Cancel</a>
<button type="submit" class="btn btn-primary">
@(Model.Bucket.Id == 0 ? "Create Bucket" : "Save Changes")
</button>
</div>
</form>
@section Scripts {
<script>
function filterBuckets() {
const q = document.getElementById('bucketFilter').value.toLowerCase();
document.querySelectorAll('.bucket-item').forEach(el => {
el.style.display = el.dataset.name.includes(q) ? '' : 'none';
});
}
</script>
}
@@ -0,0 +1,114 @@
using DataServer.Data;
using DataServer.Data.Entities;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace GameServices.Admin.Pages.DungeonBuilder.Buckets;
public class EditModel : AdminPageModel
{
private readonly GameDbContext _db;
public EditModel(GameDbContext db)
{
_db = db;
}
[BindProperty]
public TileBucket Bucket { get; set; } = new();
public List<TileBucket> AllBuckets { get; set; } = new();
public HashSet<int> AllowedBucketIds { get; set; } = new();
public string? Message { get; set; }
public bool IsError { get; set; }
public async Task OnGetAsync(int? id)
{
await LoadBucketsAsync();
if (id.HasValue)
{
var bucket = await _db.TileBuckets.FindAsync(id.Value);
if (bucket != null)
{
Bucket = bucket;
AllowedBucketIds = await _db.TileBucketRules
.Where(r => r.SourceBucketId == bucket.Id)
.Select(r => r.TargetBucketId)
.ToHashSetAsync();
}
}
else
{
Bucket.IsEnabled = true;
}
}
public async Task<IActionResult> OnPostAsync()
{
await LoadBucketsAsync();
if (string.IsNullOrWhiteSpace(Bucket.Name))
{
IsError = true;
Message = "Name is required.";
return Page();
}
Bucket.UpdatedAt = DateTime.UtcNow;
var allowedIds = Request.Form["allowedBucketIds"]
.Select(v => int.TryParse(v, out var id) ? id : 0)
.Where(id => id > 0)
.ToHashSet();
if (Bucket.Id == 0)
{
Bucket.CreatedAt = DateTime.UtcNow;
_db.TileBuckets.Add(Bucket);
await _db.SaveChangesAsync();
}
else
{
var existing = await _db.TileBuckets.FindAsync(Bucket.Id);
if (existing == null)
{
IsError = true;
Message = "Bucket not found.";
return Page();
}
existing.Name = Bucket.Name.Trim();
existing.BucketType = Bucket.BucketType?.Trim();
existing.Description = Bucket.Description?.Trim();
existing.IsEnabled = Bucket.IsEnabled;
existing.UpdatedAt = DateTime.UtcNow;
}
var sourceId = Bucket.Id;
var existingRules = _db.TileBucketRules.Where(r => r.SourceBucketId == sourceId);
_db.TileBucketRules.RemoveRange(existingRules);
foreach (var targetId in allowedIds.Where(id => id != sourceId))
{
_db.TileBucketRules.Add(new TileBucketRule
{
SourceBucketId = sourceId,
TargetBucketId = targetId,
Weight = 1.0f
});
}
await _db.SaveChangesAsync();
return RedirectToPage(new { id = sourceId });
}
private async Task LoadBucketsAsync()
{
AllBuckets = await _db.TileBuckets
.OrderBy(b => b.Name)
.ToListAsync();
}
}
@@ -0,0 +1,68 @@
@page "/admin/dungeonbuilder/buckets"
@model DungeonBuilder.Buckets.IndexModel
@{
ViewData["Title"] = "Tile Buckets";
}
<div class="mb-4">
<a href="/admin/dungeonbuilder" class="text-blue-400 hover:text-blue-300 text-sm">&larr; Back to Dungeon Builder</a>
</div>
<div class="flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-6">
<div>
<h1 class="text-2xl font-bold text-white">Tile Buckets</h1>
<p class="text-gray-400 text-sm mt-1">Connectivity buckets and allow-lists</p>
</div>
<a href="/admin/dungeonbuilder/buckets/edit" class="btn btn-primary">+ New Bucket</a>
</div>
@if (!string.IsNullOrEmpty(Model.Message))
{
<div class="mb-4 p-3 rounded @(Model.IsError ? "bg-red-900/50 text-red-300" : "bg-green-900/50 text-green-300")">
@Model.Message
</div>
}
<div class="card p-4">
<table class="w-full text-sm">
<thead>
<tr class="text-left text-gray-400 border-b border-gray-700">
<th class="pb-2 pr-4">Name</th>
<th class="pb-2 pr-4">Type</th>
<th class="pb-2 pr-4">Rules</th>
<th class="pb-2 pr-4">Enabled</th>
<th class="pb-2">Actions</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-700/50">
@foreach (var b in Model.Buckets)
{
<tr class="hover:bg-gray-800/50">
<td class="py-2 pr-4 text-white">@b.Name</td>
<td class="py-2 pr-4 text-gray-400">@(string.IsNullOrWhiteSpace(b.BucketType) ? "-" : b.BucketType)</td>
<td class="py-2 pr-4 text-gray-400">@b.RuleCount</td>
<td class="py-2 pr-4">
<span class="px-2 py-0.5 text-xs rounded @(b.IsEnabled ? "bg-green-900 text-green-300" : "bg-red-900 text-red-300")">
@(b.IsEnabled ? "On" : "Off")
</span>
</td>
<td class="py-2">
<div class="flex gap-2">
<a href="/admin/dungeonbuilder/buckets/edit?id=@b.Id" class="text-blue-400 hover:text-blue-300">Edit</a>
<form method="post" asp-page-handler="Delete" class="inline" onsubmit="return confirm('Delete this bucket?')">
<input type="hidden" name="id" value="@b.Id" />
<button type="submit" class="text-red-400 hover:text-red-300">Delete</button>
</form>
</div>
</td>
</tr>
}
@if (!Model.Buckets.Any())
{
<tr>
<td colspan="5" class="py-8 text-center text-gray-500">No buckets created yet.</td>
</tr>
}
</tbody>
</table>
</div>
@@ -0,0 +1,61 @@
using DataServer.Data;
using DataServer.Data.Entities;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace GameServices.Admin.Pages.DungeonBuilder.Buckets;
public class IndexModel : AdminPageModel
{
private readonly GameDbContext _db;
public IndexModel(GameDbContext db)
{
_db = db;
}
public List<BucketRow> Buckets { get; set; } = new();
public string? Message { get; set; }
public bool IsError { get; set; }
public async Task OnGetAsync()
{
Buckets = await _db.TileBuckets
.OrderBy(b => b.Name)
.Select(b => new BucketRow
{
Id = b.Id,
Name = b.Name,
BucketType = b.BucketType,
IsEnabled = b.IsEnabled,
RuleCount = _db.TileBucketRules.Count(r => r.SourceBucketId == b.Id)
})
.ToListAsync();
}
public async Task<IActionResult> OnPostDeleteAsync(int id)
{
var bucket = await _db.TileBuckets.FindAsync(id);
if (bucket != null)
{
// Remove rules and links first
var rules = _db.TileBucketRules.Where(r => r.SourceBucketId == id || r.TargetBucketId == id);
_db.TileBucketRules.RemoveRange(rules);
var links = _db.TileDefinitionBuckets.Where(l => l.TileBucketId == id);
_db.TileDefinitionBuckets.RemoveRange(links);
_db.TileBuckets.Remove(bucket);
await _db.SaveChangesAsync();
}
return RedirectToPage();
}
public class BucketRow
{
public int Id { get; set; }
public string Name { get; set; } = "";
public string? BucketType { get; set; }
public bool IsEnabled { get; set; }
public int RuleCount { get; set; }
}
}
@@ -17,7 +17,7 @@
}
<!-- Quick Stats -->
<div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
<div class="grid grid-cols-2 md:grid-cols-6 gap-4 mb-6">
<div class="card p-4">
<div class="text-3xl font-bold text-blue-400">@Model.TileTemplateCount</div>
<div class="text-gray-400 text-sm">Tile Templates</div>
@@ -34,6 +34,14 @@
<div class="text-3xl font-bold text-yellow-400">@Model.PaletteCount</div>
<div class="text-gray-400 text-sm">Dungeon Palettes</div>
</div>
<div class="card p-4">
<div class="text-3xl font-bold text-cyan-400">@Model.BucketCount</div>
<div class="text-gray-400 text-sm">Tile Buckets</div>
</div>
<div class="card p-4">
<div class="text-3xl font-bold text-pink-400">@Model.StampCount</div>
<div class="text-gray-400 text-sm">Tile Stamps</div>
</div>
</div>
<!-- Builder Tools Grid -->
@@ -110,6 +118,42 @@
</div>
</div>
</a>
<!-- Tile Buckets -->
<a href="/admin/dungeonbuilder/buckets" class="card p-6 hover:border-cyan-500 transition-colors group">
<div class="flex items-start gap-4">
<div class="w-12 h-12 rounded-lg bg-cyan-500/20 flex items-center justify-center text-cyan-400 text-2xl">
TB
</div>
<div class="flex-1">
<h3 class="text-lg font-semibold text-white group-hover:text-cyan-400">Tile Buckets</h3>
<p class="text-gray-400 text-sm mt-1">Define bucket rules and allow-lists</p>
<div class="mt-3 text-xs text-gray-500">
- Global adjacency rules<br>
- Bucket metadata<br>
- Connectivity weights
</div>
</div>
</div>
</a>
<!-- Tile Stamps -->
<a href="/admin/dungeonbuilder/stamps" class="card p-6 hover:border-pink-500 transition-colors group">
<div class="flex items-start gap-4">
<div class="w-12 h-12 rounded-lg bg-pink-500/20 flex items-center justify-center text-pink-400 text-2xl">
TS
</div>
<div class="flex-1">
<h3 class="text-lg font-semibold text-white group-hover:text-pink-400">Tile Stamps</h3>
<p class="text-gray-400 text-sm mt-1">Reusable multi-tile paint patterns</p>
<div class="mt-3 text-xs text-gray-500">
- Saved patterns<br>
- Fast room painting<br>
- Grid-based stamps
</div>
</div>
</div>
</a>
<!-- Sprite Sheet Manager -->
<a href="/admin/tilemaps" class="card p-6 hover:border-cyan-500 transition-colors group">
@@ -18,6 +18,8 @@ public class IndexModel : AdminPageModel
public int ObjectTemplateCount { get; set; }
public int RoomTemplateCount { get; set; }
public int PaletteCount { get; set; }
public int BucketCount { get; set; }
public int StampCount { get; set; }
public List<RecentItem> RecentItems { get; set; } = new();
@@ -31,6 +33,8 @@ public class IndexModel : AdminPageModel
ObjectTemplateCount = await _db.ObjectTemplates.CountAsync();
RoomTemplateCount = await _db.BuilderRoomTemplates.CountAsync();
PaletteCount = await _db.DungeonPalettes.CountAsync();
BucketCount = await _db.TileBuckets.CountAsync();
StampCount = await _db.TileStamps.CountAsync();
// Get recent items (combined from all types)
var recentTiles = await _db.TileTemplates
@@ -27,6 +27,7 @@
<input type="hidden" asp-for="Palette.ContainerIdsJson" id="containerIds" />
<input type="hidden" asp-for="Palette.TrapIdsJson" id="trapIds" />
<input type="hidden" asp-for="Palette.RoomTemplateIdsJson" id="roomIds" />
<input type="hidden" asp-for="Palette.AllowedBucketIdsJson" id="bucketIds" />
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
<!-- Left: Basic Settings -->
@@ -59,6 +60,34 @@
</div>
</div>
<div class="card p-4">
<h3 class="font-semibold text-white mb-3">Bucket Filters</h3>
<p class="text-xs text-gray-500 mb-2">Limit generation to these buckets.</p>
<input type="text" id="bucketFilter" class="input w-full text-sm mb-2" placeholder="Type to filter buckets..." oninput="filterBuckets()" />
<div class="max-h-48 overflow-auto border border-gray-700 rounded p-2 space-y-1" id="bucketList">
@foreach (var b in Model.Buckets)
{
<label class="flex items-center gap-2 text-sm text-gray-300 bucket-item" data-name="@b.Name.ToLower()">
<input type="checkbox" class="rounded bucket-check" value="@b.Id"
@(Model.SelectedBucketIds.Contains(b.Id) ? "checked" : "") />
<span>@b.Name</span>
@if (!string.IsNullOrWhiteSpace(b.BucketType))
{
<span class="text-xs text-gray-500 ml-auto">@b.BucketType</span>
}
</label>
}
@if (!Model.Buckets.Any())
{
<div class="text-xs text-gray-500">No buckets defined yet.</div>
}
</div>
<div class="flex items-center gap-2 mt-3">
<input type="checkbox" asp-for="Palette.EnforceBiomeBuckets" class="rounded" />
<label class="text-sm text-gray-300">Enforce biome bucket</label>
</div>
</div>
<div class="card p-4">
<h3 class="font-semibold text-white mb-3">Room Generation</h3>
<div class="space-y-3">
@@ -291,7 +320,15 @@ function saveSelections() {
document.getElementById('containerIds').value = JSON.stringify(collectIds('.container-check'));
document.getElementById('trapIds').value = JSON.stringify(collectIds('.trap-check'));
document.getElementById('roomIds').value = JSON.stringify(collectIds('.room-check'));
document.getElementById('bucketIds').value = JSON.stringify(collectIds('.bucket-check'));
}
document.querySelector('form').onsubmit = () => saveSelections();
function filterBuckets() {
const q = document.getElementById('bucketFilter').value.toLowerCase();
document.querySelectorAll('.bucket-item').forEach(el => {
el.style.display = el.dataset.name.includes(q) ? '' : 'none';
});
}
</script>
@@ -26,6 +26,7 @@ public class PaletteEditModel : AdminPageModel
public List<ObjectTemplate> Containers { get; set; } = new();
public List<ObjectTemplate> Traps { get; set; } = new();
public List<BuilderRoomTemplate> Rooms { get; set; } = new();
public List<TileBucket> Buckets { get; set; } = new();
// Selected IDs
public List<int> SelectedFloorIds { get; set; } = new();
@@ -35,6 +36,7 @@ public class PaletteEditModel : AdminPageModel
public List<int> SelectedContainerIds { get; set; } = new();
public List<int> SelectedTrapIds { get; set; } = new();
public List<int> SelectedRoomIds { get; set; } = new();
public List<int> SelectedBucketIds { get; set; } = new();
public string? Message { get; set; }
public bool IsError { get; set; }
@@ -58,6 +60,7 @@ public class PaletteEditModel : AdminPageModel
SelectedContainerIds = ParseIds(palette.ContainerIdsJson);
SelectedTrapIds = ParseIds(palette.TrapIdsJson);
SelectedRoomIds = ParseIds(palette.RoomTemplateIdsJson);
SelectedBucketIds = ParseIds(palette.AllowedBucketIdsJson);
}
}
else
@@ -111,6 +114,8 @@ public class PaletteEditModel : AdminPageModel
existing.Description = Palette.Description;
existing.Biome = Palette.Biome;
existing.Tags = Palette.Tags;
existing.AllowedBucketIdsJson = Palette.AllowedBucketIdsJson;
existing.EnforceBiomeBuckets = Palette.EnforceBiomeBuckets;
existing.FloorTemplateIdsJson = Palette.FloorTemplateIdsJson;
existing.WallTemplateIdsJson = Palette.WallTemplateIdsJson;
existing.DoorTemplateIdsJson = Palette.DoorTemplateIdsJson;
@@ -145,6 +150,7 @@ public class PaletteEditModel : AdminPageModel
SelectedContainerIds = ParseIds(Palette.ContainerIdsJson);
SelectedTrapIds = ParseIds(Palette.TrapIdsJson);
SelectedRoomIds = ParseIds(Palette.RoomTemplateIdsJson);
SelectedBucketIds = ParseIds(Palette.AllowedBucketIdsJson);
return RedirectToPage(new { id = Palette.Id });
}
@@ -181,6 +187,11 @@ public class PaletteEditModel : AdminPageModel
.Where(r => r.IsEnabled)
.OrderBy(r => r.Name)
.ToListAsync();
Buckets = await _db.TileBuckets
.Where(b => b.IsEnabled)
.OrderBy(b => b.Name)
.ToListAsync();
}
private List<int> ParseIds(string? json)
@@ -84,6 +84,17 @@
}
.mob-select-item:hover { background: #374151; }
.mob-select-item.selected { background: #4f46e5; }
.stamp-select-item {
padding: 6px 8px;
background: #1f2937;
border-radius: 4px;
cursor: pointer;
display: flex;
align-items: center;
gap: 8px;
}
.stamp-select-item:hover { background: #374151; }
.stamp-select-item.selected { background: #4f46e5; }
.tag-chip {
display: inline-block;
padding: 2px 8px;
@@ -166,9 +177,13 @@
</div>
<div class="border-t border-gray-700 pt-3">
<label class="text-xs text-gray-400 mb-2 block">Layer</label>
<div class="flex gap-1">
<div class="flex flex-wrap 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="wall" onclick="setLayer('wall')">Wall</button>
<button type="button" class="tool-btn flex-1 text-xs" data-layer="decor1" onclick="setLayer('decor1')">Decor 1</button>
<button type="button" class="tool-btn flex-1 text-xs" data-layer="decor2" onclick="setLayer('decor2')">Decor 2</button>
<button type="button" class="tool-btn flex-1 text-xs" data-layer="decor3" onclick="setLayer('decor3')">Decor 3</button>
<button type="button" class="tool-btn flex-1 text-xs" data-layer="decor4" onclick="setLayer('decor4')">Decor 4</button>
<button type="button" class="tool-btn flex-1 text-xs" data-layer="spawn" onclick="setLayer('spawn')">Spawn</button>
</div>
</div>
@@ -258,6 +273,28 @@
<div class="text-gray-500 text-xs p-2">Select a TileMap to see templates</div>
</div>
</div>
<!-- Stamp Palette -->
<div class="card p-4" id="stampPaletteCard">
<h3 class="font-semibold text-white mb-3">Stamps</h3>
<div class="mb-2">
<input type="text" id="stampSearch" class="input w-full text-sm" placeholder="Search stamps..." oninput="filterStamps()" />
</div>
<div id="stampList" class="max-h-[200px] overflow-auto space-y-1">
@foreach (var stamp in Model.TileStamps)
{
<div class="stamp-select-item" data-stamp-id="@stamp.Id" data-stamp-name="@stamp.Name" onclick="selectStamp(this)">
<span class="text-sm">🗂️</span>
<span class="text-sm text-gray-300">@stamp.Name</span>
<span class="text-xs text-gray-500">(@stamp.Width x @stamp.Height)</span>
</div>
}
@if (!Model.TileStamps.Any())
{
<div class="text-xs text-gray-500">No stamps created yet.</div>
}
</div>
</div>
<!-- Spawn Palette -->
<div class="card p-4 hidden" id="spawnPaletteCard">
@@ -307,6 +344,7 @@ const loadedSheets = {};
// 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 decorData = [{}, {}, {}, {}]; // Four decoration layers
let spawnData = {}; // Spawns - { type, mobId?, mobName? }
let connectionData = {}; // Connection points (doorways) - { direction }
@@ -314,6 +352,9 @@ let connectionData = {}; // Connection points (doorways) - { direction }
const allTileTemplates = @Html.Raw(Model.TileTemplatesJson);
let tileTemplates = []; // Filtered for current sheet
let allTags = new Set();
const allStamps = @Html.Raw(Model.TileStampsJson);
const stampMap = {};
const templateBySprite = {};
let mouseDown = false;
@@ -336,6 +377,14 @@ function preloadSheets() {
document.addEventListener('DOMContentLoaded', () => {
preloadSheets();
allTileTemplates.forEach(t => {
if (t.sheetId != null) {
templateBySprite[`${t.sheetId}:${t.frameIndex}`] = t;
}
});
allStamps.forEach(s => {
stampMap[s.id] = s;
});
loadData();
buildGrid();
});
@@ -344,16 +393,17 @@ function loadData() {
try {
const td = '@Html.Raw(Model.Room.TileGridJson ?? "[]")';
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
isWalkable: t.isWalkable !== false
};
if (isWalkable) {
const layerIndex = typeof t.layer === 'number' ? t.layer : 0;
if (layerIndex >= 1 && layerIndex <= 4) {
decorData[layerIndex - 1][key] = data;
} else if (data.isWalkable) {
floorData[key] = data;
} else {
wallData[key] = data;
@@ -454,6 +504,15 @@ function render(x, y) {
// Overlays
let html = '';
const decorLayers = decorData.map(layer => layer[k]).filter(Boolean);
decorLayers.forEach(d => {
if (d.sheetId && loadedSheets[d.sheetId]) {
const s = loadedSheets[d.sheetId];
const dc = d.frameIndex % s.cols;
const dr = Math.floor(d.frameIndex / s.cols);
html += `<div class="absolute inset-0" style="background:url('${cdnBase}/${s.cdn}') ${-dc*s.tw*scale}px ${-dr*s.th*scale}px no-repeat;background-size:${s.sw*scale}px ${s.sh*scale}px;image-rendering:pixelated;"></div>`;
}
});
const sp = spawnData[k];
if (sp) {
const icons = { player:'🧑', exit:'🌀', mob:'👾', chest:'📦' };
@@ -471,7 +530,9 @@ function paint(x, y) {
const k = `${x},${y}`;
if (tool === 'paint' && sel) {
if ((layer === 'floor' || layer === 'wall') && sel.type === 'template') {
if (sel.type === 'stamp') {
applyStamp(x, y);
} else if ((layer === 'floor' || layer === 'wall') && sel.type === 'template') {
// Remove from both to avoid duplicates
delete floorData[k];
delete wallData[k];
@@ -488,6 +549,16 @@ function paint(x, y) {
} else {
wallData[k] = data;
}
} else if (layer.startsWith('decor') && sel.type === 'template') {
const decorIdx = getDecorLayerIndex(layer);
if (decorIdx !== null) {
decorData[decorIdx][k] = {
templateId: sel.templateId,
sheetId: sel.sheetId,
frameIndex: sel.frameIndex,
isWalkable: true
};
}
} else if (layer === 'spawn') {
if (sel.type === 'spawn') {
if (sel.spawn === 'connection') {
@@ -518,12 +589,19 @@ function paint(x, y) {
} else if (tool === 'erase') {
if (layer === 'floor') delete floorData[k];
else if (layer === 'wall') delete wallData[k];
else if (layer === 'spawn') {
else if (layer.startsWith('decor')) {
const decorIdx = getDecorLayerIndex(layer);
if (decorIdx !== null) delete decorData[decorIdx][k];
} else if (layer === 'spawn') {
delete spawnData[k];
delete connectionData[k];
}
} else if (tool === 'fill' && sel?.type === 'template') {
floodFill(x, y);
if (layer.startsWith('decor')) {
floodFillDecor(x, y);
} else {
floodFill(x, y);
}
}
render(x, y);
@@ -578,25 +656,109 @@ function floodFill(sx, sy) {
}
}
function floodFillDecor(sx, sy) {
const decorIdx = getDecorLayerIndex(layer);
if (decorIdx === null) return;
const layerData = decorData[decorIdx];
const sk = `${sx},${sy}`;
const startTile = layerData[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;
const current = layerData[k];
if ((current?.frameIndex ?? -1) !== startF) continue;
visited.add(k);
layerData[k] = {
templateId: sel.templateId,
sheetId: sel.sheetId,
frameIndex: sel.frameIndex,
isWalkable: true
};
render(x, y);
queue.push([x+1,y],[x-1,y],[x,y+1],[x,y-1]);
}
}
function applyStamp(x, y) {
const stamp = stampMap[sel.stampId];
if (!stamp || !stamp.tiles) return;
stamp.tiles.forEach(t => {
const tx = x + t.x;
const ty = y + t.y;
if (tx < 0 || tx >= gw || ty < 0 || ty >= gh) return;
const template = templateBySprite[`${t.sheetId}:${t.frameIndex}`];
if (!template) return;
const key = `${tx},${ty}`;
const data = {
templateId: template.id,
sheetId: template.sheetId,
frameIndex: template.frameIndex,
isWalkable: template.isWalkable
};
if (layer.startsWith('decor')) {
const decorIdx = getDecorLayerIndex(layer);
if (decorIdx !== null) {
decorData[decorIdx][key] = { ...data, isWalkable: true };
}
} else if (layer === 'floor' || layer === 'wall') {
delete floorData[key];
delete wallData[key];
if (data.isWalkable) floorData[key] = data;
else wallData[key] = data;
}
render(tx, ty);
});
updateStats();
saveData();
}
function setTool(t) {
tool = t;
document.querySelectorAll('[data-tool]').forEach(b => b.classList.toggle('active', b.dataset.tool === t));
}
function getDecorLayerIndex(layerKey) {
switch (layerKey) {
case 'decor1': return 0;
case 'decor2': return 1;
case 'decor3': return 2;
case 'decor4': return 3;
default: return null;
}
}
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 === 'spawn');
document.getElementById('spawnPaletteCard').classList.toggle('hidden', l !== 'spawn');
document.getElementById('stampPaletteCard').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.querySelectorAll('.stamp-select-item').forEach(i => i.classList.remove('selected'));
document.getElementById('selectionInfo').textContent = 'Nothing';
document.getElementById('selectionDetails').textContent = '';
// Refresh templates when switching between floor/wall layers
if (l === 'floor' || l === 'wall') {
renderTemplates();
} else if (l.startsWith('decor')) {
renderTemplates();
}
}
@@ -683,6 +845,8 @@ function renderTemplates(filterTags = []) {
filtered = filtered.filter(t => t.isWalkable);
} else if (layer === 'wall') {
filtered = filtered.filter(t => !t.isWalkable);
} else if (layer.startsWith('decor')) {
filtered = filtered.filter(t => t.category === 'Decoration');
}
// Filter by tags
@@ -737,6 +901,7 @@ function renderTemplates(filterTags = []) {
function selectPaletteItem(el) {
document.querySelectorAll('.palette-item').forEach(i => i.classList.remove('active'));
document.querySelectorAll('.mob-select-item').forEach(i => i.classList.remove('selected'));
document.querySelectorAll('.stamp-select-item').forEach(i => i.classList.remove('selected'));
el.classList.add('active');
const type = el.dataset.type;
@@ -761,6 +926,7 @@ function selectPaletteItem(el) {
function selectMob(el) {
document.querySelectorAll('.palette-item').forEach(i => i.classList.remove('active'));
document.querySelectorAll('.mob-select-item').forEach(i => i.classList.remove('selected'));
document.querySelectorAll('.stamp-select-item').forEach(i => i.classList.remove('selected'));
el.classList.add('selected');
sel = {
@@ -773,6 +939,26 @@ function selectMob(el) {
document.getElementById('selectionDetails').textContent = `Type: ${sel.mobType}`;
}
function selectStamp(el) {
document.querySelectorAll('.palette-item').forEach(i => i.classList.remove('active'));
document.querySelectorAll('.mob-select-item').forEach(i => i.classList.remove('selected'));
document.querySelectorAll('.stamp-select-item').forEach(i => i.classList.remove('selected'));
el.classList.add('selected');
const stampId = +el.dataset.stampId;
sel = { type: 'stamp', stampId };
document.getElementById('selectionInfo').textContent = `Stamp: ${el.dataset.stampName}`;
document.getElementById('selectionDetails').textContent = '';
}
function filterStamps() {
const search = document.getElementById('stampSearch').value.toLowerCase();
document.querySelectorAll('.stamp-select-item').forEach(el => {
const name = el.dataset.stampName.toLowerCase();
el.style.display = name.includes(search) ? '' : 'none';
});
}
function filterMobs() {
const search = document.getElementById('mobSearch').value.toLowerCase();
document.querySelectorAll('.mob-select-item').forEach(el => {
@@ -784,9 +970,10 @@ function filterMobs() {
function updateStats() {
const floors = Object.keys(floorData).length;
const walls = Object.keys(wallData).length;
const decors = decorData.reduce((acc, layer) => acc + Object.keys(layer).length, 0);
const spawns = Object.keys(spawnData).length;
const connections = Object.keys(connectionData).length;
document.getElementById('statsInfo').textContent = `Tiles: ${floors} | Walls: ${walls} | Spawns: ${spawns} | Connections: ${connections}`;
document.getElementById('statsInfo').textContent = `Tiles: ${floors} | Walls: ${walls} | Decor: ${decors} | Spawns: ${spawns} | Connections: ${connections}`;
}
function saveData() {
@@ -800,6 +987,12 @@ function saveData() {
const [x, y] = k.split(',').map(Number);
tiles.push({ x, y, sheetId: v.sheetId, frameIndex: v.frameIndex, templateId: v.templateId, isWalkable: false });
});
decorData.forEach((layerData, idx) => {
Object.entries(layerData).forEach(([k, v]) => {
const [x, y] = k.split(',').map(Number);
tiles.push({ x, y, sheetId: v.sheetId, frameIndex: v.frameIndex, templateId: v.templateId, layer: idx + 1, isWalkable: true });
});
});
document.getElementById('tileGridJson').value = JSON.stringify(tiles);
// Connection points
@@ -843,6 +1036,10 @@ function clearLayer() {
if (!confirm(`Clear all ${layer}?`)) return;
if (layer === 'floor') floorData = {};
else if (layer === 'wall') wallData = {};
else if (layer.startsWith('decor')) {
const decorIdx = getDecorLayerIndex(layer);
if (decorIdx !== null) decorData[decorIdx] = {};
}
else {
spawnData = {};
connectionData = {};
@@ -853,7 +1050,7 @@ function clearLayer() {
function clearAll() {
if (!confirm('Clear everything?')) return;
floorData = {}; wallData = {}; spawnData = {}; connectionData = {};
floorData = {}; wallData = {}; decorData = [{}, {}, {}, {}]; spawnData = {}; connectionData = {};
buildGrid();
saveData();
}
@@ -24,6 +24,7 @@ public class RoomEditModel : AdminPageModel
public List<ObjectTemplate> Objects { get; set; } = new();
public List<DungeonMobDefinition> Mobs { get; set; } = new();
public List<TileTemplate> TileTemplates { get; set; } = new();
public List<TileStamp> TileStamps { get; set; } = new();
/// <summary>
/// TileTemplates serialized as JSON for JavaScript consumption.
@@ -45,6 +46,17 @@ public class RoomEditModel : AdminPageModel
};
}).Where(t => t.sheetId.HasValue)
);
public string TileStampsJson => JsonSerializer.Serialize(
TileStamps.Select(s => new
{
id = s.Id,
name = s.Name,
width = s.Width,
height = s.Height,
tiles = ParseStampTiles(s.TilesJson)
})
);
private static (int? sheetId, int frameIndex) ExtractTileInfo(string? tilesJson)
{
@@ -64,6 +76,29 @@ public class RoomEditModel : AdminPageModel
public int SheetId { get; set; }
public int FrameIndex { get; set; }
}
private class StampTile
{
public int X { get; set; }
public int Y { get; set; }
public int SheetId { get; set; }
public int FrameIndex { get; set; }
public int? Layer { get; set; }
}
private static List<StampTile> ParseStampTiles(string? json)
{
if (string.IsNullOrEmpty(json)) return new List<StampTile>();
try
{
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
return JsonSerializer.Deserialize<List<StampTile>>(json, options) ?? new List<StampTile>();
}
catch
{
return new List<StampTile>();
}
}
public string CdnBaseUrl => NormalizeCdnBaseUrl(_config["Cdn:BaseUrl"]);
@@ -201,5 +236,10 @@ public class RoomEditModel : AdminPageModel
.OrderBy(t => t.Category)
.ThenBy(t => t.Name)
.ToListAsync();
TileStamps = await _db.TileStamps
.Where(s => s.IsEnabled)
.OrderBy(s => s.Name)
.ToListAsync();
}
}
@@ -0,0 +1,309 @@
@page "/admin/dungeonbuilder/stamps/edit"
@model DungeonBuilder.Stamps.EditModel
@{
ViewData["Title"] = Model.Stamp.Id == 0 ? "New Tile Stamp" : $"Edit Stamp: {Model.Stamp.Name}";
}
<style>
.stamp-grid {
display: grid;
gap: 1px;
background: #1a1a2e;
border: 2px solid #374151;
border-radius: 4px;
}
.stamp-cell {
background: #0f0f1a;
cursor: crosshair;
position: relative;
image-rendering: pixelated;
}
.stamp-cell:hover {
outline: 2px solid #60a5fa;
outline-offset: -2px;
}
.palette-tile {
cursor: pointer;
border: 2px solid transparent;
border-radius: 2px;
image-rendering: pixelated;
box-sizing: content-box;
}
.palette-tile:hover { border-color: #60a5fa; }
.palette-tile.active { border-color: #fbbf24; }
</style>
<div class="mb-4">
<a href="/admin/dungeonbuilder/stamps" class="text-blue-400 hover:text-blue-300 text-sm">&larr; Back to Stamps</a>
</div>
<h1 class="text-2xl font-bold text-white mb-6">@ViewData["Title"]</h1>
@if (!string.IsNullOrEmpty(Model.Message))
{
<div class="mb-4 p-3 rounded @(Model.IsError ? "bg-red-900/50 text-red-300" : "bg-green-900/50 text-green-300")">
@Model.Message
</div>
}
<form method="post" id="stampForm">
@Html.AntiForgeryToken()
<input type="hidden" asp-for="Stamp.Id" />
<input type="hidden" asp-for="Stamp.TilesJson" id="tilesJson" />
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
<!-- Left: Settings -->
<div class="space-y-4">
<div class="card p-4">
<h3 class="font-semibold text-white mb-3">Stamp Settings</h3>
<div class="space-y-3">
<div>
<label class="text-xs text-gray-400">Name *</label>
<input type="text" asp-for="Stamp.Name" class="input w-full text-sm" required placeholder="2x2 Pillar" />
</div>
<div>
<label class="text-xs text-gray-400">Description</label>
<textarea asp-for="Stamp.Description" rows="2" class="input w-full text-sm"></textarea>
</div>
<div class="grid grid-cols-2 gap-2">
<div>
<label class="text-xs text-gray-400">Width</label>
<input type="number" asp-for="Stamp.Width" class="input w-full text-sm" min="1" max="20" id="stampWidth" />
</div>
<div>
<label class="text-xs text-gray-400">Height</label>
<input type="number" asp-for="Stamp.Height" class="input w-full text-sm" min="1" max="20" id="stampHeight" />
</div>
</div>
<button type="button" onclick="resizeStamp()" class="btn btn-secondary w-full text-sm">Resize</button>
<div class="flex items-center gap-2">
<input type="checkbox" asp-for="Stamp.IsEnabled" class="rounded" />
<label class="text-sm text-gray-300">Enabled</label>
</div>
</div>
</div>
</div>
<!-- Center: Stamp Grid -->
<div class="space-y-4">
<div class="card p-4">
<div class="flex items-center justify-between mb-3">
<h3 class="font-semibold text-white">Stamp Grid</h3>
<button type="button" onclick="clearStamp()" class="text-xs text-gray-400 hover:text-white">Clear</button>
</div>
<div class="bg-gray-900 rounded p-4 flex justify-center">
<div id="stampGrid" class="stamp-grid inline-grid"></div>
</div>
<p class="text-xs text-gray-500 mt-2">Click cells to paint with selected tile definition.</p>
</div>
</div>
<!-- Right: Tile Palette -->
<div class="space-y-4">
<div class="card p-4">
<h3 class="font-semibold text-white mb-3">Tile Palette</h3>
<div class="mb-3">
<select id="sheetSelect" class="input w-full text-sm" onchange="loadSheet()">
<option value="">Select sprite sheet...</option>
@foreach (var sheet in Model.TileSheets)
{
<option value="@sheet.Id"
data-cdn="@sheet.CdnPath"
data-cols="@sheet.Columns"
data-tw="@sheet.TileWidth"
data-th="@sheet.TileHeight"
data-sw="@sheet.SheetWidth"
data-sh="@sheet.SheetHeight">@sheet.Name</option>
}
</select>
</div>
<div id="palette" class="flex flex-wrap gap-1 max-h-[400px] overflow-auto bg-gray-900 rounded p-2">
<div class="text-gray-500 text-xs p-2">Select a sprite sheet</div>
</div>
</div>
<div class="card p-4">
<h3 class="font-semibold text-white mb-2">Selected Tile</h3>
<div id="selectedInfo" class="text-sm text-gray-400">None</div>
<div id="selectedPreview" class="mt-2 bg-gray-900 rounded p-2 h-12 flex items-center justify-center">
<span class="text-gray-600">-</span>
</div>
</div>
</div>
</div>
<div class="flex justify-end gap-4 mt-6">
<a href="/admin/dungeonbuilder/stamps" class="btn btn-ghost">Cancel</a>
<button type="submit" class="btn btn-primary">
@(Model.Stamp.Id == 0 ? "Create Stamp" : "Save Changes")
</button>
</div>
</form>
<script>
const cdnBase = '@Model.CdnBaseUrl';
let sw = @Model.Stamp.Width, sh = @Model.Stamp.Height;
let currentSheetId = null;
let selected = null;
let stampData = {};
const loadedSheets = {};
const tileDefs = @Html.Raw(Model.TileDefinitionsJson);
function preloadSheets() {
document.querySelectorAll('#sheetSelect option').forEach(opt => {
if (opt.value) {
loadedSheets[+opt.value] = {
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
};
}
});
}
document.addEventListener('DOMContentLoaded', () => {
preloadSheets();
loadExisting();
buildStampGrid();
});
function loadExisting() {
const json = document.getElementById('tilesJson').value;
if (json) {
try {
JSON.parse(json).forEach(t => {
stampData[`${t.x},${t.y}`] = { sheetId: t.sheetId, frameIndex: t.frameIndex, tileDefinitionId: t.tileDefinitionId || t.tileDefId || 0 };
});
} catch {}
}
}
function buildStampGrid() {
const grid = document.getElementById('stampGrid');
let cellW = 32, cellH = 32;
if (currentSheetId && loadedSheets[currentSheetId]) {
cellW = loadedSheets[currentSheetId].tw;
cellH = loadedSheets[currentSheetId].th;
} else {
const firstTile = Object.values(stampData)[0];
if (firstTile && loadedSheets[firstTile.sheetId]) {
cellW = loadedSheets[firstTile.sheetId].tw;
cellH = loadedSheets[firstTile.sheetId].th;
}
}
grid.style.gridTemplateColumns = `repeat(${sw}, ${cellW}px)`;
grid.innerHTML = '';
for (let y = 0; y < sh; y++) {
for (let x = 0; x < sw; x++) {
const cell = document.createElement('div');
cell.className = 'stamp-cell';
cell.style.width = cellW + 'px';
cell.style.height = cellH + 'px';
cell.dataset.x = x;
cell.dataset.y = y;
cell.onclick = () => paintCell(x, y);
grid.appendChild(cell);
renderCell(x, y);
}
}
}
function renderCell(x, y) {
const cell = document.querySelector(`.stamp-cell[data-x="${x}"][data-y="${y}"]`);
if (!cell) return;
const data = stampData[`${x},${y}`];
if (data && data.sheetId && loadedSheets[data.sheetId]) {
const sheet = loadedSheets[data.sheetId];
const col = data.frameIndex % sheet.cols;
const row = Math.floor(data.frameIndex / sheet.cols);
cell.style.background = `url('${cdnBase}/${sheet.cdn}') ${-col * sheet.tw}px ${-row * sheet.th}px no-repeat`;
cell.style.backgroundSize = `${sheet.sw}px ${sheet.sh}px`;
} else {
cell.style.background = '#0f0f1a';
}
}
function paintCell(x, y) {
if (!selected) return;
stampData[`${x},${y}`] = { sheetId: selected.sheetId, frameIndex: selected.frameIndex, tileDefinitionId: selected.tileDefinitionId };
renderCell(x, y);
saveData();
}
function loadSheet() {
const opt = document.getElementById('sheetSelect').selectedOptions[0];
if (!opt?.value) {
currentSheetId = null;
document.getElementById('palette').innerHTML = '<div class="text-gray-500 text-xs p-2">Select a sprite sheet</div>';
return;
}
currentSheetId = +opt.value;
const sheet = loadedSheets[currentSheetId];
const tiles = tileDefs.filter(t => t.sheetId === currentSheetId);
let html = '';
if (tiles.length === 0) {
html = '<div class="text-gray-500 text-xs p-2">No tile definitions for this sheet.</div>';
} else {
tiles.forEach(t => {
const col = t.frameIndex % sheet.cols;
const row = Math.floor(t.frameIndex / sheet.cols);
html += `<div class="palette-tile" data-frame="${t.frameIndex}" data-tile-id="${t.id}" onclick="selectTile(${t.frameIndex}, ${t.id})"
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;"></div>`;
});
}
document.getElementById('palette').innerHTML = html;
}
function selectTile(frameIndex, tileId) {
document.querySelectorAll('.palette-tile').forEach(t => t.classList.remove('active'));
document.querySelector(`.palette-tile[data-frame="${frameIndex}"]`)?.classList.add('active');
const sheet = loadedSheets[currentSheetId];
selected = { sheetId: currentSheetId, frameIndex, tileDefinitionId: tileId };
document.getElementById('selectedInfo').textContent = `Frame ${frameIndex}`;
const col = frameIndex % sheet.cols;
const row = Math.floor(frameIndex / sheet.cols);
document.getElementById('selectedPreview').innerHTML = `
<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;
image-rendering: pixelated;"></div>
`;
}
function resizeStamp() {
sw = +document.getElementById('stampWidth').value || 1;
sh = +document.getElementById('stampHeight').value || 1;
sw = Math.max(1, Math.min(20, sw));
sh = Math.max(1, Math.min(20, sh));
buildStampGrid();
}
function clearStamp() {
if (!confirm('Clear all tiles?')) return;
stampData = {};
buildStampGrid();
saveData();
}
function saveData() {
const tiles = Object.entries(stampData).map(([k, v]) => {
const [x, y] = k.split(',').map(Number);
return { x, y, sheetId: v.sheetId, frameIndex: v.frameIndex, tileDefinitionId: v.tileDefinitionId, layer: 0 };
});
document.getElementById('tilesJson').value = JSON.stringify(tiles);
}
document.getElementById('stampForm').onsubmit = () => saveData();
</script>
@@ -0,0 +1,128 @@
using DataServer.Data;
using DataServer.Data.Entities;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Text.Json;
namespace GameServices.Admin.Pages.DungeonBuilder.Stamps;
public class EditModel : AdminPageModel
{
private readonly GameDbContext _db;
private readonly IConfiguration _config;
public EditModel(GameDbContext db, IConfiguration config)
{
_db = db;
_config = config;
}
[BindProperty]
public TileStamp Stamp { get; set; } = new();
public List<TileMapSheet> TileSheets { get; set; } = new();
public List<TileDefinition> TileDefinitions { get; set; } = new();
public string TileDefinitionsJson => JsonSerializer.Serialize(
TileDefinitions.Select(t => new
{
id = t.Id,
sheetId = t.TileMapSheetId,
frameIndex = t.FrameIndex,
name = t.Name
})
);
public string CdnBaseUrl => NormalizeCdnBaseUrl(_config["Cdn:BaseUrl"]);
public string? Message { get; set; }
public bool IsError { get; set; }
public async Task OnGetAsync(int? id)
{
await LoadReferenceData();
if (id.HasValue)
{
var stamp = await _db.TileStamps.FindAsync(id.Value);
if (stamp != null)
{
Stamp = stamp;
}
}
else
{
Stamp.IsEnabled = true;
Stamp.Width = 1;
Stamp.Height = 1;
}
}
public async Task<IActionResult> OnPostAsync()
{
await LoadReferenceData();
if (string.IsNullOrWhiteSpace(Stamp.Name))
{
IsError = true;
Message = "Name is required.";
return Page();
}
Stamp.UpdatedAt = DateTime.UtcNow;
if (Stamp.Id == 0)
{
Stamp.CreatedAt = DateTime.UtcNow;
_db.TileStamps.Add(Stamp);
Message = "Stamp created!";
}
else
{
var existing = await _db.TileStamps.FindAsync(Stamp.Id);
if (existing == null)
{
IsError = true;
Message = "Stamp not found.";
return Page();
}
existing.Name = Stamp.Name;
existing.Description = Stamp.Description;
existing.Width = Stamp.Width;
existing.Height = Stamp.Height;
existing.TilesJson = Stamp.TilesJson;
existing.IsEnabled = Stamp.IsEnabled;
existing.UpdatedAt = DateTime.UtcNow;
}
await _db.SaveChangesAsync();
return RedirectToPage(new { id = Stamp.Id });
}
private async Task LoadReferenceData()
{
TileSheets = await _db.TileMapSheets
.Where(s => s.IsEnabled)
.OrderBy(s => s.Name)
.ToListAsync();
TileDefinitions = await _db.TileDefinitions
.Where(t => t.IsEnabled)
.OrderBy(t => t.TileMapSheetId)
.ThenBy(t => t.FrameIndex)
.ToListAsync();
}
private string NormalizeCdnBaseUrl(string? baseUrl)
{
baseUrl = string.IsNullOrWhiteSpace(baseUrl)
? "https://assets.aeternalisgames.com"
: baseUrl;
baseUrl = baseUrl.TrimEnd('/');
if (!baseUrl.EndsWith("/downloads", StringComparison.OrdinalIgnoreCase))
baseUrl += "/downloads";
return baseUrl;
}
}
@@ -0,0 +1,66 @@
@page "/admin/dungeonbuilder/stamps"
@model DungeonBuilder.Stamps.IndexModel
@{
ViewData["Title"] = "Tile Stamps";
}
<div class="mb-4">
<a href="/admin/dungeonbuilder" class="text-blue-400 hover:text-blue-300 text-sm">&larr; Back to Dungeon Builder</a>
</div>
<div class="flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-6">
<div>
<h1 class="text-2xl font-bold text-white">Tile Stamps</h1>
<p class="text-gray-400 text-sm mt-1">Saved multi-tile patterns for fast painting</p>
</div>
<a href="/admin/dungeonbuilder/stamps/edit" class="btn btn-primary">+ New Stamp</a>
</div>
@if (!string.IsNullOrEmpty(Model.Message))
{
<div class="mb-4 p-3 rounded @(Model.IsError ? "bg-red-900/50 text-red-300" : "bg-green-900/50 text-green-300")">
@Model.Message
</div>
}
<div class="card p-4">
<table class="w-full text-sm">
<thead>
<tr class="text-left text-gray-400 border-b border-gray-700">
<th class="pb-2 pr-4">Name</th>
<th class="pb-2 pr-4">Size</th>
<th class="pb-2 pr-4">Enabled</th>
<th class="pb-2">Actions</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-700/50">
@foreach (var s in Model.Stamps)
{
<tr class="hover:bg-gray-800/50">
<td class="py-2 pr-4 text-white">@s.Name</td>
<td class="py-2 pr-4 text-gray-400">@s.Width x @s.Height</td>
<td class="py-2 pr-4">
<span class="px-2 py-0.5 text-xs rounded @(s.IsEnabled ? "bg-green-900 text-green-300" : "bg-red-900 text-red-300")">
@(s.IsEnabled ? "On" : "Off")
</span>
</td>
<td class="py-2">
<div class="flex gap-2">
<a href="/admin/dungeonbuilder/stamps/edit?id=@s.Id" class="text-blue-400 hover:text-blue-300">Edit</a>
<form method="post" asp-page-handler="Delete" class="inline" onsubmit="return confirm('Delete this stamp?')">
<input type="hidden" name="id" value="@s.Id" />
<button type="submit" class="text-red-400 hover:text-red-300">Delete</button>
</form>
</div>
</td>
</tr>
}
@if (!Model.Stamps.Any())
{
<tr>
<td colspan="4" class="py-8 text-center text-gray-500">No stamps created yet.</td>
</tr>
}
</tbody>
</table>
</div>
@@ -0,0 +1,39 @@
using DataServer.Data;
using DataServer.Data.Entities;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace GameServices.Admin.Pages.DungeonBuilder.Stamps;
public class IndexModel : AdminPageModel
{
private readonly GameDbContext _db;
public IndexModel(GameDbContext db)
{
_db = db;
}
public List<TileStamp> Stamps { get; set; } = new();
public string? Message { get; set; }
public bool IsError { get; set; }
public async Task OnGetAsync()
{
Stamps = await _db.TileStamps
.OrderBy(s => s.Name)
.ToListAsync();
}
public async Task<IActionResult> OnPostDeleteAsync(int id)
{
var stamp = await _db.TileStamps.FindAsync(id);
if (stamp != null)
{
_db.TileStamps.Remove(stamp);
await _db.SaveChangesAsync();
}
return RedirectToPage();
}
}
@@ -288,6 +288,8 @@ let primarySet = false;
// All loaded sheets (by ID) for rendering tiles from any sheet
const loadedSheets = {};
const tileDefs = @Html.Raw(Model.TileDefinitionsJson);
const tileDefMap = {};
// Pre-load all sheet data from the dropdown
function preloadSheets() {
@@ -308,6 +310,9 @@ function preloadSheets() {
document.addEventListener('DOMContentLoaded', () => {
preloadSheets();
tileDefs.forEach(t => {
tileDefMap[`${t.sheetId}:${t.frameIndex}`] = t.id;
});
loadExisting();
buildTemplateGrid();
});
@@ -381,7 +386,7 @@ function paintCell(x, y) {
if (!selected) return;
const key = `${x},${y}`;
templateData[key] = { sheetId: selected.sheetId, frameIndex: selected.frameIndex };
templateData[key] = { sheetId: selected.sheetId, frameIndex: selected.frameIndex, tileDefId: selected.tileDefId };
// First tile becomes primary
if (!primarySet) {
@@ -430,7 +435,8 @@ function selectTile(frameIndex) {
document.querySelector(`.palette-tile[data-frame="${frameIndex}"]`)?.classList.add('active');
const sheet = loadedSheets[currentSheetId];
selected = { sheetId: currentSheetId, frameIndex };
const tileDefId = tileDefMap[`${currentSheetId}:${frameIndex}`] || null;
selected = { sheetId: currentSheetId, frameIndex, tileDefId };
document.getElementById('selectedInfo').textContent = `Frame ${frameIndex}`;
@@ -30,6 +30,16 @@ public class TileEditModel : AdminPageModel
public string? SocketConfigJson { get; set; }
public List<TileMapSheet> TileSheets { get; set; } = new();
public List<TileDefinition> TileDefinitions { get; set; } = new();
public string TileDefinitionsJson => JsonSerializer.Serialize(
TileDefinitions.Select(t => new
{
id = t.Id,
sheetId = t.TileMapSheetId,
frameIndex = t.FrameIndex
})
);
/// <summary>All existing socket names for autocomplete</summary>
public List<string> AllSocketNames { get; set; } = new();
@@ -214,6 +224,10 @@ public class TileEditModel : AdminPageModel
.Where(s => s.IsEnabled)
.OrderBy(s => s.Name)
.ToListAsync();
TileDefinitions = await _db.TileDefinitions
.Where(t => t.IsEnabled)
.ToListAsync();
AllSocketNames = await _db.SocketNames
.OrderByDescending(s => s.UsageCount)
+62 -4
View File
@@ -124,23 +124,72 @@
</div>
</div>
<!-- Note about Tile Templates -->
<!-- Note about Tile Definitions -->
@if (Model.Sheet.Id > 0)
{
<div class="card p-4 md:p-6 mt-4 md:mt-6">
<div class="flex items-center gap-3">
<div class="text-2xl">💡</div>
<div>
<h3 class="font-semibold text-white">Create Tile Templates</h3>
<h3 class="font-semibold text-white">Define Tile Properties</h3>
<p class="text-gray-400 text-sm mt-1">
To use tiles from this sheet, create <a href="/admin/dungeonbuilder/tiles" class="text-blue-400 hover:underline">Tile Templates</a>
which define walkability, sockets, and other properties.
Use Tile Definitions below to set walkability, buckets, and other gameplay properties per frame.
</p>
</div>
</div>
</div>
}
@if (Model.Sheet.Id > 0)
{
<div class="card p-4 md:p-6 mt-4 md:mt-6">
<div class="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
<div>
<h3 class="text-lg font-semibold text-white">Tile Definitions</h3>
<p class="text-gray-400 text-sm mt-1">Define gameplay properties and buckets per frame.</p>
</div>
<div class="flex gap-2">
<input type="number" id="frameJump" class="input text-sm w-28" min="0" placeholder="Frame #" />
<button type="button" class="btn btn-secondary text-sm" onclick="openTileEditor()">Edit Frame</button>
</div>
</div>
<div class="overflow-x-auto mt-4">
<table class="w-full text-sm">
<thead>
<tr class="text-left text-gray-400 border-b border-gray-700">
<th class="pb-2 pr-4">Frame</th>
<th class="pb-2 pr-4">Name</th>
<th class="pb-2 pr-4">Type</th>
<th class="pb-2 pr-4">Buckets</th>
<th class="pb-2">Actions</th>
</tr>
</thead>
<tbody class="divide-y divide-gray-700/50">
@foreach (var row in Model.TileDefinitionRows)
{
<tr class="hover:bg-gray-800/50">
<td class="py-2 pr-4 text-gray-300">@row.FrameIndex</td>
<td class="py-2 pr-4 text-white">@(!string.IsNullOrWhiteSpace(row.Name) ? row.Name : "-")</td>
<td class="py-2 pr-4 text-gray-400">@row.Type</td>
<td class="py-2 pr-4 text-gray-400">@row.BucketCount</td>
<td class="py-2">
<a href="/admin/tilemaps/tiles/edit?id=@row.Id" class="text-blue-400 hover:text-blue-300">Edit</a>
</td>
</tr>
}
@if (!Model.TileDefinitionRows.Any())
{
<tr>
<td colspan="5" class="py-6 text-center text-gray-500">No tile definitions yet. Use "Edit Frame" to create one.</td>
</tr>
}
</tbody>
</table>
</div>
</div>
}
<!-- CDN Browser Modal -->
<div id="cdnBrowserModal" class="fixed inset-0 bg-black/50 z-50 hidden items-center justify-center p-4">
<div class="bg-gray-900 rounded-xl shadow-xl p-4 md:p-6 w-full max-w-2xl border border-gray-700 max-h-[90vh] overflow-hidden flex flex-col">
@@ -230,5 +279,14 @@
closeCdnBrowser();
}
});
function openTileEditor() {
const frame = document.getElementById('frameJump').value;
if (frame === '') {
alert('Enter a frame index.');
return;
}
window.location.href = `/admin/tilemaps/tiles/edit?sheetId=@Model.Sheet.Id&frameIndex=${frame}`;
}
</script>
}
@@ -20,6 +20,7 @@ public class EditModel : AdminPageModel
public TileMapSheet Sheet { get; set; } = new();
public List<TileDefinition> TileDefinitions { get; set; } = new();
public List<TileDefinitionRow> TileDefinitionRows { get; set; } = new();
public List<ClientAsset> CdnImages { get; set; } = new();
public string CdnBaseUrl { get; set; } = "";
@@ -54,6 +55,7 @@ public class EditModel : AdminPageModel
{
Sheet = sheet;
TileDefinitions = sheet.Tiles?.OrderBy(t => t.FrameIndex).ToList() ?? new();
await LoadTileDefinitionRows();
}
}
else
@@ -109,6 +111,8 @@ public class EditModel : AdminPageModel
.Where(t => t.TileMapSheetId == Sheet.Id)
.OrderBy(t => t.FrameIndex)
.ToListAsync();
await LoadTileDefinitionRows();
}
}
catch (Exception ex)
@@ -296,4 +300,44 @@ public class EditModel : AdminPageModel
return baseUrl;
}
private async Task LoadTileDefinitionRows()
{
if (Sheet.Id == 0)
{
TileDefinitionRows = new();
return;
}
var tileDefs = await _db.TileDefinitions
.Where(t => t.TileMapSheetId == Sheet.Id)
.OrderBy(t => t.FrameIndex)
.ToListAsync();
var tileIds = tileDefs.Select(t => t.Id).ToList();
var bucketCounts = await _db.TileDefinitionBuckets
.Where(b => tileIds.Contains(b.TileDefinitionId))
.GroupBy(b => b.TileDefinitionId)
.Select(g => new { TileDefinitionId = g.Key, Count = g.Count() })
.ToDictionaryAsync(g => g.TileDefinitionId, g => g.Count);
TileDefinitionRows = tileDefs.Select(t => new TileDefinitionRow
{
Id = t.Id,
FrameIndex = t.FrameIndex,
Name = t.Name,
Type = t.Type.ToString(),
BucketCount = bucketCounts.TryGetValue(t.Id, out var count) ? count : 0
}).ToList();
}
public class TileDefinitionRow
{
public int Id { get; set; }
public int FrameIndex { get; set; }
public string? Name { get; set; }
public string Type { get; set; } = "";
public int BucketCount { get; set; }
}
}
@@ -0,0 +1,174 @@
@page "/admin/tilemaps/tiles/edit"
@model TileMaps.TileEditModel
@using DataServer.Data.Entities
@{
ViewData["Title"] = Model.Tile.Id == 0 ? "New Tile Definition" : $"Edit Tile Definition: {Model.Tile.Name ?? $"Frame {Model.Tile.FrameIndex}"}";
var sheet = Model.Sheet;
var frameIndex = Model.Tile.FrameIndex;
var cols = sheet.Columns;
var col = cols > 0 ? frameIndex % cols : 0;
var row = cols > 0 ? frameIndex / cols : 0;
var imageUrl = sheet.CdnPath;
if (!string.IsNullOrEmpty(imageUrl))
{
if (!imageUrl.StartsWith("http"))
{
var baseUrl = Model.CdnBaseUrl.TrimEnd('/');
if (!baseUrl.EndsWith("/downloads"))
{
baseUrl += "/downloads";
}
imageUrl = $"{baseUrl}/{imageUrl.TrimStart('/')}";
}
}
}
<div class="mb-4">
<a href="/admin/tilemaps/edit?id=@sheet.Id" class="text-blue-400 hover:text-blue-300 text-sm">&larr; Back to TileMap Sheet</a>
</div>
<h1 class="text-2xl font-bold text-white mb-6">@ViewData["Title"]</h1>
@if (!string.IsNullOrEmpty(Model.Message))
{
<div class="mb-4 p-3 rounded @(Model.IsError ? "bg-red-900/50 text-red-300" : "bg-green-900/50 text-green-300")">
@Model.Message
</div>
}
<form method="post">
@Html.AntiForgeryToken()
<input type="hidden" asp-for="Tile.Id" />
<input type="hidden" asp-for="Tile.TileMapSheetId" />
<input type="hidden" asp-for="Tile.FrameIndex" />
<div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
<div class="card p-4 space-y-3">
<h3 class="font-semibold text-white">Tile Preview</h3>
<div class="bg-gray-900 rounded p-4 flex items-center justify-center">
<div style="width:@(sheet.TileWidth)px;height:@(sheet.TileHeight)px;background:url('@imageUrl') @(-col * sheet.TileWidth)px @(-row * sheet.TileHeight)px no-repeat;background-size:@(sheet.SheetWidth)px @(sheet.SheetHeight)px;image-rendering:pixelated;"></div>
</div>
<div class="text-xs text-gray-500">
Sheet: <span class="text-gray-300">@sheet.Name</span><br />
Frame: <span class="text-gray-300">@frameIndex</span>
</div>
</div>
<div class="card p-4 space-y-3">
<h3 class="font-semibold text-white">Tile Properties</h3>
<div>
<label class="text-xs text-gray-400">Name</label>
<input type="text" asp-for="Tile.Name" class="input w-full text-sm" placeholder="Stone Floor Clean" />
</div>
<div>
<label class="text-xs text-gray-400">Type</label>
<select asp-for="Tile.Type" class="input w-full text-sm">
@foreach (var t in Enum.GetValues<TileType>())
{
<option value="@t">@t</option>
}
</select>
</div>
<div>
<label class="text-xs text-gray-400">Tags</label>
<input type="text" asp-for="Tile.Tags" class="input w-full text-sm" placeholder="stone,clean" />
</div>
<div>
<label class="text-xs text-gray-400">Biome</label>
<input type="text" asp-for="Tile.Biome" class="input w-full text-sm" placeholder="dungeon" />
</div>
<div class="grid grid-cols-2 gap-2">
<div class="flex items-center gap-2">
<input type="checkbox" asp-for="Tile.IsWalkable" class="rounded" />
<label class="text-sm text-gray-300">Walkable</label>
</div>
<div class="flex items-center gap-2">
<input type="checkbox" asp-for="Tile.BlocksProjectiles" class="rounded" />
<label class="text-sm text-gray-300">Blocks Projectiles</label>
</div>
<div class="flex items-center gap-2">
<input type="checkbox" asp-for="Tile.BlocksLineOfSight" class="rounded" />
<label class="text-sm text-gray-300">Blocks LOS</label>
</div>
<div class="flex items-center gap-2">
<input type="checkbox" asp-for="Tile.IsInteractable" class="rounded" />
<label class="text-sm text-gray-300">Interactable</label>
</div>
</div>
<div class="grid grid-cols-2 gap-2">
<div>
<label class="text-xs text-gray-400">Render Layer</label>
<input type="number" asp-for="Tile.RenderLayer" class="input w-full text-sm" min="0" />
</div>
<div>
<label class="text-xs text-gray-400">Z Index</label>
<input type="number" asp-for="Tile.ZIndex" class="input w-full text-sm" min="0" />
</div>
</div>
<div class="grid grid-cols-2 gap-2">
<div class="flex items-center gap-2">
<input type="checkbox" asp-for="Tile.IsAnimated" class="rounded" />
<label class="text-sm text-gray-300">Animated</label>
</div>
<div class="flex items-center gap-2">
<input type="checkbox" asp-for="Tile.IsEnabled" class="rounded" />
<label class="text-sm text-gray-300">Enabled</label>
</div>
</div>
<div class="grid grid-cols-2 gap-2">
<div>
<label class="text-xs text-gray-400">Anim Frames</label>
<input type="number" asp-for="Tile.AnimationFrameCount" class="input w-full text-sm" min="1" />
</div>
<div>
<label class="text-xs text-gray-400">Anim FPS</label>
<input type="number" asp-for="Tile.AnimationFps" class="input w-full text-sm" min="1" step="0.5" />
</div>
</div>
</div>
<div class="card p-4 space-y-3">
<h3 class="font-semibold text-white">Buckets</h3>
<p class="text-xs text-gray-500">Assign this tile to one or more buckets.</p>
<input type="text" id="bucketFilter" class="input w-full text-sm" placeholder="Type to filter buckets..." oninput="filterBuckets()" />
<div id="bucketList" class="max-h-80 overflow-auto border border-gray-700 rounded p-2 space-y-1">
@foreach (var b in Model.AllBuckets)
{
<label class="flex items-center gap-2 text-sm text-gray-300 bucket-item" data-name="@b.Name.ToLower()">
<input type="checkbox" name="bucketIds" value="@b.Id" class="rounded"
@(Model.SelectedBucketIds.Contains(b.Id) ? "checked" : "") />
<span>@b.Name</span>
@if (!string.IsNullOrWhiteSpace(b.BucketType))
{
<span class="text-xs text-gray-500 ml-auto">@b.BucketType</span>
}
</label>
}
@if (!Model.AllBuckets.Any())
{
<div class="text-xs text-gray-500">No buckets defined yet.</div>
}
</div>
</div>
</div>
<div class="flex justify-end gap-4 mt-6">
<a href="/admin/tilemaps/edit?id=@sheet.Id" class="btn btn-ghost">Cancel</a>
<button type="submit" class="btn btn-primary">
@(Model.Tile.Id == 0 ? "Create Tile" : "Save Changes")
</button>
</div>
</form>
@section Scripts {
<script>
function filterBuckets() {
const q = document.getElementById('bucketFilter').value.toLowerCase();
document.querySelectorAll('.bucket-item').forEach(el => {
el.style.display = el.dataset.name.includes(q) ? '' : 'none';
});
}
</script>
}
@@ -0,0 +1,177 @@
using DataServer.Data;
using DataServer.Data.Entities;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace GameServices.Admin.Pages.TileMaps;
public class TileEditModel : AdminPageModel
{
private readonly GameDbContext _db;
private readonly IConfiguration _config;
public TileEditModel(GameDbContext db, IConfiguration config)
{
_db = db;
_config = config;
}
[BindProperty]
public TileDefinition Tile { get; set; } = new();
public TileMapSheet Sheet { get; set; } = new();
public List<TileBucket> AllBuckets { get; set; } = new();
public HashSet<int> SelectedBucketIds { get; set; } = new();
public string CdnBaseUrl { get; set; } = "";
public string? Message { get; set; }
public bool IsError { get; set; }
public async Task<IActionResult> OnGetAsync(int? id, int? sheetId, int? frameIndex)
{
CdnBaseUrl = NormalizeCdnBaseUrl(_config["Cdn:BaseUrl"]);
AllBuckets = await _db.TileBuckets.OrderBy(b => b.Name).ToListAsync();
if (id.HasValue)
{
var tile = await _db.TileDefinitions
.Include(t => t.TileMapSheet)
.FirstOrDefaultAsync(t => t.Id == id.Value);
if (tile == null) return RedirectToPage("/TileMaps/Index");
Tile = tile;
Sheet = tile.TileMapSheet ?? await _db.TileMapSheets.FindAsync(tile.TileMapSheetId) ?? new TileMapSheet();
SelectedBucketIds = await _db.TileDefinitionBuckets
.Where(b => b.TileDefinitionId == tile.Id)
.Select(b => b.TileBucketId)
.ToHashSetAsync();
return Page();
}
if (!sheetId.HasValue || !frameIndex.HasValue)
{
return RedirectToPage("/TileMaps/Index");
}
var sheet = await _db.TileMapSheets.FindAsync(sheetId.Value);
if (sheet == null) return RedirectToPage("/TileMaps/Index");
Sheet = sheet;
var existing = await _db.TileDefinitions
.FirstOrDefaultAsync(t => t.TileMapSheetId == sheetId.Value && t.FrameIndex == frameIndex.Value);
if (existing != null)
{
Tile = existing;
SelectedBucketIds = await _db.TileDefinitionBuckets
.Where(b => b.TileDefinitionId == existing.Id)
.Select(b => b.TileBucketId)
.ToHashSetAsync();
}
else
{
Tile = new TileDefinition
{
TileMapSheetId = sheetId.Value,
FrameIndex = frameIndex.Value,
IsEnabled = true,
IsWalkable = true,
Type = TileType.Floor
};
}
return Page();
}
public async Task<IActionResult> OnPostAsync()
{
CdnBaseUrl = NormalizeCdnBaseUrl(_config["Cdn:BaseUrl"]);
AllBuckets = await _db.TileBuckets.OrderBy(b => b.Name).ToListAsync();
if (Tile.TileMapSheetId == 0)
{
IsError = true;
Message = "Missing tilemap sheet.";
return Page();
}
Sheet = await _db.TileMapSheets.FindAsync(Tile.TileMapSheetId) ?? new TileMapSheet();
var bucketIds = Request.Form["bucketIds"]
.Select(v => int.TryParse(v, out var id) ? id : 0)
.Where(id => id > 0)
.ToHashSet();
if (Tile.Id == 0)
{
_db.TileDefinitions.Add(Tile);
await _db.SaveChangesAsync();
}
else
{
var existing = await _db.TileDefinitions.FindAsync(Tile.Id);
if (existing == null)
{
IsError = true;
Message = "Tile definition not found.";
return Page();
}
existing.Name = Tile.Name;
existing.Type = Tile.Type;
existing.Tags = Tile.Tags;
existing.Biome = Tile.Biome;
existing.IsWalkable = Tile.IsWalkable;
existing.BlocksProjectiles = Tile.BlocksProjectiles;
existing.BlocksLineOfSight = Tile.BlocksLineOfSight;
existing.IsInteractable = Tile.IsInteractable;
existing.RenderLayer = Tile.RenderLayer;
existing.ZIndex = Tile.ZIndex;
existing.IsAnimated = Tile.IsAnimated;
existing.AnimationFrameCount = Tile.AnimationFrameCount;
existing.AnimationFps = Tile.AnimationFps;
existing.IsEnabled = Tile.IsEnabled;
}
await _db.SaveChangesAsync();
var tileId = Tile.Id;
if (tileId == 0)
{
tileId = await _db.TileDefinitions
.Where(t => t.TileMapSheetId == Tile.TileMapSheetId && t.FrameIndex == Tile.FrameIndex)
.Select(t => t.Id)
.FirstAsync();
}
var existingLinks = _db.TileDefinitionBuckets.Where(b => b.TileDefinitionId == tileId);
_db.TileDefinitionBuckets.RemoveRange(existingLinks);
foreach (var bucketId in bucketIds)
{
_db.TileDefinitionBuckets.Add(new TileDefinitionBucket
{
TileDefinitionId = tileId,
TileBucketId = bucketId
});
}
await _db.SaveChangesAsync();
return RedirectToPage(new { id = tileId });
}
private string NormalizeCdnBaseUrl(string? baseUrl)
{
baseUrl = string.IsNullOrWhiteSpace(baseUrl)
? "https://assets.aeternalisgames.com"
: baseUrl;
baseUrl = baseUrl.TrimEnd('/');
if (!baseUrl.EndsWith("/downloads", StringComparison.OrdinalIgnoreCase))
baseUrl += "/downloads";
return baseUrl;
}
}
+72
View File
@@ -0,0 +1,72 @@
# Dungeon Tile System Overhaul (Plan)
Goal: Unify live dungeon editor, Builder, and TileMaps around a shared tile metadata model that supports decoration overlays and animation behavior.
## Tile Types
- Floor: base walkable tile.
- Wall: base blocking tile.
- Decoration: overlay tile that does not modify underlying base tile properties.
## Tile Properties (Base)
- `type`: floor | wall | decoration
- `isStatic`: bool (static vs animated)
- `blocksLos`: bool
- `blocksProjectiles`: bool
- `interactable`: bool
## Tile Properties (Animation)
Only if `isStatic = false`:
- `frames`: ordered list of frame indices (from the same sheet)
- `frameRate`: float (fps) or `frameDurationMs` (pick one)
- `trigger`: `tick` | `interaction`
- `endBehavior`: `reset` | `loop` | `stop`
- `reset`: return to frame 0 and stop
- `loop`: continuously loop
- `stop`: stop on last frame
- `finalFrameOverrides` (optional):
- Properties that change when animation ends, e.g. `blocksLos`, `blocksProjectiles`, `walkable`, `interactable`
## Apply Scope
- `scope = tile_instance` (this placement only)
- `scope = tile_type` (all tiles with this sprite definition)
## Data Model (Draft)
Shared metadata should be stored once and used by:
- Live editor (runtime overrides)
- Builder (authoring time)
- TileMaps (definition time)
Proposed entities:
- `TileDefinition` (global): sheetId + frameIndex + base properties + animation settings
- `TileInstanceOverride` (per placement): overrides for base/animation props
- `DecorationLayer` (per placement): optional overlay(s) with own definition and properties
## UI Flow (Live Editor)
1) Mode toggle: View | Edit
2) Tile Picker enabled only in Edit
3) Select Sheet ? Select Tile(s)
4) Show "Tile Properties" panel
5) Choose Apply Scope: This Tile Only / All Tiles of This Type
6) For Animated:
- select frames
- trigger (interaction/tick)
- endBehavior (reset/loop/stop)
- optional final frame overrides
## Builder + TileMaps
- Should surface the same Tile Properties UI and write to the same tables/JSON
- Decoration tiles must be placeable on top of base tiles without changing base
## DungeonSimulation Impact
- Must resolve base tile + decoration layers into:
- walkability
- LOS blocking
- projectile blocking
- interactability
- Animated tiles with end behavior + final overrides must update tile state at runtime
- e.g. door animation ends ? walkable = true, blocksLos = false
## Open Questions
- Should `frameRate` be global per definition or per instance?
- Should decoration tiles participate in collisions (default: no)?
- Do we allow multiple decorations per tile? If yes, define max layers.
+292
View File
@@ -0,0 +1,292 @@
# Tile Management Revamp — Verbose Plan (with examples)
This is a draft plan for replacing socket-based connections with a bucket/graph system and consolidating tile management across TileMaps, Builder, and runtime generation. It is intentionally verbose and example-driven so we can refine the model before coding.
---
## 0) Goals (What We Want)
- Remove socket matching; replace with bucket-based connectivity rules.
- Make tile metadata consistent across:
- TileMaps (sheet registration only)
- Builder (tile definitions, room templates, object templates)
- Live editor (overrides)
- Scale the same model to:
- Dungeons (procedural rooms + corridors)
- Overworld (large persistent world)
- Support connectivity cardinality:
- 1 → 1 (strict)
- 1 → many
- many ↔ many
- Biomes are buckets.
---
## 1) Big Picture Architecture
### 1.1 TileMaps (Sheet Registry Only)
- TileMaps only store:
- CDN path
- image dimensions
- tile size
- enabled flag
- No gameplay properties live here.
### 1.2 Builder (Where Everything Is Defined)
- Builder owns:
- Tile Definitions (properties + buckets)
- Room Templates
- Object Templates
- Tile “stamps” (optional multi-tile patterns)
- Builder becomes the single source of gameplay tile metadata.
### 1.3 Generation & Runtime
- Generator uses buckets + rules to place tiles.
- Room templates can ignore bucket constraints (painted layouts are authoritative).
- DungeonSimulation consumes resolved layout (walkability, LOS, projectile blocking, interactions), not editor concepts.
---
## 2) Data Model (Draft)
### 2.1 TileDefinition
Represents one tile frame and its gameplay meaning.
**Fields (proposed):**
- `id`
- `sheetId`
- `frameIndex`
- `name`
- `tags` (optional)
- `buckets: string[]` (one tile can be in many buckets)
- `properties`
- `walkable: bool`
- `blocksLos: bool`
- `blocksProjectiles: bool`
- `interactable: bool`
- `type: floor | wall | decoration | water | etc` (optional — could be a bucket instead)
- `renderLayer` (visual)
- `isEnabled`
### 2.2 BucketRule (Global)
Controls which buckets can connect.
**Fields (proposed):**
- `bucket: string`
- `allows: string[]` (explicit allow-list)
- `weights?: { bucket: string, weight: float }[]` (optional)
- `directional?: bool` (optional, default false)
**Cardinality support**
- 1→1: bucket allows exactly one target.
- 1→many: bucket allows multiple targets.
- many↔many: multiple buckets allow each other.
### 2.3 Palette (Theme Filter + Generation Rules)
**Fields (proposed):**
- `allowedBuckets: string[]`
- `allowedTileIds: int[]` (optional explicit list)
- `roomRules: { minRooms, maxRooms, sizes, corridorWidth }`
- `densityRules: { decorations, containers, traps }`
### 2.4 TileInstanceOverride (optional)
- Used for live editor or per-instance overrides.
- Applies on top of a TileDefinition.
---
## 3) Buckets: Examples
### 3.1 Basic Dungeon Buckets
```
Buckets:
floor_basic
wall_outer
wall_inner
doorway
corridor
deco_wall
deco_floor
biome_dungeon
```
### 3.2 Basic Overworld Buckets
```
Buckets:
biome_forest
biome_plains
biome_tundra
ground_grass
ground_dirt
water_shallow
water_deep
coast
path
```
### 3.3 Example: Tile Definitions
**Stone Floor (Dungeon)**
- buckets: `floor_basic`, `corridor`, `biome_dungeon`
- walkable: true
- blocksLos: false
- blocksProjectiles: false
**Dungeon Wall**
- buckets: `wall_outer`, `biome_dungeon`
- walkable: false
- blocksLos: true
- blocksProjectiles: true
**Forest Grass**
- buckets: `ground_grass`, `biome_forest`
- walkable: true
**Forest Water Edge (Coast)**
- buckets: `coast`, `biome_forest`, `water_shallow`
- walkable: false (or true if shallow is walkable)
---
## 4) BucketRule Examples
### 4.1 Dungeon (Global Rules)
```
Rule: floor_basic allows [floor_basic, corridor, doorway]
Rule: corridor allows [corridor, floor_basic, doorway]
Rule: doorway allows [floor_basic, corridor]
Rule: wall_outer allows [wall_outer]
Rule: wall_inner allows [wall_inner]
Rule: deco_floor allows [floor_basic, corridor]
```
### 4.2 Overworld (Global Rules)
```
Rule: ground_grass allows [ground_grass, ground_dirt, path, coast]
Rule: ground_dirt allows [ground_dirt, ground_grass, path, coast]
Rule: coast allows [ground_grass, ground_dirt, water_shallow]
Rule: water_shallow allows [coast, water_shallow, water_deep]
Rule: water_deep allows [water_shallow, water_deep]
```
### 4.3 1→1 Example
```
Rule: doorway_strict allows [corridor_strict]
Rule: corridor_strict allows [doorway_strict]
```
### 4.4 Weighted Example
```
Rule: ground_grass allows [ground_grass (weight 0.7), ground_dirt (weight 0.2), path (weight 0.1)]
```
---
## 5) Procedural Generation Strategy (Bucket-Based)
### 5.1 Flow (Dungeon)
1) Choose palette (filters allowed buckets/tiles).
2) Create room graph (rooms + corridors) ignoring bucket constraints.
3) Fill room interiors with `floor_basic` bucket.
4) Build walls from `wall_outer` bucket around floors.
5) Place doorways where corridors connect to rooms.
6) Place decorations by choosing tiles from `deco_floor` and `deco_wall` buckets.
### 5.2 Flow (Overworld)
1) Choose biome region per chunk (biome bucket).
2) Seed ground layer using biome ground buckets.
3) Apply adjacency rules for transitions (coast, rivers, paths).
4) Add decorations/objects by bucket + density rules.
---
## 6) Builder UX Changes (Proposed)
### 6.1 Tile Definition Editor
- Select TileMap sheet
- Click frame
- Set properties (walkable, LOS, projectiles, interactable)
- Assign buckets (multi-select)
- Optional tags
### 6.2 Bucket Manager
- Define bucket names
- Define allowed connections (matrix or allow-list)
- Optional weights
- Global scope (shared across palettes)
### 6.3 Room Template Editor
- Paint tiles based on Tile Definitions
- Ignore connectivity/bucket constraints
- Save grid and spawns as-is
### 6.4 Palette Editor
- Choose bucket sets to enable for generation
- Choose tile definitions explicitly (optional)
- Set density rules and room/corridor ranges
---
## 7) Runtime (DungeonSimulation) Alignment
- Simulation does not need to know about buckets.
- It only needs resolved tile properties:
- walkable
- blocks LOS
- blocks projectiles
- interactable
- Generator should output a resolved layout (tile properties per cell).
---
## 8) Migration Strategy (Phased)
### Phase 1: Data Model
- Add buckets to TileDefinitions in Builder.
- Add BucketRules as global config.
- Keep sockets temporarily for compatibility.
### Phase 2: Builder UI
- Tile Definition editor gains bucket assignment.
- New Bucket Manager UI.
- Room editor uses TileDefinitions (not socketed TileTemplates).
### Phase 3: Generator
- Remove socket matching.
- Generate from bucket adjacency rules.
### Phase 4: Cleanup
- Retire socket fields from TileTemplates/TileDefinitions.
- Remove socket UI.
---
## 9) Open Decisions
- Should TileTemplates remain for multi-tile stamps, or be replaced by “paint + stamps” in Builder?
- How many decoration layers do we want per tile?
- Should biome membership be required for all tiles, or optional?
- Should bucket adjacency allow directional rules (north/south) or always symmetric?
---
## 10) Next Steps (If This Plan Looks Right)
1) Confirm multi-tile pattern approach (keep vs remove).
2) Decide how BucketRules are stored (DB table vs JSON config).
3) Draft the minimal schema changes.
4) Update Builder UX to handle bucket assignments.
5) Implement generator using bucket adjacency.
---
End of plan.
## Decisions Locked In (from latest notes)
- Buckets must be add/remove‑able from tiles, with a searchable dropdown (type to filter, then select). Provide multi‑select chips with remove.
- Bucket rules must allow explicit allow‑lists so a tile/bucket can connect only to specific buckets (e.g., X connects only to Y and Z).
- Tile type should be editable (e.g., Floor/Wall/Decoration), and membership in that type can be managed (add/remove).
- TileTemplates decision: **replace with paint + stamps in Builder** (stamps are just saved selections of tiles for fast painting).
- Decoration layers per tile: **4 layers**.
- Biome membership: **optional**, with a global checkbox to enforce or not.
- Bucket adjacency: **non‑directional/symmetric**. Specificity is handled by bucket assignment and allow‑lists.
+4
View File
@@ -36,6 +36,10 @@ public sealed class GameDbContext : DbContext
// TileMap system
public DbSet<TileMapSheet> TileMapSheets => Set<TileMapSheet>();
public DbSet<TileDefinition> TileDefinitions => Set<TileDefinition>();
public DbSet<TileBucket> TileBuckets => Set<TileBucket>();
public DbSet<TileBucketRule> TileBucketRules => Set<TileBucketRule>();
public DbSet<TileDefinitionBucket> TileDefinitionBuckets => Set<TileDefinitionBucket>();
public DbSet<TileStamp> TileStamps => Set<TileStamp>();
public DbSet<RoomTemplate> RoomTemplates => Set<RoomTemplate>();
public DbSet<DungeonTemplate> DungeonTemplates => Set<DungeonTemplate>();
public DbSet<DungeonObjectDefinition> DungeonObjects => Set<DungeonObjectDefinition>();
+12
View File
@@ -513,6 +513,18 @@ public class DungeonPalette
[MaxLength(256)]
public string? Tags { get; set; }
/// <summary>
/// Optional allowed bucket IDs for generation filtering.
/// JSON array of TileBucket.Id values.
/// </summary>
[Column(TypeName = "json")]
public string? AllowedBucketIdsJson { get; set; }
/// <summary>
/// If true, tiles must include the palette biome bucket.
/// </summary>
public bool EnforceBiomeBuckets { get; set; } = false;
// --- Template Collections (JSON arrays of IDs) ---
/// <summary>Floor tile template IDs</summary>
+103
View File
@@ -0,0 +1,103 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace DataServer.Data.Entities;
/// <summary>
/// Bucket used for tile connectivity and filtering.
/// </summary>
[Table("tile_buckets")]
public class TileBucket
{
[Key]
public int Id { get; set; }
[Required, MaxLength(64)]
public string Name { get; set; } = "";
/// <summary>Optional bucket category/type (e.g., "biome", "floor", "wall")</summary>
[MaxLength(32)]
public string? BucketType { get; set; }
[MaxLength(256)]
public string? Description { get; set; }
public bool IsEnabled { get; set; } = true;
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
}
/// <summary>
/// Explicit allow-list rule: Source bucket can connect to Target bucket.
/// </summary>
[Table("tile_bucket_rules")]
public class TileBucketRule
{
[Key]
public int Id { get; set; }
public int SourceBucketId { get; set; }
public int TargetBucketId { get; set; }
/// <summary>Optional weight for selection bias (1.0 = default)</summary>
public float Weight { get; set; } = 1.0f;
[ForeignKey(nameof(SourceBucketId))]
public TileBucket? SourceBucket { get; set; }
[ForeignKey(nameof(TargetBucketId))]
public TileBucket? TargetBucket { get; set; }
}
/// <summary>
/// Join table: which buckets a tile definition belongs to.
/// </summary>
[Table("tile_definition_buckets")]
public class TileDefinitionBucket
{
[Key]
public int Id { get; set; }
public int TileDefinitionId { get; set; }
public int TileBucketId { get; set; }
[ForeignKey(nameof(TileDefinitionId))]
public TileDefinition? TileDefinition { get; set; }
[ForeignKey(nameof(TileBucketId))]
public TileBucket? TileBucket { get; set; }
}
/// <summary>
/// Saved stamp of multiple tile placements for fast painting.
/// </summary>
[Table("tile_stamps")]
public class TileStamp
{
[Key]
public int Id { get; set; }
[Required, MaxLength(64)]
public string Name { get; set; } = "";
[MaxLength(256)]
public string? Description { get; set; }
public int Width { get; set; } = 1;
public int Height { get; set; } = 1;
/// <summary>
/// JSON array of placements: { x, y, tileDefinitionId, layer }
/// </summary>
[Column(TypeName = "json")]
public string? TilesJson { get; set; }
public bool IsEnabled { get; set; } = true;
public DateTime CreatedAt { get; set; } = DateTime.UtcNow;
public DateTime UpdatedAt { get; set; } = DateTime.UtcNow;
}
+3
View File
@@ -108,6 +108,9 @@ public class TileDefinition
/// <summary>Whether this blocks line of sight</summary>
public bool BlocksLineOfSight { get; set; } = false;
/// <summary>Whether this tile can be interacted with</summary>
public bool IsInteractable { get; set; } = false;
/// <summary>Layer for rendering order (0=ground, 1=floor decor, 2=walls, 3=ceiling)</summary>
public int RenderLayer { get; set; } = 0;