feat(plugins): MossTank — a self-buffing plugin, and the automation surface it needed

First consumer of acdream's plugin automation surface, and the first slice of
the VTank-class plugin milestone
(docs/research/2026-07-29-vtank-plugin-automation-requirements.md).

MossTank shows a panel with a Buff button; clicking it casts every self-buff
the character is missing, skips what is already in force at an equal or higher
tier, and refreshes what is nearly expired.

The host/plugin line is the load-bearing decision here. The host publishes
spell DATA -- family, tier, difficulty, mana, duration -- plus a cast
primitive with a preflight gate. The plugin owns the POLICY. That is the
architectural conclusion the requirements research reached: VTank's engine
lived in plugin-land, built on Decal's primitives, and baking "best buff for
skill X" into the host would start pulling the engine inward one convenience
at a time.

Why the plan is driven off the spellbook rather than off trained skills, which
is the obvious reading of "buff every trained and specialised skill": the
client cannot honestly make that mapping. The link between a spell and the
stat it modifies arrives from the SERVER in the enchantment message and is
absent from the client's own spell table. What the client does know is which
spells the character has learned -- and a character only learns buffs for the
skills they use, so the spellbook reaches the same set without inventing a
mapping the client has no grounds for.

Surface added, all BCL-only so Plugin.Abstractions keeps its zero project
references:

* ICharacterInfo, ISpellCatalog, IMagicCommands, grouped behind one
  IAutomationSurface so IPluginHost grows by one member rather than three.
* IEvents.Tick. Automation is sequences, not single calls -- a buff pass casts
  several spells and must wait between them. Without a host tick a plugin
  would need its own timer thread re-entering the host off its update thread.
* NoOpAutomationSurface for hosts with no live session, so a plugin keeps one
  code path and checks IsAvailable.

Markup gained <button> and <label>; it previously supported only <meter>, with
a comment promising the rest. Buttons bind onclick to an Action property and
FAIL THE PANEL LOAD if it does not resolve -- a silently dead button is worse
than a panel that refuses to load, because the user clicks and there is
nothing to diagnose. Labels bind through a Func so a status line tracks its
binding instead of freezing at build time.

Enchantment reads use EnchantmentsInEffectSnapshot rather than the raw active
set: retail leaves a weaker same-family enchantment in the registry while a
stronger one is in force, and a plugin asking "am I buffed?" means in force.

BuffPlan is a pure function of (known buffs, active enchantments) precisely so
it can be tested without a session; 9 tests cover tier supersede, the
family-0 no-stack bucket that must not be de-duplicated, expiry refresh, and
plan stability across the rebuilds the tick loop performs.

Solution builds clean; 14,421 tests pass on the standard hermetic lane filter,
0 failures.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Erik 2026-08-20 16:22:28 +02:00
parent 690f21889e
commit 9d1117b923
27 changed files with 1546 additions and 10 deletions

View file

