ModernUO/Projects/UOContent/Engines/Spawners/SpawnerGump.cs
Kamron Batman a52ce6ef70
refactor(spawners): subclass-owned entries, lifecycle hooks, per-entry Disabled flag (#2621)
## Summary

Moves spawner entry storage out of the abstract `BaseSpawner` into the concrete owner, so a spawner subclass can store its own entry type while every stock code path keeps working. Motivation: an out-of-tree spawner (ModernSpawner) needs `ModernSpawnerEntry : SpawnerEntry` with extra fields; today `BaseSpawner` owns `List<SpawnerEntry>` and a family of non-virtual members, and the serialization generator constructs list elements from the declared element type, so storage has to live in the class that declares the concrete list.

### What changed

- **`BaseSpawner` v13** no longer owns `_entries`. It reads entries through an abstract view and mutates them through an owner contract (`BaseSpawner.Entries.cs`):
  `Entries` (`IReadOnlyList<SpawnerEntry>`, `[IgnoreDupe]`), `EntrySpan` (`ReadOnlySpan<SpawnerEntry>` for hot loops), `CreateEntry`, `AddEntryCore`, `RemoveEntryCore`, `ClearEntriesCore`, `AdoptEntries`, `CloneEntry`, `TransferSpawned`, plus public `RemoveAllEntries()`, `CopyEntriesTo(target)` and protected `RebuildSpawned()`. Every loop inside `BaseSpawner` is an indexed `for` over `EntrySpan`.
- **`Spawner` v2** owns `[SerializedIgnoreDupe] List<SpawnerEntry> _entryList` (generated `EntryList`, protected). `ProximitySpawner`/`RegionSpawner` inherit it unchanged. The `Spawned` rebuild and timer re-arm moved from the base `[AfterDeserialization]` (which runs before derived fields are read) into `Spawner`'s.
- **Save migration**: `MigrateFrom(V12Content)` (and the v10/v11/legacy readers) hand the old list to the owner via `AdoptEntries`; `Spawner.MigrateFrom(V1Content)` restores its own fields and leaves the adopted list alone. Three v12/v1/v0 save blobs captured before the change are committed as fixtures and loaded by tests.
- **Lifecycle hooks** (`BaseSpawner.Hooks.cs`, all no-op by default): `OnStarted`, `OnStopped`, `OnBeforeSpawn(entry)` veto, `OnConfigureSpawned(entry, spawned)` before positioning, entry-aware `GetSpawnPosition(entry, spawned, map)`, `OnSpawned(entry, spawned)`, `OnSpawnedDeath(entry, spawned, killer)`. `BaseCreature.OnDeath` calls `NotifySpawnedDeath` before base death (which deletes the mobile and unlinks the spawner). `Start()` and the `NextSpawn` setter share one start core so `OnStarted` fires on both.
- **`SpawnerEntry` v2**: per-entry `Disabled` (XmlSpawner's entry "lock"), stored inverted so the common case writes nothing in binary or JSON; skipped by weighted selection, live spawns untouched; toggle button per row in `SpawnerGump`. `SetParent` is public and `Parent` is protected so an out-of-tree entry subclass can adopt and dirty-track.
- **DTO**: `SpawnerDto` loses `Entries`; each concrete record declares its own `entries` at the same JSON order, so `Distribution/Data/Spawns/**` is byte-identical. Import adopts the deserialized entry objects instead of recreating them through `AddEntry`, which is what preserves subtype fields (and `disabled`).

### Breaking changes and behaviour changes

- **API:** `BaseSpawner.Entries` is `IReadOnlyList<SpawnerEntry>` instead of `List<SpawnerEntry>`. The generated `AddToEntries`/`RemoveFromEntries`/`InsertIntoEntries`/`RemoveFromEntriesAt`/`ClearEntries` helpers on `BaseSpawner` are gone; use `AddEntry`/`RemoveEntry`/`RemoveAllEntries`/`CopyEntriesTo`. `RemoveAllEntries()` deletes the entries' live spawns as well as the entries (the old generated `ClearEntries()` only cleared the list), which is why it has a new name rather than the old one.
- `SpawnerControllerGump` "copy entries" now goes through `CopyEntriesTo`, which deletes the target's live spawns (previously it cleared the list and left the spawns orphaned) and is a no-op when source == target (previously that wiped the source).
- `RemoveEntry` with an entry the spawner does not own is now a no-op (previously it deleted that entry's spawns).
- `Respawn()` honours `Disabled` because it calls `Spawn()`; `Spawn(int index)`, `RemoveSpawn`, and `RemoveSpawns` ignore it.
- Copying entries between spawners no longer forces a 1-second first spawn; the target re-arms on its normal delay.
- Subclasses that own a different entry list than `Spawner`'s must call `RebuildSpawned()` from their own `[AfterDeserialization]` (`Spawner`'s call runs before their list is read) and, when converting adopted entries into their own type, carry live spawns across with `TransferSpawned`. The in-repo test subclass demonstrates both.

### Performance

Manual harness (`Benchmark_SpawnPath_Manual`, skipped by default): 100k calls, entries all full so `Spawn()` does selection only.

| Path | Before (4bad0cc9e) | After |
|---|---|---|
| `Spawn()` 1 entry | 48.7 ns | 53.2 ns (within run-to-run noise) |
| `Spawn()` 10 entries | 243.7 ns | 153.1 ns |
| `Spawn()` 50 entries | 1077.6 ns | 645.1 ns |
| `Remove()` 10 entries | 139.6 ns | 83.6 ns |

Hooks are no-ops for stock spawners; `OnMovement` is untouched.

### Tests

- `SpawnerEntryOwnershipTests` (add/remove/clear, start after stop, dupe, copy, self-copy, foreign-entry removal, Disabled binary/JSON)
- `SpawnerHookTests` (hook order for mobiles and items, veto, death notification, `NextSpawn` start, a subclass with its own `List<TestEntry>` round-tripping and duping)
- `SpawnerSaveMigrationTests` (v12 fixtures through `Spawner`, `ProximitySpawner`, `RegionSpawner`; new-format byte-identical round trip with a live spawn reference)
- `SpawnerDtoEntryTests` (compact JSON position of `entries`, `disabled` only when set, import adopts the deserialized objects)
- Existing DTO/JSON/spawn-data tests unchanged. UOContent.Tests 801 passed, Server.Tests 869 passed. Migration schemas regenerated (`BaseSpawner.v13`, `Spawner.v2`, `SpawnerEntry.v2`).

Coverage caveats, stated plainly: v10, v11 and the pre-codegen legacy reader could not be captured as fixtures by the current code; each changed only `_entries = …` → `AdoptEntries(…)` into the same sink the v12 fixtures exercise, and is covered by review. The captured v12 fixtures carry no live spawns, so re-linking live `ISpawnable` references is proven by the new-format round trip, not by a legacy blob. The `SpawnerGump` toggle layout could not be checked in a client; the delete button moved from x=38 to x=46 to make room.
2026-09-11 17:41:08 -07:00

475 lines
15 KiB
C#

using System;
using Server.Collections;
using Server.Gumps;
using Server.Network;
namespace Server.Engines.Spawners;
public class SpawnerGump : Gump
{
private readonly BaseSpawner _spawner;
private SpawnerEntry _entry;
private int _page;
public SpawnerGump(BaseSpawner spawner, SpawnerEntry focusentry = null, int page = 0) : base(50, 50)
{
_spawner = spawner;
_entry = focusentry;
_page = page;
AddPage(0);
AddBackground(0, 0, 346, 400 + (_entry != null ? 44 : 0), 5054);
AddAlphaRegion(0, 0, 346, 400 + (_entry != null ? 44 : 0));
AddHtml(240, 1, 250, 20, "<BASEFONT COLOR=#F4F4F4>#</BASEFONT>");
AddHtml(271, 1, 250, 20, "<BASEFONT COLOR=#F4F4F4>Max</BASEFONT>");
AddHtml(311, 1, 250, 20, "<BASEFONT COLOR=#F4F4F4>Prb</BASEFONT>");
// AddLabel( 95, 1, 0, "Creatures List" );
var offset = 0;
for (var i = 0; i < 13; i++)
{
var textIndex = i * 5;
var entryIndex = _page * 13 + i;
SpawnerEntry entry = null;
if (entryIndex < spawner.Entries.Count)
{
entry = _spawner.Entries[entryIndex];
}
if (entry == null || _entry != entry)
{
AddButton(
5,
22 * i + 21 + offset,
entry != null ? 0xFBA : 0xFA5,
entry != null ? 0xFBC : 0xFA7,
GetButtonID(2, i * 2)
); // Expand
}
else
{
AddButton(
5,
22 * i + 21 + offset,
0xFBB,
0xFBC,
GetButtonID(2, i * 2)
); // Unexpand
}
AddButton(46, 22 * i + 21 + offset, 0xFA2, 0xFA4, GetButtonID(2, 1 + i * 2)); // Delete
if (entry != null)
{
AddButton(
22,
22 * i + 21 + offset,
entry.Disabled ? 0xD2 : 0xD3,
entry.Disabled ? 0xD3 : 0xD2,
GetButtonID(3, i)
); // Enabled toggle (checked = enabled)
}
AddImageTiled(71, 22 * i + 20 + offset, 161, 23, 0xA40); // creature text box
AddImageTiled(72, 22 * i + 21 + offset, 159, 21, 0xBBC); // creature text box
AddImageTiled(235, 22 * i + 20 + offset, 35, 23, 0xA40); // count html label
AddImageTiled(236, 22 * i + 21 + offset, 33, 21, 0xE14); // count html label
AddImageTiled(267, 22 * i + 20 + offset, 35, 23, 0xA40); // maxcount text box
AddImageTiled(268, 22 * i + 21 + offset, 33, 21, 0xBBC); // maxcount text box
AddImageTiled(305, 22 * i + 20 + offset, 35, 23, 0xA40); // probability text box
AddImageTiled(306, 22 * i + 21 + offset, 33, 21, 0xBBC); // probability text box
string name;
string probability;
string maxCount;
var flags = EntryFlags.None;
if (entry != null)
{
name = entry.SpawnedName;
probability = entry.SpawnedProbability.ToString();
maxCount = entry.SpawnedMaxCount.ToString();
flags = entry.Valid;
var count = spawner.CountSpawns(entry);
AddHtml(235, 22 * i + 20 + offset + 1, 35, 15, $"<BASEFONT COLOR={GetCountColor(count, entry.SpawnedMaxCount)}><div align=RIGHT>{count}<BASEFONT COLOR=#F4F4F4>/</BASEFONT></div></BASEFONT>");
}
else
{
name = "";
probability = "";
maxCount = "";
}
// creature
AddTextEntry(
75,
22 * i + 21 + offset,
156,
21,
(flags & EntryFlags.InvalidType) != 0 ? 33 : entry?.Disabled == true ? 0x3B2 : 0,
textIndex,
name
);
AddTextEntry(270, 22 * i + 21 + offset, 30, 21, 0, textIndex + 1, maxCount); // max count
AddTextEntry(308, 22 * i + 21 + offset, 30, 21, 0, textIndex + 2, probability); // probability
if (entry != null && _entry == entry)
{
AddLabel(5, 22 * i + 42, 0x384, "Params");
AddImageTiled(55, 22 * i + 42, 253, 23, 0xA40); // Parameters
AddImageTiled(56, 22 * i + 43, 251, 21, 0xBBC); // Parameters
AddLabel(5, 22 * i + 64, 0x384, "Props");
AddImageTiled(55, 22 * i + 64, 253, 23, 0xA40); // Properties
AddImageTiled(56, 22 * i + 65, 251, 21, 0xBBC); // Properties
AddTextEntry(
59,
22 * i + 42,
248,
21,
(flags & EntryFlags.InvalidParams) != 0 ? 33 : 0,
textIndex + 3,
entry.Parameters
); // parameters
AddTextEntry(
59,
22 * i + 62,
248,
21,
(flags & EntryFlags.InvalidProps) != 0 ? 33 : 0,
textIndex + 4,
entry.Properties
); // properties
offset += 44;
}
}
if (spawner.Running)
{
AddButton(5, 312 + offset, 0x2A4E, 0x2A3A, GetButtonID(1, 6));
AddLabel(38, 317 + offset, 0x384, "On");
}
else
{
AddButton(5, 312 + offset, 0x2A62, 0x2A3A, GetButtonID(1, 7));
AddLabel(38, 317 + offset, 0x384, "Off");
}
var totalSpawned = 0;
var totalWeight = 0;
for (var i = 0; i < _spawner.Entries.Count; i++)
{
var spawnerEntry = _spawner.Entries[i];
totalSpawned += spawner.CountSpawns(spawnerEntry);
totalWeight += spawnerEntry.SpawnedProbability;
}
AddHtml(232, 308 + offset, 35, 20, Html.Center($"{totalSpawned}", 0xF4F4F4));
AddHtml(270, 308 + offset, 35, 20, Html.Center($"{totalWeight}", 0xF4F4F4));
AddHtml(5, 1, 161, 20, $"<BASEFONT COLOR=#FFEA00>{spawner.Name}</BASEFONT><BASEFONT COLOR={GetCountColor(totalSpawned, spawner.Count)}> ({totalSpawned}/{spawner.Count})</BASEFONT>");
AddButton(5, 347 + offset, 0xFAB, 0xFAD, GetButtonID(1, 2));
AddLabel(38, 347 + offset, 0x384, "Props");
AddButton(5, 369 + offset, 0xFAE, 0xFAF, GetButtonID(1, 8));
AddLabel(38, 369 + offset, 0x384, "Goto");
AddButton(90, 325 + offset, 0xFA2, 0xFA3, GetButtonID(1, 9));
AddLabel(123, 325 + offset, 0x384, "Reset");
AddButton(90, 347 + offset, 0xFB4, 0xFB6, GetButtonID(1, 3));
AddLabel(123, 347 + offset, 0x384, "Bring Home");
AddButton(90, 369 + offset, 0xFA8, 0xFAA, GetButtonID(1, 4));
AddLabel(123, 369 + offset, 0x384, "Total Respawn");
AddButton(260, 347 + offset, 0xFB7, 0xFB9, GetButtonID(1, 5));
AddLabel(293, 347 + offset, 0x384, "Save");
AddButton(260, 369 + offset, 0xFB1, 0xFB3, 0);
AddLabel(293, 369 + offset, 0x384, "Cancel");
if (_page > 0)
{
AddButton(200, 308 + offset, 0x15E3, 0x15E7, GetButtonID(1, 0));
}
else
{
AddImage(200, 308 + offset, 0x25EA);
}
if ((_page + 1) * 13 <= _spawner.Entries.Count)
{
AddButton(217, 308 + offset, 0x15E1, 0x15E5, GetButtonID(1, 1));
}
else
{
AddImage(217, 308 + offset, 0x25E6);
}
}
public int GetButtonID(int type, int index) => 1 + index * 10 + type;
private static string GetCountColor(int count, int maxCount) =>
((double) count / maxCount) switch
{
<= 0.25 => "#DE3163", // red
<= 0.50 => "#FF7F50", // orange
<= 0.75 => "#DFFF00", // yellow
<= 1 => "#00FF00", // green
_ => "#F4F4F4" // white
};
public void CreateArray(RelayInfo info, Mobile from, BaseSpawner spawner)
{
var ocount = spawner.Entries.Count;
using var queue = PooledRefQueue<SpawnerEntry>.Create();
for (var i = 0; i < 13; i++)
{
var index = i * 5;
var entryindex = _page * 13 + i;
var typeEntry = info.GetTextEntry(index);
var maxSpawns = info.GetTextEntry(index + 1);
var probability = info.GetTextEntry(index + 2);
var customParams = info.GetTextEntry(index + 3);
var customPrompts = info.GetTextEntry(index + 4);
if (typeEntry == null)
{
continue;
}
var str = typeEntry.Trim().ToLower();
if (str.Length > 0)
{
var type = AssemblyHandler.FindTypeByName(str);
if (type == null)
{
from.SendMessage($"{str} is not a valid type name for entry #{i}.");
return;
}
SpawnerEntry entry;
if (entryindex < ocount)
{
entry = spawner.Entries[entryindex];
entry.SpawnedName = str;
if (maxSpawns != null)
{
entry.SpawnedMaxCount = Utility.ToInt32(maxSpawns.AsSpan().Trim());
}
if (probability != null)
{
entry.SpawnedProbability = Utility.ToInt32(probability.AsSpan().Trim());
}
}
else
{
var maxcount = maxSpawns != null ? Utility.ToInt32(maxSpawns.AsSpan().Trim()) : 1;
var probcount = probability != null ? Utility.ToInt32(probability.AsSpan().Trim()) : 100;
entry = spawner.AddEntry(str, probcount, maxcount);
}
if (customParams != null)
{
entry.Parameters = customParams.Trim();
}
if (customPrompts != null)
{
entry.Properties = customPrompts.Trim();
}
}
else if (entryindex < ocount && spawner.Entries[entryindex] != null)
{
queue.Enqueue(spawner.Entries[entryindex]);
}
}
while (queue.Count > 0)
{
spawner.RemoveEntry(queue.Dequeue());
}
if (ocount == 0 && spawner.Entries.Count > 0)
{
spawner.Start();
}
}
public override void OnResponse(NetState state, in RelayInfo info)
{
if (_spawner.Deleted)
{
return;
}
var val = info.ButtonID - 1;
if (val < 0)
{
return;
}
var type = val % 10;
var index = val / 10;
switch (type)
{
case 0: // Cancel
{
return;
}
case 1:
{
switch (index)
{
case 0:
{
if (_spawner.Entries != null && _page > 0)
{
_page--;
_entry = null;
}
break;
}
case 1:
{
if ((_page + 1) * 13 <= _spawner.Entries?.Count)
{
_page++;
_entry = null;
}
break;
}
case 2: // Props
{
state.Mobile.SendGump(new PropertiesGump(state.Mobile, _spawner));
break;
}
case 3: // Bring Home
{
_spawner.BringToHome();
break;
}
case 4: // Complete respawn
{
_spawner.Respawn();
break;
}
case 5: // Save
{
CreateArray(info, state.Mobile, _spawner);
break;
}
case 6: // On button
{
_spawner.Running = false;
break;
}
case 7: // Off button
{
_spawner.Running = true;
break;
}
case 8: // Goto
{
state.Mobile.MoveToWorld(_spawner.Location, _spawner.Map);
break;
}
case 9: // Reset
{
_spawner.Reset();
break;
}
}
break;
}
case 2:
{
var entryIndex = index / 2 + _page * 13;
var buttonType = index % 2;
if (entryIndex >= 0 && entryIndex < _spawner.Entries.Count)
{
var entry = _spawner.Entries[entryIndex];
if (buttonType == 0) // Spawn creature
{
_entry = _entry != entry ? entry : null;
}
else // Remove creatures
{
_spawner.RemoveSpawn(entryIndex);
}
}
CreateArray(info, state.Mobile, _spawner);
break;
}
case 3: // Enable/disable entry
{
var entryIndex = index + _page * 13;
if (entryIndex >= 0 && entryIndex < _spawner.Entries.Count)
{
var entry = _spawner.Entries[entryIndex];
entry.Disabled = !entry.Disabled;
}
CreateArray(info, state.Mobile, _spawner);
break;
}
}
if (_entry != null && HasEntry(_spawner, _entry))
{
state.Mobile.SendGump(new SpawnerGump(_spawner, _entry, _page));
}
else
{
state.Mobile.SendGump(new SpawnerGump(_spawner, null, _page));
}
}
private static bool HasEntry(BaseSpawner spawner, SpawnerEntry entry)
{
var entries = spawner.Entries;
for (var i = 0; i < entries.Count; i++)
{
if (entries[i] == entry)
{
return true;
}
}
return false;
}
}