Switch NPC editor to mob-style animation assignment selection

This commit is contained in:
dingo
2026-02-14 02:06:51 -05:00
parent 4ba5a1040b
commit 40d8570550
2 changed files with 347 additions and 204 deletions
+182 -108
View File
@@ -4,8 +4,23 @@
@using DataServer.Data.Enums @using DataServer.Data.Enums
@{ @{
ViewData["Title"] = Model.IsNew ? "Create NPC" : $"Edit: {Model.Npc.Name}"; ViewData["Title"] = Model.IsNew ? "Create NPC" : $"Edit: {Model.Npc.Name}";
var selectedAbilitiesJson = JsonSerializer.Serialize(Model.SelectedAbilityIds); var selectedAbilitiesJson = JsonSerializer.Serialize(Model.SelectedAbilityIds);
var spriteSheetOptions = JsonSerializer.Serialize(Model.AllSpriteSheets.Select(s => new { id = s.Id, name = s.Name, cdnPath = s.CdnPath })); var selectedAnimationsJson = JsonSerializer.Serialize(Model.SelectedAnimations);
var animationCatalogJson = JsonSerializer.Serialize(Model.AllAnimations.Select(a => new
{
id = a.Id,
key = a.Key,
sheetName = a.SpriteSheet != null ? a.SpriteSheet.Name : "",
sheetPath = a.SpriteSheet != null ? a.SpriteSheet.CdnPath : "",
frameSequence = a.FrameSequence,
fps = a.Fps,
loop = a.Loop,
flipX = a.FlipX,
flipY = a.FlipY,
search = ($"{a.Key} {(a.Name ?? "")} {(a.SpriteSheet != null ? a.SpriteSheet.Name : "")} {(a.SpriteSheet != null ? a.SpriteSheet.CdnPath : "")}").ToLowerInvariant()
}));
var resistanceOptions = string.Join("", Model.ResistanceTypes.Select(rt => $"<option value=\"{rt.Key}\">{rt.DisplayName}</option>")); var resistanceOptions = string.Join("", Model.ResistanceTypes.Select(rt => $"<option value=\"{rt.Key}\">{rt.DisplayName}</option>"));
} }
@@ -146,7 +161,7 @@
</div> </div>
<div class="card"> <div class="card">
<div class="p-4 border-b border-gray-700 flex items-center justify-between"> <div class="p-4 border-b border-gray-700">
<h2 class="text-lg font-semibold text-white">Damage Resistances</h2> <h2 class="text-lg font-semibold text-white">Damage Resistances</h2>
</div> </div>
<div class="p-6"> <div class="p-6">
@@ -161,8 +176,7 @@
} }
@foreach (var resist in resistances) @foreach (var resist in resistances)
{ {
var bgColor = resist.Value < 0 ? "bg-red-900/30 border-red-700" : resist.Value > 0 ? "bg-green-900/30 border-green-700" : "bg-gray-800 border-gray-700"; <div class="bg-gray-800 border border-gray-700 rounded-lg p-3 flex items-center gap-4 resistance-row">
<div class="@bgColor border rounded-lg p-3 flex items-center gap-4 resistance-row">
<select name="resist_name[]" class="input w-40"> <select name="resist_name[]" class="input w-40">
@foreach (var rt in Model.ResistanceTypes) @foreach (var rt in Model.ResistanceTypes)
{ {
@@ -176,7 +190,7 @@
<span class="text-gray-400">%</span> <span class="text-gray-400">%</span>
</div> </div>
</div> </div>
<button type="button" onclick="this.closest('.resistance-row').remove()" class="p-2 text-red-400 hover:text-red-300">Remove</button> <button type="button" onclick="this.closest('.resistance-row').remove()" class="btn btn-danger btn-sm">Remove</button>
</div> </div>
} }
</div> </div>
@@ -225,62 +239,54 @@
</div> </div>
</div> </div>
<div class="card"> <div class="card" id="animations-section">
<div class="p-4 border-b border-gray-700"> <div class="p-4 border-b border-gray-700 flex items-center justify-between">
<h2 class="text-lg font-semibold text-white">Sprite Config</h2> <h2 class="text-lg font-semibold text-white">Animations</h2>
<button type="button" class="btn btn-primary btn-sm" onclick="showAddAnimationModal()">+ Add Animation</button>
</div> </div>
<div class="p-6 space-y-4"> <div class="p-6 overflow-x-auto">
<div class="grid grid-cols-1 md:grid-cols-3 gap-4"> <div id="animationHiddenInputs"></div>
<table class="w-full">
<thead class="bg-gray-900/50">
<tr>
<th class="table-header">Key</th>
<th class="table-header">Sheet</th>
<th class="table-header">Frames</th>
<th class="table-header">FPS</th>
<th class="table-header">Options</th>
<th class="table-header">Override Key</th>
<th class="table-header">Status</th>
<th class="table-header">Actions</th>
</tr>
</thead>
<tbody id="npcAnimationTableBody" class="divide-y divide-gray-700"></tbody>
</table>
</div>
</div>
<div id="addAnimationModal" class="fixed inset-0 bg-black/50 z-50 hidden items-center justify-center">
<div class="bg-gray-900 rounded-xl shadow-xl p-6 w-full max-w-md mx-4 border border-gray-700">
<h3 class="text-lg font-semibold text-white mb-4">Add Animation</h3>
<div class="space-y-4">
<div> <div>
<label class="label">Frame Width</label> <label class="label">Search</label>
<input type="number" name="sprite_frameWidth" value="@Model.SpriteConfig.FrameWidth" class="input" min="8" step="8" /> <input id="animationSearch" type="text" class="input mb-2" placeholder="Type to search animations..." oninput="filterAnimations()" autocomplete="off" />
<select id="animationSelect" class="input" size="10" style="height: auto;">
@foreach (var anim in Model.AllAnimations)
{
<option value="@anim.Id" data-search="@($"[{(anim.SpriteSheet?.Name ?? "?")}] {anim.Key} {anim.FrameSequence} {anim.Fps}".ToLowerInvariant())">[@(anim.SpriteSheet?.Name ?? "?")] @anim.Key - @anim.FrameSequence (@anim.Fps fps)</option>
}
</select>
</div> </div>
<div> <div>
<label class="label">Frame Height</label> <label class="label">Override Key (optional)</label>
<input type="number" name="sprite_frameHeight" value="@Model.SpriteConfig.FrameHeight" class="input" min="8" step="8" /> <input id="animationOverrideKey" type="text" class="input" placeholder="e.g. idle_down" />
</div>
<div>
<label class="label">Default FPS</label>
<input type="number" name="sprite_fps" value="@Model.SpriteConfig.Fps" class="input" min="1" max="60" />
</div> </div>
</div> </div>
<div class="flex justify-end gap-3 pt-4">
<div class="grid grid-cols-1 md:grid-cols-2 gap-4"> <button type="button" onclick="closeAddAnimationModal()" class="btn btn-secondary">Cancel</button>
<div> <button type="button" onclick="addAnimationFromModal()" class="btn btn-primary">Assign</button>
<label class="label">Filter Sprite Sheets</label>
<input id="spriteSheetSearch" type="text" class="input" placeholder="Type to filter sprite sheets..." oninput="filterSpriteSheets()" />
</div>
</div> </div>
<div id="spriteRows" class="space-y-2">
@for (var i = 0; i < Model.SpriteRows.Count; i++)
{
var row = Model.SpriteRows[i];
<div class="grid grid-cols-1 md:grid-cols-12 gap-2 sprite-row">
<select name="sprite_key[]" class="input md:col-span-2">
@foreach (var key in new[] { "idle_front", "idle_back", "idle_left", "idle_right", "run_front", "run_back", "run_left", "run_right", "attack_front", "attack_back", "death" })
{
<option value="@key" selected="@(row.Key == key)">@key</option>
}
</select>
<select name="sprite_sheet_id[]" class="input md:col-span-5 sprite-sheet-select">
<option value="">Select sheet...</option>
@foreach (var s in Model.AllSpriteSheets)
{
<option value="@s.Id" selected="@(row.SheetId == s.Id)" data-search="@($"{s.Name} {s.CdnPath}".ToLowerInvariant())">@s.Name (@s.CdnPath)</option>
}
</select>
<input type="number" name="sprite_frames[]" value="@row.Frames" class="input md:col-span-2" min="1" placeholder="Frames" />
<label class="md:col-span-2 flex items-center gap-2 text-sm text-gray-300">
<input type="checkbox" name="sprite_loop[]" value="@i" checked="@row.Loop" class="rounded border-gray-600 bg-gray-800" />
Loop
</label>
<button type="button" class="btn btn-danger md:col-span-1" onclick="this.closest('.sprite-row').remove()">X</button>
</div>
}
</div>
<button type="button" class="btn btn-secondary" onclick="addSpriteRow()">Add Sprite Row</button>
</div> </div>
</div> </div>
@@ -343,8 +349,9 @@
@section Scripts { @section Scripts {
<script> <script>
const selectedAbilitiesSeed = @Html.Raw(selectedAbilitiesJson); const selectedAbilityIds = @Html.Raw(selectedAbilitiesJson);
const spriteSheetCatalog = @Html.Raw(spriteSheetOptions); const selectedAnimations = @Html.Raw(selectedAnimationsJson);
const animationCatalog = @Html.Raw(animationCatalogJson);
const resistanceOptionsHtml = `@Html.Raw(resistanceOptions)`; const resistanceOptionsHtml = `@Html.Raw(resistanceOptions)`;
const abilityById = { const abilityById = {
@@ -357,7 +364,7 @@
function renderSelectedAbilities() { function renderSelectedAbilities() {
const container = document.getElementById('selectedAbilities'); const container = document.getElementById('selectedAbilities');
container.innerHTML = ''; container.innerHTML = '';
selectedAbilitiesSeed.forEach(id => { selectedAbilityIds.forEach(id => {
const row = document.createElement('div'); const row = document.createElement('div');
row.className = 'flex items-center justify-between bg-gray-800 border border-gray-700 rounded p-2'; row.className = 'flex items-center justify-between bg-gray-800 border border-gray-700 rounded p-2';
const label = abilityById[id] || ('Ability #' + id); const label = abilityById[id] || ('Ability #' + id);
@@ -367,9 +374,9 @@
} }
function removeAbility(id) { function removeAbility(id) {
const idx = selectedAbilitiesSeed.indexOf(id); const idx = selectedAbilityIds.indexOf(id);
if (idx >= 0) { if (idx >= 0) {
selectedAbilitiesSeed.splice(idx, 1); selectedAbilityIds.splice(idx, 1);
renderSelectedAbilities(); renderSelectedAbilities();
} }
} }
@@ -378,8 +385,8 @@
const select = document.getElementById('abilityPicker'); const select = document.getElementById('abilityPicker');
const id = parseInt(select.value || '0', 10); const id = parseInt(select.value || '0', 10);
if (!id) return; if (!id) return;
if (!selectedAbilitiesSeed.includes(id)) { if (!selectedAbilityIds.includes(id)) {
selectedAbilitiesSeed.push(id); selectedAbilityIds.push(id);
renderSelectedAbilities(); renderSelectedAbilities();
} }
} }
@@ -412,65 +419,132 @@
<span class="text-gray-400">%</span> <span class="text-gray-400">%</span>
</div> </div>
</div> </div>
<button type="button" onclick="this.closest('.resistance-row').remove()" class="p-2 text-red-400 hover:text-red-300">Remove</button> <button type="button" onclick="this.closest('.resistance-row').remove()" class="btn btn-danger btn-sm">Remove</button>
`; `;
document.getElementById('resistancesList').appendChild(row); document.getElementById('resistancesList').appendChild(row);
typeSelect.value = ''; typeSelect.value = '';
valueInput.value = '50'; valueInput.value = '50';
} }
function filterSpriteSheets() { function getAnimationById(id) {
const term = (document.getElementById('spriteSheetSearch').value || '').toLowerCase(); return animationCatalog.find(a => a.id === id) || null;
const selects = document.querySelectorAll('.sprite-sheet-select'); }
selects.forEach(select => {
for (let i = 0; i < select.options.length; i++) { function showAddAnimationModal() {
const opt = select.options[i]; document.getElementById('addAnimationModal').classList.remove('hidden');
const text = (opt.dataset.search || opt.text || '').toLowerCase(); document.getElementById('addAnimationModal').classList.add('flex');
if (opt.value === '') { }
opt.style.display = '';
} else { function closeAddAnimationModal() {
opt.style.display = term === '' || text.includes(term) ? '' : 'none'; document.getElementById('addAnimationModal').classList.add('hidden');
} document.getElementById('addAnimationModal').classList.remove('flex');
document.getElementById('animationSearch').value = '';
filterAnimations();
}
function filterAnimations() {
const term = (document.getElementById('animationSearch').value || '').toLowerCase();
const select = document.getElementById('animationSelect');
for (let i = 0; i < select.options.length; i++) {
const opt = select.options[i];
const text = (opt.dataset.search || opt.text || '').toLowerCase();
opt.style.display = term === '' || text.includes(term) ? '' : 'none';
}
}
function addAnimationFromModal() {
const select = document.getElementById('animationSelect');
const id = parseInt(select.value || '0', 10);
if (!id) return;
const override = (document.getElementById('animationOverrideKey').value || '').trim();
const exists = selectedAnimations.some(a => a.animationDefinitionId === id && (a.overrideKey || '') === override);
if (exists) return;
selectedAnimations.push({
animationDefinitionId: id,
overrideKey: override || null,
isEnabled: true
});
document.getElementById('animationOverrideKey').value = '';
closeAddAnimationModal();
renderAnimationTable();
}
function removeAnimation(idx) {
selectedAnimations.splice(idx, 1);
renderAnimationTable();
}
function toggleAnimation(idx) {
selectedAnimations[idx].isEnabled = !selectedAnimations[idx].isEnabled;
renderAnimationTable();
}
function renderAnimationTable() {
const body = document.getElementById('npcAnimationTableBody');
const hiddenInputs = document.getElementById('animationHiddenInputs');
body.innerHTML = '';
hiddenInputs.innerHTML = '';
if (selectedAnimations.length === 0) {
const tr = document.createElement('tr');
tr.innerHTML = '<td class="table-cell text-center text-gray-500 py-8" colspan="8">No animations assigned. Add animations from the selector.</td>';
body.appendChild(tr);
return;
}
selectedAnimations.forEach((row, idx) => {
const anim = getAnimationById(row.animationDefinitionId);
if (!anim) return;
const key = row.overrideKey && row.overrideKey.length ? row.overrideKey : anim.key;
const options = [anim.loop ? 'Loop' : null, anim.flipX ? 'FlipX' : null, anim.flipY ? 'FlipY' : null].filter(Boolean).join(', ');
const tr = document.createElement('tr');
tr.className = 'hover:bg-gray-700/30';
tr.innerHTML = `
<td class="table-cell text-white font-mono">${anim.key}</td>
<td class="table-cell text-gray-300 text-xs">${anim.sheetName}</td>
<td class="table-cell text-gray-300 font-mono text-xs">${anim.frameSequence}</td>
<td class="table-cell text-gray-300">${anim.fps}</td>
<td class="table-cell text-gray-400 text-xs">${options || '-'}</td>
<td class="table-cell text-gray-300 font-mono text-xs">
<input type="text" class="input" value="${row.overrideKey || ''}" placeholder="-" onchange="updateOverride(${idx}, this.value)" />
</td>
<td class="table-cell">
<span class="${row.isEnabled ? 'text-green-400' : 'text-gray-500'} text-xs">${row.isEnabled ? 'Active' : 'Disabled'}</span>
</td>
<td class="table-cell">
<div class="flex gap-2">
<button type="button" class="btn btn-secondary btn-sm" onclick="toggleAnimation(${idx})">${row.isEnabled ? 'Disable' : 'Enable'}</button>
<button type="button" class="btn btn-danger btn-sm" onclick="removeAnimation(${idx})">Remove</button>
</div>
</td>
`;
body.appendChild(tr);
hiddenInputs.insertAdjacentHTML('beforeend', `<input type="hidden" name="npc_anim_id[]" value="${row.animationDefinitionId}">`);
hiddenInputs.insertAdjacentHTML('beforeend', `<input type="hidden" name="npc_anim_override_key[]" value="${(row.overrideKey || '').replace(/"/g, '&quot;')}">`);
if (row.isEnabled) {
hiddenInputs.insertAdjacentHTML('beforeend', `<input type="hidden" name="npc_anim_enabled[]" value="${idx}">`);
} }
}); });
} }
function addSpriteRow() { function updateOverride(idx, value) {
const idx = document.querySelectorAll('#spriteRows .sprite-row').length; selectedAnimations[idx].overrideKey = (value || '').trim() || null;
const row = document.createElement('div'); renderAnimationTable();
row.className = 'grid grid-cols-1 md:grid-cols-12 gap-2 sprite-row';
const sheetOptions = spriteSheetCatalog
.map(s => `<option value="${s.id}" data-search="${(s.name + ' ' + s.cdnPath).toLowerCase()}">${s.name} (${s.cdnPath})</option>`)
.join('');
row.innerHTML = `
<select name="sprite_key[]" class="input md:col-span-2">
<option value="idle_front">idle_front</option>
<option value="idle_back">idle_back</option>
<option value="idle_left">idle_left</option>
<option value="idle_right">idle_right</option>
<option value="run_front">run_front</option>
<option value="run_back">run_back</option>
<option value="run_left">run_left</option>
<option value="run_right">run_right</option>
<option value="attack_front">attack_front</option>
<option value="attack_back">attack_back</option>
<option value="death">death</option>
</select>
<select name="sprite_sheet_id[]" class="input md:col-span-5 sprite-sheet-select"><option value="">Select sheet...</option>${sheetOptions}</select>
<input type="number" name="sprite_frames[]" value="8" class="input md:col-span-2" min="1" placeholder="Frames" />
<label class="md:col-span-2 flex items-center gap-2 text-sm text-gray-300">
<input type="checkbox" name="sprite_loop[]" value="${idx}" checked class="rounded border-gray-600 bg-gray-800" />
Loop
</label>
<button type="button" class="btn btn-danger md:col-span-1" onclick="this.closest('.sprite-row').remove()">X</button>
`;
document.getElementById('spriteRows').appendChild(row);
filterSpriteSheets();
} }
document.addEventListener('keydown', e => {
if (e.key === 'Escape') {
closeAddAnimationModal();
}
});
renderSelectedAbilities(); renderSelectedAbilities();
renderAnimationTable();
</script> </script>
} }
+165 -96
View File
@@ -24,36 +24,19 @@ public class EditModel : AdminPageModel
public List<DungeonNpcDialogTree> DialogTrees { get; set; } = new(); public List<DungeonNpcDialogTree> DialogTrees { get; set; } = new();
public List<DamageResistanceType> ResistanceTypes { get; set; } = new(); public List<DamageResistanceType> ResistanceTypes { get; set; } = new();
public List<MobAbilityDefinition> AllAbilities { get; set; } = new(); public List<MobAbilityDefinition> AllAbilities { get; set; } = new();
public List<MobSpriteSheet> AllSpriteSheets { get; set; } = new(); public List<MobAnimationDefinition> AllAnimations { get; set; } = new();
public List<int> SelectedAbilityIds { get; set; } = new(); public List<int> SelectedAbilityIds { get; set; } = new();
public List<NpcSpriteRow> SpriteRows { get; set; } = new(); public List<NpcAnimationSelection> SelectedAnimations { get; set; } = new();
public NpcSpriteConfig SpriteConfig { get; set; } = new();
public bool IsNew => Npc.Id == 0; public bool IsNew => Npc.Id == 0;
public string? Message { get; set; } public string? Message { get; set; }
public bool IsError { get; set; } public bool IsError { get; set; }
public class NpcSpriteRow public class NpcAnimationSelection
{ {
public string Key { get; set; } = ""; public int AnimationDefinitionId { get; set; }
public int? SheetId { get; set; } public string? OverrideKey { get; set; }
public int Frames { get; set; } = 8; public bool IsEnabled { get; set; } = true;
public bool Loop { get; set; } = true;
}
public class NpcSpriteConfig
{
public Dictionary<string, string> Sprites { get; set; } = new();
public Dictionary<string, SpriteAnimation> Animations { get; set; } = new();
public int FrameWidth { get; set; } = 64;
public int FrameHeight { get; set; } = 64;
public int Fps { get; set; } = 8;
public class SpriteAnimation
{
public int Frames { get; set; } = 8;
public bool Loop { get; set; } = true;
}
} }
public async Task OnGetAsync(int? id) public async Task OnGetAsync(int? id)
@@ -116,9 +99,10 @@ public class EditModel : AdminPageModel
Npc.Key = (Npc.Key ?? "").Trim(); Npc.Key = (Npc.Key ?? "").Trim();
Npc.Description ??= ""; Npc.Description ??= "";
Npc.TintColor = string.IsNullOrWhiteSpace(Npc.TintColor) ? "#ffffff" : Npc.TintColor.Trim(); Npc.TintColor = string.IsNullOrWhiteSpace(Npc.TintColor) ? "#ffffff" : Npc.TintColor.Trim();
ParseAndSetResistancesFromForm(); ParseAndSetResistancesFromForm();
ParseAndSetAbilityIdsFromForm(); ParseAndSetAbilityIdsFromForm();
ParseAndSetSpriteConfigFromForm(); ParseAndSetAnimationsFromForm();
if (string.IsNullOrWhiteSpace(Npc.Name)) if (string.IsNullOrWhiteSpace(Npc.Name))
{ {
@@ -130,9 +114,7 @@ public class EditModel : AdminPageModel
if (string.IsNullOrWhiteSpace(Npc.Key)) if (string.IsNullOrWhiteSpace(Npc.Key))
{ {
Npc.Key = Npc.Name Npc.Key = Npc.Name.ToLowerInvariant().Replace(" ", "_");
.ToLowerInvariant()
.Replace(" ", "_");
} }
try try
@@ -228,9 +210,12 @@ public class EditModel : AdminPageModel
.OrderBy(a => a.Name) .OrderBy(a => a.Name)
.ToListAsync(); .ToListAsync();
AllSpriteSheets = await _db.MobSpriteSheets AllAnimations = await _db.MobAnimationDefinitions
.Where(s => s.IsEnabled) .Include(a => a.SpriteSheet)
.OrderBy(s => s.Name) .Where(a => a.IsEnabled)
.Where(a => a.SpriteSheet != null && a.SpriteSheet.IsEnabled)
.OrderBy(a => a.SpriteSheet!.Name)
.ThenBy(a => a.Key)
.ToListAsync(); .ToListAsync();
} }
@@ -256,42 +241,81 @@ public class EditModel : AdminPageModel
Npc.AbilityDefinitionIdsJson = "[]"; Npc.AbilityDefinitionIdsJson = "[]";
} }
SelectedAnimations = ParseAnimationsFromSpriteConfig(Npc.SpriteConfigJson);
}
private List<NpcAnimationSelection> ParseAnimationsFromSpriteConfig(string? spriteConfigJson)
{
var selected = new List<NpcAnimationSelection>();
if (string.IsNullOrWhiteSpace(spriteConfigJson)) return selected;
try try
{ {
SpriteConfig = string.IsNullOrWhiteSpace(Npc.SpriteConfigJson) using var doc = JsonDocument.Parse(spriteConfigJson);
? new NpcSpriteConfig() var root = doc.RootElement;
: (JsonSerializer.Deserialize<NpcSpriteConfig>(Npc.SpriteConfigJson!, new JsonSerializerOptions
if (!root.TryGetProperty("sheets", out var sheetsElem) || !root.TryGetProperty("animations", out var animationsElem))
return selected;
foreach (var animProp in animationsElem.EnumerateObject())
{
var animKey = animProp.Name;
var animObj = animProp.Value;
if (!animObj.TryGetProperty("sheet", out var sheetRefElem)) continue;
var sheetRef = sheetRefElem.GetString();
if (string.IsNullOrWhiteSpace(sheetRef)) continue;
if (!sheetsElem.TryGetProperty(sheetRef, out var sheetObj)) continue;
if (!sheetObj.TryGetProperty("path", out var pathElem)) continue;
var path = pathElem.GetString();
if (string.IsNullOrWhiteSpace(path)) continue;
var frames = animObj.TryGetProperty("frames", out var framesElem)
? framesElem.EnumerateArray().Select(x => x.GetInt32()).ToArray()
: Array.Empty<int>();
var fps = animObj.TryGetProperty("fps", out var fpsElem) ? fpsElem.GetSingle() : 8f;
var loop = animObj.TryGetProperty("loop", out var loopElem) && loopElem.GetBoolean();
var flipX = animObj.TryGetProperty("flipX", out var flipXElem) && flipXElem.GetBoolean();
var flipY = animObj.TryGetProperty("flipY", out var flipYElem) && flipYElem.GetBoolean();
var match = AllAnimations.FirstOrDefault(a =>
{ {
PropertyNameCaseInsensitive = true var sheet = a.SpriteSheet;
}) ?? new NpcSpriteConfig()); if (sheet == null) return false;
if (!string.Equals(sheet.CdnPath, path, StringComparison.OrdinalIgnoreCase)) return false;
if (Math.Abs(a.Fps - fps) > 0.01f) return false;
if (a.Loop != loop || a.FlipX != flipX || a.FlipY != flipY) return false;
var aFrames = ParseFrameSequence(a.FrameSequence);
return aFrames.SequenceEqual(frames);
});
if (match == null)
{
match = AllAnimations.FirstOrDefault(a =>
a.SpriteSheet != null &&
string.Equals(a.Key, animKey, StringComparison.OrdinalIgnoreCase) &&
string.Equals(a.SpriteSheet.CdnPath, path, StringComparison.OrdinalIgnoreCase));
}
if (match != null)
{
selected.Add(new NpcAnimationSelection
{
AnimationDefinitionId = match.Id,
OverrideKey = string.Equals(animKey, match.Key, StringComparison.OrdinalIgnoreCase) ? null : animKey,
IsEnabled = true
});
}
}
} }
catch catch
{ {
SpriteConfig = new NpcSpriteConfig(); // Keep empty if invalid JSON
} }
SpriteRows = new List<NpcSpriteRow>(); return selected
foreach (var kv in SpriteConfig.Sprites) .GroupBy(x => new { x.AnimationDefinitionId, Key = (x.OverrideKey ?? "").Trim().ToLowerInvariant() })
{ .Select(g => g.First())
var frames = 8; .ToList();
var loop = true;
if (SpriteConfig.Animations.TryGetValue(kv.Key, out var anim))
{
frames = anim.Frames;
loop = anim.Loop;
}
var matchingSheet = AllSpriteSheets.FirstOrDefault(s =>
string.Equals(s.CdnPath, kv.Value, StringComparison.OrdinalIgnoreCase));
SpriteRows.Add(new NpcSpriteRow
{
Key = kv.Key,
SheetId = matchingSheet?.Id,
Frames = frames,
Loop = loop
});
}
} }
private void ParseAndSetResistancesFromForm() private void ParseAndSetResistancesFromForm()
@@ -323,56 +347,101 @@ public class EditModel : AdminPageModel
Npc.AbilityDefinitionIdsJson = JsonSerializer.Serialize(list); Npc.AbilityDefinitionIdsJson = JsonSerializer.Serialize(list);
} }
private void ParseAndSetSpriteConfigFromForm() private void ParseAndSetAnimationsFromForm()
{ {
var spriteKeys = Request.Form["sprite_key[]"].ToArray(); var ids = Request.Form["npc_anim_id[]"].ToArray();
var spriteSheetIds = Request.Form["sprite_sheet_id[]"].ToArray(); var overrides = Request.Form["npc_anim_override_key[]"].ToArray();
var spriteFrames = Request.Form["sprite_frames[]"].ToArray(); var enabledValues = Request.Form["npc_anim_enabled[]"].ToHashSet(StringComparer.OrdinalIgnoreCase);
var spriteLoops = Request.Form["sprite_loop[]"].ToArray();
var config = new NpcSpriteConfig(); var selected = new List<NpcAnimationSelection>();
if (int.TryParse(Request.Form["sprite_frameWidth"], out var fw)) config.FrameWidth = fw; for (var i = 0; i < ids.Length; i++)
if (int.TryParse(Request.Form["sprite_frameHeight"], out var fh)) config.FrameHeight = fh;
if (int.TryParse(Request.Form["sprite_fps"], out var fps)) config.Fps = fps;
for (var i = 0; i < spriteKeys.Length && i < spriteSheetIds.Length; i++)
{ {
var key = (spriteKeys[i] ?? "").Trim(); if (!int.TryParse(ids[i], out var animId) || animId <= 0) continue;
if (string.IsNullOrWhiteSpace(key)) continue; var isEnabled = enabledValues.Contains(i.ToString());
if (!int.TryParse(spriteSheetIds[i], out var sheetId)) continue; var ov = i < overrides.Length ? overrides[i]?.Trim() : null;
var sheet = AllSpriteSheets.FirstOrDefault(s => s.Id == sheetId); if (string.IsNullOrWhiteSpace(ov)) ov = null;
if (sheet == null) continue;
var frames = 8; selected.Add(new NpcAnimationSelection
if (i < spriteFrames.Length && int.TryParse(spriteFrames[i], out var rowFrames))
{ {
frames = Math.Max(1, rowFrames); AnimationDefinitionId = animId,
} OverrideKey = ov,
IsEnabled = isEnabled
var loop = spriteLoops.Contains(i.ToString()); });
config.Sprites[key] = sheet.CdnPath;
config.Animations[key] = new NpcSpriteConfig.SpriteAnimation
{
Frames = frames,
Loop = loop
};
} }
if (config.Sprites.Count == 0) selected = selected
.GroupBy(x => new { x.AnimationDefinitionId, Key = (x.OverrideKey ?? "").Trim().ToLowerInvariant() })
.Select(g => g.First())
.ToList();
SelectedAnimations = selected;
var enabled = selected.Where(s => s.IsEnabled).ToList();
if (enabled.Count == 0)
{ {
SpriteConfig = new NpcSpriteConfig();
SpriteRows = new List<NpcSpriteRow>();
Npc.SpriteConfigJson = null; Npc.SpriteConfigJson = null;
return; return;
} }
SpriteConfig = config; var byId = AllAnimations.Where(a => a.SpriteSheet != null).ToDictionary(a => a.Id, a => a);
Npc.SpriteConfigJson = JsonSerializer.Serialize(config, new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});
// rebuild display rows for round-trip on validation failure var sheets = new Dictionary<string, object>();
ParseNpcJsonFields(); var sheetKeyById = new Dictionary<int, string>();
var animations = new Dictionary<string, object>();
foreach (var sel in enabled)
{
if (!byId.TryGetValue(sel.AnimationDefinitionId, out var anim)) continue;
var sheet = anim.SpriteSheet;
if (sheet == null) continue;
if (!sheetKeyById.TryGetValue(sheet.Id, out var sheetKey))
{
sheetKey = $"sheet_{sheet.Id}";
sheetKeyById[sheet.Id] = sheetKey;
sheets[sheetKey] = new
{
path = sheet.CdnPath,
width = sheet.SheetWidth,
height = sheet.SheetHeight,
frameWidth = sheet.FrameWidth,
frameHeight = sheet.FrameHeight
};
}
var key = !string.IsNullOrWhiteSpace(sel.OverrideKey) ? sel.OverrideKey! : anim.Key;
animations[key] = new
{
sheet = sheetKey,
frames = ParseFrameSequence(anim.FrameSequence),
fps = anim.Fps,
loop = anim.Loop,
flipX = anim.FlipX,
flipY = anim.FlipY
};
}
if (animations.Count == 0)
{
Npc.SpriteConfigJson = null;
return;
}
Npc.SpriteConfigJson = JsonSerializer.Serialize(new
{
sheets,
animations
});
}
private static int[] ParseFrameSequence(string frameSequence)
{
if (string.IsNullOrWhiteSpace(frameSequence))
return new[] { 0 };
return frameSequence
.Split(',')
.Select(s => int.TryParse(s.Trim(), out var n) ? n : 0)
.ToArray();
} }
} }