@ -146,4 +146,53 @@
Overwrite="true"
Lines="{ &quot;id&quot;: &quot;acdream.smoke&quot;, &quot;displayName&quot;: &quot;Smoke Plugin&quot;, &quot;version&quot;: &quot;0.1.0&quot;, &quot;entryDll&quot;: &quot;AcDream.Plugins.Smoke.dll&quot;, &quot;apiVersion&quot;: 1 }" />
</Target>
<!-- MossTank ships the same way as the smoke plugin, plus its panel markup:
MossTankPlugin resolves mosstank.xml relative to its own assembly, so the
two files must land in the same plugin directory. -->
<ItemGroup>
<ProjectReference Include="..\AcDream.Plugins.MossTank\AcDream.Plugins.MossTank.csproj">
<ReferenceOutputAssembly>false</ReferenceOutputAssembly>
<SkipGetTargetFrameworkProperties>true</SkipGetTargetFrameworkProperties>
</ProjectReference>
</ItemGroup>
<Target
Name="CopyMossTankPluginToBuildOutput"
AfterTargets="Build"
Condition="'$(IsCrossTargetingBuild)' != 'true'">
<PropertyGroup>
<_MossTankSourceDir>$(MSBuildProjectDirectory)/../AcDream.Plugins.MossTank/bin/$(Configuration)/$(TargetFramework)</_MossTankSourceDir>
<_MossTankSourceDir Condition="'$(RuntimeIdentifier)' != ''">$(_MossTankSourceDir)/$(RuntimeIdentifier)</_MossTankSourceDir>
<_MossTankDestDir>$(OutputPath)plugins/AcDream.Plugins.MossTank</_MossTankDestDir>
</PropertyGroup>
<MakeDir Directories="$(_MossTankDestDir)" />
<Copy
SourceFiles="$(_MossTankSourceDir)/AcDream.Plugins.MossTank.dll;$(_MossTankSourceDir)/mosstank.xml"
DestinationFolder="$(_MossTankDestDir)"
SkipUnchangedFiles="true" />
<WriteLinesToFile
File="$(_MossTankDestDir)/plugin.json"
Overwrite="true"
Lines="{ &quot;id&quot;: &quot;acdream.mosstank&quot;, &quot;displayName&quot;: &quot;MossTank&quot;, &quot;version&quot;: &quot;0.1.0&quot;, &quot;entryDll&quot;: &quot;AcDream.Plugins.MossTank.dll&quot;, &quot;apiVersion&quot;: 1 }" />
</Target>
<Target
Name="CopyMossTankPluginToPublishOutput"
AfterTargets="Publish"
Condition="'$(IsCrossTargetingBuild)' != 'true'">
<PropertyGroup>
<_MossTankPublishSourceDir>$(MSBuildProjectDirectory)/../AcDream.Plugins.MossTank/bin/$(Configuration)/$(TargetFramework)</_MossTankPublishSourceDir>
<_MossTankPublishSourceDir Condition="'$(RuntimeIdentifier)' != ''">$(_MossTankPublishSourceDir)/$(RuntimeIdentifier)</_MossTankPublishSourceDir>
<_MossTankPublishDestDir>$(PublishDir)plugins/AcDream.Plugins.MossTank</_MossTankPublishDestDir>
</PropertyGroup>
<MakeDir Directories="$(_MossTankPublishDestDir)" />
<Copy
SourceFiles="$(_MossTankPublishSourceDir)/AcDream.Plugins.MossTank.dll;$(_MossTankPublishSourceDir)/mosstank.xml"
DestinationFolder="$(_MossTankPublishDestDir)"
SkipUnchangedFiles="true" />
<WriteLinesToFile
File="$(_MossTankPublishDestDir)/plugin.json"
Overwrite="true"
Lines="{ &quot;id&quot;: &quot;acdream.mosstank&quot;, &quot;displayName&quot;: &quot;MossTank&quot;, &quot;version&quot;: &quot;0.1.0&quot;, &quot;entryDll&quot;: &quot;AcDream.Plugins.MossTank.dll&quot;, &quot;apiVersion&quot;: 1 }" />
</Target>
</Project>

View file

@ -0,0 +1,275 @@
using AcDream.Core.Player;
using AcDream.Core.Spells;
using AcDream.Plugin.Abstractions;
using AcDream.Runtime.Gameplay;
namespace AcDream.App.Plugins;
/// <summary>
/// Projects the canonical Runtime gameplay owners into the BCL-only plugin
/// automation surface.
/// </summary>
/// <remarks>
/// <para>
/// Owns nothing: the character state and cast state are borrowed from
/// <c>GameRuntime</c> and rebound per session, matching how every other
/// graphical projection treats Runtime owners. Between sessions the surface
/// reports <see cref="IsAvailable"/> false and every command refuses, rather
/// than throwing at a plugin that ticked one frame late.
/// </para>
/// <para>
/// The two snapshot lists are rebuilt on Spellbook change notifications rather
/// than per read, because a plugin ticking each frame would otherwise force a
/// full spellbook walk 60 times a second for data that changes rarely.
/// </para>
/// </remarks>
internal sealed class AppAutomationSurface
: IAutomationSurface, ICharacterInfo, ISpellCatalog, IMagicCommands, IDisposable
{
private readonly object _gate = new();
private RuntimeCharacterState? _character;
private RuntimeSpellCastState? _cast;
private Spellbook? _spellbook;
private bool _disposed;
private IReadOnlyList<PluginSpellInfo> _knownSelfBuffs = Array.Empty<PluginSpellInfo>();
private IReadOnlyList<PluginActiveEnchantment> _enchantments =
Array.Empty<PluginActiveEnchantment>();
public bool IsAvailable
{
get
{
lock (_gate)
return !_disposed && _character is not null && _cast is not null;
}
}
public ICharacterInfo Character => this;
public ISpellCatalog Spells => this;
public IMagicCommands Magic => this;
/// <summary>Bind the surface to a live session's owners.</summary>
public void Bind(RuntimeCharacterState character, RuntimeSpellCastState cast)
{
ArgumentNullException.ThrowIfNull(character);
ArgumentNullException.ThrowIfNull(cast);
Spellbook spellbook = character.Spellbook;
lock (_gate)
{
if (_disposed)
return;
DetachLocked();
_character = character;
_cast = cast;
_spellbook = spellbook;
spellbook.SpellbookChanged += OnSpellbookChanged;
spellbook.EnchantmentsChanged += OnEnchantmentsChanged;
}
RebuildSpellbook();
RebuildEnchantments();
}
/// <summary>Release the session's owners; reads go inert until the next bind.</summary>
public void Unbind()
{
lock (_gate)
DetachLocked();
_knownSelfBuffs = Array.Empty<PluginSpellInfo>();
_enchantments = Array.Empty<PluginActiveEnchantment>();
}
private void DetachLocked()
{
if (_spellbook is not null)
{
_spellbook.SpellbookChanged -= OnSpellbookChanged;
_spellbook.EnchantmentsChanged -= OnEnchantmentsChanged;
}
_spellbook = null;
_character = null;
_cast = null;
}
private void OnSpellbookChanged() => RebuildSpellbook();
private void OnEnchantmentsChanged() => RebuildEnchantments();
private void RebuildSpellbook()
{
Spellbook? spellbook;
lock (_gate)
spellbook = _spellbook;
if (spellbook is null)
{
_knownSelfBuffs = Array.Empty<PluginSpellInfo>();
return;
}
var built = new List<PluginSpellInfo>();
foreach (uint spellId in spellbook.LearnedSpells)
{
if (!spellbook.TryGetMetadata(spellId, out SpellMetadata meta))
continue;
if (!meta.IsSelfTargeted || !meta.IsBeneficial || meta.IsDebuff)
continue;
built.Add(Project(meta));
}
// Stable order so a plugin's buff sequence does not reshuffle between
// passes: family first, then strongest tier within it.
built.Sort(static (a, b) =>
a.Family != b.Family
? a.Family.CompareTo(b.Family)
: b.Tier.CompareTo(a.Tier));
_knownSelfBuffs = built;
}
private void RebuildEnchantments()
{
Spellbook? spellbook;
lock (_gate)
spellbook = _spellbook;
if (spellbook is null)
{
_enchantments = Array.Empty<PluginActiveEnchantment>();
return;
}
// EnchantmentsInEffectSnapshot, not the raw active set: retail lets a
// weaker same-family enchantment sit in the registry while a stronger
// one is in force. A plugin asking "am I buffed?" means in force.
IReadOnlyList<ActiveEnchantmentRecord> active =
spellbook.EnchantmentsInEffectSnapshot;
var built = new List<PluginActiveEnchantment>(active.Count);
foreach (ActiveEnchantmentRecord record in active)
{
uint family = 0;
int tier = 0;
if (spellbook.TryGetMetadata(record.SpellId, out SpellMetadata meta))
{
family = meta.Family;
tier = meta.Generation;
}
built.Add(new PluginActiveEnchantment(
record.SpellId, family, tier, record.Duration));
}
_enchantments = built;
}
private static PluginSpellInfo Project(SpellMetadata meta) => new(
meta.SpellId,
meta.Name,
meta.Family,
meta.Generation,
meta.Difficulty,
meta.ManaCost,
meta.Duration,
meta.IsSelfTargeted,
meta.IsBeneficial);
// ── ICharacterInfo ────────────────────────────────────────────────────
public bool IsInWorld => IsAvailable;
public uint CurrentMana => Vital(out uint current, out _) ? current : 0u;
public uint MaxMana => Vital(out _, out uint maximum) ? maximum : 0u;
private bool Vital(out uint current, out uint maximum)
{
current = 0;
maximum = 0;
RuntimeCharacterState? character;
lock (_gate)
character = _character;
if (character is null)
return false;
if (!character.View.TryGetVital(
(int)LocalPlayerState.VitalKind.Mana, out var vital))
{
return false;
}
current = vital.Current;
maximum = vital.Maximum;
return true;
}
public IReadOnlyList<PluginActiveEnchantment> ActiveEnchantments => _enchantments;
// ── ISpellCatalog ─────────────────────────────────────────────────────
public IReadOnlyList<PluginSpellInfo> KnownSelfBuffs => _knownSelfBuffs;
public bool TryGet(uint spellId, out PluginSpellInfo info)
{
Spellbook? spellbook;
lock (_gate)
spellbook = _spellbook;
if (spellbook is not null
&& spellbook.TryGetMetadata(spellId, out SpellMetadata meta))
{
info = Project(meta);
return true;
}
info = default;
return false;
}
// ── IMagicCommands ────────────────────────────────────────────────────
public bool IsCasting
{
get
{
RuntimeSpellCastState? cast;
lock (_gate)
cast = _cast;
return cast?.LastRequestedSpellId is not null;
}
}
public PluginCastGate EvaluateGate(uint spellId)
{
RuntimeSpellCastState? cast;
Spellbook? spellbook;
lock (_gate)
{
cast = _cast;
spellbook = _spellbook;
}
if (cast is null || spellbook is null)
return PluginCastGate.Unavailable;
if (!spellbook.Knows(spellId))
return PluginCastGate.NotKnown;
return cast.EvaluateCastGate(spellId) switch
{
SpellCastGate.Unknown => PluginCastGate.NotKnown,
SpellCastGate.NoTargetNeeded => PluginCastGate.Ready,
SpellCastGate.TargetCompatible => PluginCastGate.Ready,
_ => PluginCastGate.Refused,
};
}
public bool Cast(uint spellId)
{
RuntimeSpellCastState? cast;
lock (_gate)
cast = _cast;
return cast is not null && cast.Cast(spellId) == CastRequestResult.Sent;
}
public void Dispose()
{
lock (_gate)
{
if (_disposed)
return;
_disposed = true;
DetachLocked();
}
_knownSelfBuffs = Array.Empty<PluginSpellInfo>();
_enchantments = Array.Empty<PluginActiveEnchantment>();
}
}

View file

@ -9,13 +9,15 @@ public sealed class AppPluginHost : IPluginHost
IGameState state,
IEvents events,
ISelectionService selection,
IUiRegistry ui)
IUiRegistry ui,
IAutomationSurface automation)
{
Log = log;
State = state;
Events = events;
Selection = selection;
Ui = ui;
Automation = automation;
}
public bool HasUi => true;
@ -24,4 +26,5 @@ public sealed class AppPluginHost : IPluginHost
public IEvents Events { get; }
public ISelectionService Selection { get; }
public IUiRegistry Ui { get; }
public IAutomationSurface Automation { get; }
}

View file

@ -149,18 +149,23 @@ if (runtimeOptions.DevTools)
var worldGameState = new AcDream.Core.Plugins.WorldGameState();
var worldEvents = new AcDream.Core.Plugins.WorldEvents();
var uiRegistry = new AcDream.App.Plugins.BufferedUiRegistry();
// Constructed here and handed to both sides: GameWindow binds it to the live
// session's Runtime owners, the plugin host exposes it to plugins.
using var automation = new AcDream.App.Plugins.AppAutomationSurface();
using var window = new GameWindow(
runtimeOptions,
worldGameState,
worldEvents,
uiRegistry,
graphicalPlatform);
graphicalPlatform,
automation);
var host = new AppPluginHost(
new SerilogAdapter(Log.Logger),
worldGameState,
worldEvents,
window.Selection,
uiRegistry);
uiRegistry,
automation);
GraphicalPluginSession pluginSession = GraphicalPluginSession.Create(
applicationPaths,
runtimeOptions.Plugins,

View file

@ -363,6 +363,7 @@ public sealed class GameWindow :
// J4/J5.1: Runtime owns communication, selection, combat, and target-mode
// state. App, UI, plugins, and live-session routing borrow exact children.
private readonly AcDream.App.Plugins.AppAutomationSurface? _automation;
private readonly GameRuntime _runtime;
private readonly IDisposable _runtimeHostLease;
private RuntimeCommunicationState _runtimeCommunication =>
@ -634,9 +635,11 @@ public sealed class GameWindow :
WorldGameState worldGameState,
WorldEvents worldEvents,
AcDream.App.Plugins.BufferedUiRegistry? uiRegistry,
GraphicalHostPlatformServices platformServices)
GraphicalHostPlatformServices platformServices,
AcDream.App.Plugins.AppAutomationSurface? automation = null)
{
_options = options ?? throw new System.ArgumentNullException(nameof(options));
_automation = automation;
_statusWriter = new SessionStatusWriter(options.StatusFilePath);
_platformServices = platformServices
?? throw new ArgumentNullException(nameof(platformServices));
@ -653,6 +656,11 @@ public sealed class GameWindow :
options.DumpSky ? Console.WriteLine : null));
_runtimeHostLease = _runtime.AcquireHostLease(
"graphical GameWindow");
// Bound once, not per session: since Slice J the gameplay owners are
// stable for the GameRuntime's lifetime and it is their *contents* that
// reset across generations. Re-binding per session would be re-binding
// the same two references.
_automation?.Bind(_runtime.CharacterOwner, _runtime.ActionOwner.SpellCast);
_localPlayerIdentity = new AcDream.App.Input.LocalPlayerIdentityState(
_runtime.PlayerIdentity);
_updateFrameClock = new AcDream.App.Update.UpdateFrameClock(
@ -1626,6 +1634,11 @@ public sealed class GameWindow :
using var _updStage = _frameProfiler.BeginStage(
AcDream.App.Diagnostics.FrameStage.Update);
_frameGraphs.Tick(new AcDream.App.Update.UpdateFrameInput(dt));
// After the frame graph, so a plugin observes state the host has
// already advanced this frame rather than a half-updated world.
// WorldEvents.FireTick swallows per-subscriber faults, so a throwing
// plugin cannot break the render loop.
_worldEvents.FireTick(dt);
_renderLoopArmed = false;
}

View file

@ -75,12 +75,100 @@ public static class MarkupDocument
FrontRight = Hex((string?)el.Attribute("frontright")),
});
break;
// future element kinds (label, button, image) added here
case "label":
// Text may be a literal or a {Binding}. Bound labels re-read
// their property every frame through the Func, so a plugin
// updates its status line by assigning a property rather
// than by touching UI objects from its own thread.
var label = new UiLabel
{
Left = F(el, "x"),
Top = F(el, "y"),
TextSource = BindString((string?)el.Attribute("text"), binding),
};
if (el.Attribute("color") is not null)
label.TextColor = Color((string?)el.Attribute("color"));
panel.AddChild(label);
break;
case "button":
// onclick binds to an Action property on the binding
// object. Resolved once at build time: a button whose
// handler silently failed to bind is a bug worth failing
// loudly for, and MarkupDocument.Build is already inside
// the host's try/catch that reports panel load failures.
string? clickName = (string?)el.Attribute("onclick");
Action? onClick = BindAction(clickName, binding);
if (clickName is not null && onClick is null)
{
throw new FormatException(
$"<button onclick=\"{clickName}\"> did not resolve to an "
+ $"Action property on {binding.GetType().Name}");
}
// UiSimpleButton, not the dat-sprite UiButton: a plugin
// panel has no LayoutDesc behind it and no StateDesc
// sprites to name, so the plain rect-and-text button is the
// one that can actually render from markup alone.
var button = new UiSimpleButton
{
Left = F(el, "x"),
Top = F(el, "y"),
Width = F(el, "w"),
Height = F(el, "h"),
Text = (string?)el.Attribute("text") ?? string.Empty,
};
if (el.Attribute("color") is not null)
button.TextColor = Color((string?)el.Attribute("color"));
if (onClick is not null)
button.Click += onClick;
panel.AddChild(button);
break;
}
}
return panel;
}
/// <summary>
/// Resolves <c>{PropName}</c> to a live string reader, or returns the
/// literal text unchanged. The indirection matters: binding to a
/// <see cref="Func{T}"/> rather than copying the value once is what makes a
/// plugin's status text update as its state changes.
/// </summary>
private static Func<string?> BindString(string? attribute, object binding)
{
if (attribute is null)
return static () => null;
if (!IsBinding(attribute))
return () => attribute;
string name = attribute[1..^1];
PropertyInfo? property = binding.GetType().GetProperty(name);
if (property is null)
return () => attribute;
return () => property.GetValue(binding)?.ToString();
}
/// <summary>Resolves <c>{PropName}</c> to an <see cref="Action"/> property.</summary>
private static Action? BindAction(string? attribute, object binding)
{
if (attribute is null || !IsBinding(attribute))
return null;
string name = attribute[1..^1];
PropertyInfo? property = binding.GetType().GetProperty(name);
if (property is null || !typeof(Action).IsAssignableFrom(property.PropertyType))
return null;
// Read through on each click rather than capturing the delegate now, so
// a binding object may swap its handler (or null it out while busy)
// without rebuilding the panel.
return () => (property.GetValue(binding) as Action)?.Invoke();
}
private static bool IsBinding(string value) =>
value.Length > 2 && value[0] == '{' && value[^1] == '}';
private static float F(XElement e, string attr)
=> float.TryParse((string?)e.Attribute(attr), NumberStyles.Float,
CultureInfo.InvariantCulture, out var v) ? v : 0f;

View file

@ -69,10 +69,19 @@ public class UiLabel : UiElement
public string Text { get; set; } = string.Empty;
public Vector4 TextColor { get; set; } = new(1f, 1f, 1f, 1f);
/// <summary>
/// Optional live text reader, evaluated each draw and preferred over
/// <see cref="Text"/> when set. Markup <c>{Binding}</c> labels use this so
/// the displayed value tracks the binding object instead of freezing at
/// whatever it held when the panel was built — which is what a plugin
/// status line needs.
/// </summary>
public Func<string?>? TextSource { get; set; }
public UiLabel() { ClickThrough = true; }
protected override void OnDraw(UiRenderContext ctx)
=> ctx.DrawString(Text, 0, 0, TextColor);
=> ctx.DrawString(TextSource?.Invoke() ?? Text, 0, 0, TextColor);
}
/// <summary>