RynthCore as of 2026-10-05 evening (internal 0a2043e): release 2026.10.5.20 - own dat reader, plugin manifests, UI/login hooks with Loot Editor drag-and-drop, server-message stream (API v78), raise attributes and skills (API v79), nameplate sizing and overlay opacity, engine reload held while a plugin is fighting, StatusAgent character sheet, world map and travel for DrakRemote

This commit is contained in:
Tom Bohar 2026-10-05 14:59:43 -04:00
commit 913a2a00b6
110 changed files with 12560 additions and 1151 deletions

View file

@ -31,6 +31,9 @@ internal static class EngineSettings
private static DecalBridgeMode _decalBridgeMode = DecalBridgeMode.Auto;
private static bool _decalInGameImGui = true;
private static bool _decalStandDown = true;
// "DisabledUiHooks": the UI hooks (Compatibility/UiHookRegistry) switched off by name.
private static readonly HashSet<string> _disabledUiHooks = new(StringComparer.OrdinalIgnoreCase);
private static bool _serverMessageStream = true;
private static bool _loaded;
public static IReadOnlyList<string> PluginPaths
@ -252,6 +255,39 @@ internal static class EngineSettings
}
}
/// <summary>"DisabledUiHooks" in engine.json: an array of UI hook names
/// (Compatibility/UiHookRegistry: UseNewMode, ClientCleanup, StartTooltip, ResetTooltip,
/// CheckTooltip, StartDragandDrop, CatchDroppedItem). A listed hook is not installed at
/// the next start. Missing = every hook on. /rc hooks on|off &lt;name&gt; edits it.</summary>
public static bool IsUiHookEnabled(string name)
{
EnsureLoaded();
return !_disabledUiHooks.Contains(name);
}
/// <summary>Switches a UI hook on or off for the next start, and saves engine.json.</summary>
public static void SetUiHookEnabled(string name, bool enabled)
{
EnsureLoaded();
bool changed = enabled ? _disabledUiHooks.Remove(name) : _disabledUiHooks.Add(name);
if (changed)
Save();
}
/// <summary>"ServerMessageStream" in engine.json (default true): the kill switch for the
/// reassembled server-message stream (Net/ServerMessageStream.cs, plugin API v78). Even when
/// true, nothing is copied off the receive hook until a plugin asks for messages (or
/// /rc netmsg log|capture is on). false = the RecvFrom detour does exactly what it did
/// before the stream existed; /rc netmsg on can't override it.</summary>
public static bool ServerMessageStream
{
get
{
EnsureLoaded();
return _serverMessageStream;
}
}
public static void AddPluginPath(string path)
{
EnsureLoaded();
@ -374,11 +410,25 @@ internal static class EngineSettings
(dsdEl.ValueKind == JsonValueKind.True || dsdEl.ValueKind == JsonValueKind.False))
_decalStandDown = dsdEl.GetBoolean();
if (doc.RootElement.TryGetProperty("ServerMessageStream", out var smsEl) &&
(smsEl.ValueKind == JsonValueKind.True || smsEl.ValueKind == JsonValueKind.False))
_serverMessageStream = smsEl.GetBoolean();
if (doc.RootElement.TryGetProperty("PreventIdleLogoff", out var pilEl) &&
(pilEl.ValueKind == JsonValueKind.True || pilEl.ValueKind == JsonValueKind.False))
{
_preventIdleLogoff = pilEl.GetBoolean();
}
if (doc.RootElement.TryGetProperty("DisabledUiHooks", out var duhEl) &&
duhEl.ValueKind == JsonValueKind.Array)
{
foreach (var el in duhEl.EnumerateArray())
{
if (el.ValueKind == JsonValueKind.String && el.GetString() is { Length: > 0 } hookName)
_disabledUiHooks.Add(hookName.Trim());
}
}
}
catch (Exception ex)
{
@ -417,6 +467,15 @@ internal static class EngineSettings
w.WriteBoolean("DecalInGameImGui", false);
if (!_decalStandDown) // default true: leave the file as it was
w.WriteBoolean("DecalStandDown", false);
if (_disabledUiHooks.Count > 0) // default none: leave the file as it was
{
w.WriteStartArray("DisabledUiHooks");
foreach (string hookName in _disabledUiHooks)
w.WriteStringValue(hookName);
w.WriteEndArray();
}
if (!_serverMessageStream) // default true: leave the file as it was
w.WriteBoolean("ServerMessageStream", false);
w.WriteEndObject();
}
File.WriteAllBytes(SettingsPath, ms.ToArray());

View file

@ -55,6 +55,21 @@ internal sealed class LoadedPlugin
public PluginTickDelegate? Tick { get; set; }
public PluginRenderDelegate? Render { get; set; }
// ─── v77 UI exports (resolved lazily by PluginManager.ResolveUiExports) ───
public bool UiExportsResolved { get; set; }
public IntPtr OnScreenChangedPtr { get; set; }
public IntPtr OnClientCleanupPtr { get; set; }
public IntPtr OnTooltipShowPtr { get; set; }
public IntPtr OnTooltipHidePtr { get; set; }
public IntPtr OnDragStartPtr { get; set; }
public IntPtr OnItemDroppedPtr { get; set; }
// ─── v78 server messages (resolved when the plugin calls SetServerMessageInterest) ──
/// <summary><c>void RynthPluginOnServerMessage(uint opcode, byte* data, int length)</c>, Cdecl.</summary>
public IntPtr OnServerMessagePtr { get; set; }
/// <summary>What the plugin asked for; null or empty = nothing.</summary>
public Net.ServerMessageInterest? ServerMessageInterest { get; set; }
// ─── Runtime state ───────────────────────────────────────────────
public bool Initialized { get; set; }
public bool LoginCompleteDispatched { get; set; }
@ -62,4 +77,12 @@ internal sealed class LoadedPlugin
public bool Failed { get; set; }
public string DisplayName { get; set; } = "";
public string VersionString { get; set; } = "";
/// <summary>
/// The manifest embedded in the DLL (read before loading it; see PluginManifestGate), or null
/// for a plugin without one. Set by PluginManager after PluginLoader loads the plugin.
/// </summary>
public RynthCore.PluginSdk.Manifest.RynthPluginManifest? Manifest { get; set; }
/// <summary>Why the plugin was not started (a required plugin missing or failed); empty otherwise.</summary>
public string NotStartedReason { get; set; } = "";
}

View file

@ -11,6 +11,9 @@
// const char* RynthPluginVersion() — version string (e.g. "1.0.0")
// void RynthPluginTick() — per-frame logic (before render)
// void RynthPluginRender() — per-frame ImGui drawing
// void RynthPluginOnServerMessage(uint opcode, byte* data, int length)
// — v78, reassembled server messages the plugin
// asked for with SetServerMessageInterestFn
// ============================================================================
using System;
@ -780,6 +783,156 @@ internal struct RynthCoreAPI
/// AC's main thread (queued in the action ring from other threads, ahead of anything queued
/// after it). Returns 1 if sent or queued. Requires API v76+.</summary>
public IntPtr CloseContainerFn;
/// <summary>v77: <c>int GetScreenMode(int* previousMode)</c>: the client's screen (UIFlow mode,
/// Compatibility/UiFlowHooks.cs): 0x10000001 intro, 0x10000002 disconnected, 0x10000008 the
/// world, 0x10000009 epilogue, 0x1000000A character select, 0x1000000B character creation;
/// 0 = not known yet. *previousMode (may be null) = the screen before. Any thread.
/// Requires API v77+.</summary>
public IntPtr GetScreenModeFn;
/// <summary>v77: <c>uint GetUiHookFlags(void)</c>: which UI hooks are live, so a plugin knows
/// which v77 callbacks can arrive. bit0 RynthPluginOnScreenChanged from the UseNewMode hook,
/// bit1 ... from the +0x8C mode poll instead (one tick late), bit2 RynthPluginOnClientCleanup,
/// bit3 RynthPluginOnTooltipShow, bit4 RynthPluginOnTooltipHide, bit5 RynthPluginOnDragStart,
/// bit6 RynthPluginOnItemDropped, bit7 Client::Cleanup has started. Any thread.
/// Requires API v77+.</summary>
public IntPtr GetUiHookFlagsFn;
/// <summary>v78: <c>int SetServerMessageInterest(uint* opcodes, int opcodeCount, uint* gameEvents,
/// int eventCount)</c>: which reassembled server messages the calling plugin wants on its
/// <c>void RynthPluginOnServerMessage(uint opcode, byte* data, int length)</c> export (Cdecl;
/// data = the message after its u32 opcode, valid only during the call; for 0xF7B0 it starts
/// with object id, sequence, event type). Replaces the plugin's previous set; both counts 0 =
/// none. Opcodes are 16-bit; 0xF7B0 = every game event, 0xFFFFFFFF = every message;
/// gameEvents lists single event types. Read-only: the client's packets are never changed.
/// Call from the plugin's Init, Tick or an event (the engine finds the caller that way).
/// Returns 1 = streaming, 2 = accepted but the stream is off (engine.json
/// "ServerMessageStream": false or /rc netmsg off), 0 = the plugin has no
/// RynthPluginOnServerMessage export, -1 = caller unknown (another thread), -3 = bad
/// arguments. Requires API v78+.</summary>
public IntPtr SetServerMessageInterestFn;
/// <summary>v79: <c>int GetTrainingInfo(TrainingInfoNative* info, TrainingEntryNative* entries,
/// int maxEntries)</c>: what spending experience would do (Compatibility/TrainingApi.cs): the
/// unassigned XP, skill credits and level, and one entry per attribute (1..6), vital maximum
/// (1 health, 3 stamina, 5 mana) and portal-SkillTable skill with ranks, XP spent, base and
/// buffed value and the XP for +1 / +10 from the portal XpTable. Set info->Size to sizeof
/// before the call (info may be null; entries may be null to ask for the count). Returns the
/// number of entries there are (at most maxEntries written), 0 when there are no numbers yet
/// (not in the world, or the first read hasn't happened: it is asked for by this call and
/// comes within a couple of seconds). Asking keeps the numbers coming every 2 s for 5 s.
/// Any thread. Requires API v79+.</summary>
public IntPtr GetTrainingInfoFn;
/// <summary>v79: <c>int Raise(uint kind, uint stype, uint ranks, long expectedXp, long* xpSent)</c>:
/// spend unassigned XP like the character window's "+": kind 1 attribute (stype 1..6), 2 vital
/// (1 health, 3 stamina, 5 mana), 3 trained or specialized skill; ranks 1..100. The engine works
/// the XP out from the numbers GetTrainingInfo reports and sends it with the client's own
/// CM_Train sender (0x0045 / 0x0044 / 0x0046) on AC's main thread. expectedXp &gt; 0 must equal
/// that XP (the cost the user confirmed), else nothing is sent; 0 skips the comparison.
/// *xpSent (may be null) = the XP sent. Returns 1 sent or queued, 0 the senders aren't bound,
/// -1 not in the world, -2 bad arguments, -3 no numbers yet, -4 the numbers are over 3 s old
/// (a read was asked for: call again shortly), -5 the cost changed, -6 not enough XP, -7 not
/// raisable (top rank, untrained skill), -8 an earlier raise hasn't landed yet, -9 the send
/// failed. Any thread. Requires API v79+.</summary>
public IntPtr RaiseFn;
/// <summary>v79: <c>int TrainSkill(uint stype, int expectedCredits)</c>: train an untrained
/// skill with skill credits, as the skills window's train dialog does (0x0047, exactly the
/// portal SkillTable's TrainedCost; the server refuses anything else). expectedCredits &gt; 0
/// must equal that price; 0 skips the comparison. Same results and threading as Raise.
/// Requires API v79+.</summary>
public IntPtr TrainSkillFn;
}
/// <summary>v79 <see cref="TrainingInfoNative.Flags"/> bits.</summary>
internal static class TrainingInfoFlags
{
public const uint InWorld = 1u << 0;
/// <summary>The attribute, vital and skill raise senders are bound on this client.</summary>
public const uint RaiseBound = 1u << 1;
/// <summary>The train-with-credits sender is bound.</summary>
public const uint TrainBound = 1u << 2;
/// <summary>The player's numbers have been read (entries follow).</summary>
public const uint HaveNumbers = 1u << 3;
/// <summary>The portal SkillTable and XpTable are loaded.</summary>
public const uint HaveTables = 1u << 4;
/// <summary>A raise or train from the API hasn't shown up in the numbers yet.</summary>
public const uint Busy = 1u << 5;
}
/// <summary>v79 <see cref="TrainingEntryNative.Flags"/> bits.</summary>
internal static class TrainingEntryFlags
{
/// <summary>Can be raised with XP (an attribute, a vital, a trained or specialized skill below the top rank).</summary>
public const uint Raisable = 1u << 0;
public const uint AtTop = 1u << 1;
/// <summary>Skills: usable untrained (the SkillTable's min level 1).</summary>
public const uint UsableUntrained = 1u << 2;
/// <summary>Skills: untrained, and the SkillTable prices training it (TrainCredits).</summary>
public const uint Trainable = 1u << 3;
}
/// <summary>
/// v79 <c>GetTrainingInfo</c> header. Pack 4, 64 bytes; later versions only append.
/// Mirrored by RynthCore.PluginSdk (TrainingInfoNative in RynthCoreApiNative.cs).
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 4)]
internal unsafe struct TrainingInfoNative
{
/// <summary>In: the caller's sizeof. Out: bytes written.</summary>
public uint Size;
/// <summary><see cref="TrainingInfoFlags"/>.</summary>
public uint Flags;
/// <summary>Changes whenever any number changes.</summary>
public uint SnapshotVersion;
/// <summary>Milliseconds since the numbers were read; 0xFFFFFFFF = never.</summary>
public uint AgeMs;
/// <summary>-1 when unknown.</summary>
public long UnassignedXp;
/// <summary>-1 when unknown.</summary>
public long TotalXp;
public int Level;
/// <summary>-1 when unknown.</summary>
public int SkillCredits;
public int EntryCount;
/// <summary>Raise refuses numbers older than this (Stale).</summary>
public int StaleAfterMs;
public fixed uint Reserved[4];
}
/// <summary>
/// v79 <c>GetTrainingInfo</c> entry: one attribute, vital or skill. Pack 4, 64 bytes; later
/// versions only append. Mirrored by RynthCore.PluginSdk (TrainingEntryNative).
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 4)]
internal struct TrainingEntryNative
{
/// <summary>1 attribute, 2 vital, 3 skill.</summary>
public uint Kind;
/// <summary>Attribute 1..6, vital maximum 1 / 3 / 5, skill id.</summary>
public uint Stype;
/// <summary>Skills: 0 not in the table, 1 untrained, 2 trained, 3 specialized. 0 otherwise.</summary>
public uint Class;
public uint Ranks;
public uint XpSpent;
/// <summary>The innate (starting) level.</summary>
public uint Innate;
/// <summary>Without enchantments (a vital's maximum).</summary>
public int Base;
public int Buffed;
/// <summary>XP for one more rank; -1 at the top or not raisable.</summary>
public long CostOne;
/// <summary>XP for ten more ranks; -1 when fewer than ten are left or not raisable.</summary>
public long CostTen;
public int RanksLeft;
/// <summary>Ranks in a row the unassigned XP buys now.</summary>
public int Affordable;
/// <summary>Untrained skills: the credits to train it (0 = can't be trained from the client).</summary>
public int TrainCredits;
/// <summary><see cref="TrainingEntryFlags"/>.</summary>
public uint Flags;
}
/// <summary>v72 <see cref="TradeStateNative.Flags"/> bits.</summary>
@ -964,11 +1117,8 @@ internal unsafe struct VendorTradeStatusNative
/// <summary>Current API version. Bump when adding fields to RynthCoreAPI.</summary>
internal static class PluginContractVersion
{
public const uint Current = 76;
}
// PluginContractVersion (the current API version) lives in PluginContractVersion.cs, which
// the SDK and the launcher compile in too, so their copies can't drift from the engine's.
internal static class ClientActionHookFlags
{
@ -1077,6 +1227,17 @@ internal delegate void PluginTickDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void PluginRenderDelegate();
// v77 callbacks (exports resolved by PluginManager.ResolveUiExports, not PluginLoader):
// void RynthPluginOnScreenChanged(int oldMode, int newMode) - UIFlow mode change (GetScreenModeFn values)
// void RynthPluginOnClientCleanup(void) - Client::Cleanup starting; no ticks after it
// void RynthPluginOnTooltipShow(uint objectId, uint spellId) - AC shows a tooltip (0/0: not an item or spell)
// void RynthPluginOnTooltipHide(void) - that tooltip is gone
// void RynthPluginOnDragStart(uint objectId, uint spellId, uint iconId) - a drag out of AC's UI began
// void RynthPluginOnItemDropped(uint objectId, uint spellId, uint targetElementId) - AC caught a drop
// All cdecl, all on the plugin pump like the other events, except OnClientCleanup (see
// PluginManager.DispatchClientCleanup).
// ─── Log callback that plugins can call ─────────────────────────────────
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
@ -1485,3 +1646,21 @@ internal unsafe delegate int GetServerInfoCallbackDelegate(byte* worldName, int
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int CloseContainerCallbackDelegate(uint containerId);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetScreenModeCallbackDelegate(int* previousMode);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate uint GetUiHookFlagsCallbackDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int SetServerMessageInterestCallbackDelegate(uint* opcodes, int opcodeCount, uint* gameEvents, int eventCount);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetTrainingInfoCallbackDelegate(TrainingInfoNative* info, TrainingEntryNative* entries, int maxEntries);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int RaiseCallbackDelegate(uint kind, uint stype, uint ranks, long expectedXp, long* xpSent);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate int TrainSkillCallbackDelegate(uint stype, int expectedCredits);

View file

@ -0,0 +1,19 @@
// ============================================================================
// RynthCore.Engine - Plugins/PluginContractVersion.cs
// The plugin API's version: the number of the last table (RynthCoreAPI) layout.
//
// One file, compiled into three assemblies so they can't disagree:
// - the engine (this folder), which hands it to plugins in RynthCoreAPI.Version;
// - the SDK (RynthCore.PluginSdk), as RynthCoreHost.CurrentApiVersion;
// - the launcher (RynthCore.App.Avalonia), as the API of the engine it installed,
// to hold back feed plugins whose minEngineApi is newer.
// tools\PluginManifestTests also checks the SDK's table covers this version.
// ============================================================================
namespace RynthCore.Engine.Plugins;
/// <summary>Current API version. Bump when adding fields to RynthCoreAPI (and the SDK's RynthCoreApiNative).</summary>
internal static class PluginContractVersion
{
public const uint Current = 79;
}

View file

@ -0,0 +1,282 @@
// ============================================================================
// RynthCore.Engine - Plugins/PluginManager.UiHooks.cs
//
// API v77 (2026-10-05): the plugin side of Compatibility/UiFlowHooks and
// Compatibility/UiElementHooks.
//
// Callbacks (optional plugin exports, cdecl; looked up here on first use, not by
// PluginLoader):
// RynthPluginOnScreenChanged(int oldMode, int newMode)
// RynthPluginOnClientCleanup()
// RynthPluginOnTooltipShow(uint objectId, uint spellId)
// RynthPluginOnTooltipHide()
// RynthPluginOnDragStart(uint objectId, uint spellId, uint iconId)
// RynthPluginOnItemDropped(uint objectId, uint spellId, uint targetElementId)
// The hooks queue them from AC's main thread; ProcessPendingActions delivers them
// on the plugin pump in the order they happened (one queue), like every other
// event. OnClientCleanup is the exception: it must arrive while AC's UI still
// stands, so the Client::Cleanup detour (AC's main thread) waits, bounded, for the
// pump to deliver it, and delivers it itself (under the pump's frame guard) if the
// pump doesn't come. After it the pump delivers no more events and TickAll stops
// ticking. Plugins: keep OnClientCleanup short and never wait on AC's main thread
// inside it (it may be running on it, or waiting for you).
//
// Table functions: GetScreenModeFn, GetUiHookFlagsFn (PluginContract.cs).
// Older engines have neither the table fields nor the callbacks: a plugin checks
// RynthCoreAPI.Version >= 77 before reading the fields (RynthCoreHost.HasUiHooks).
// ============================================================================
using System;
using System.Collections.Generic;
using System.Threading;
using RynthCore.Engine.Compatibility;
namespace RynthCore.Engine.Plugins;
internal static partial class PluginManager
{
private static GetScreenModeCallbackDelegate? _getScreenModeCallback; // v77
private static GetUiHookFlagsCallbackDelegate? _getUiHookFlagsCallback; // v77
/// <summary>The thread that ran TickAll last (the plugin pump).</summary>
private static int _tickThread;
private enum UiEventKind : byte { ScreenChanged, TooltipShow, TooltipHide, DragStart, ItemDropped }
private readonly record struct PendingUiEvent(UiEventKind Kind, uint A, uint B, uint C);
private const int MaxPendingUiEvents = 256;
private static readonly Queue<PendingUiEvent> _pendingUiEvents = new();
private static readonly object PendingUiEventsLock = new();
// Client::Cleanup: 0 nothing, 1 waiting for the pump, 2 delivered (or nobody to tell).
private static int _cleanupState;
// ── Queueing (AC's main thread) ──────────────────────────────────────
public static void QueueScreenChanged(int oldMode, int newMode) => QueueUiEvent(UiEventKind.ScreenChanged, (uint)oldMode, (uint)newMode, 0);
public static void QueueTooltipShown(uint objectId, uint spellId) => QueueUiEvent(UiEventKind.TooltipShow, objectId, spellId, 0);
public static void QueueTooltipHidden() => QueueUiEvent(UiEventKind.TooltipHide, 0, 0, 0);
public static void QueueDragStarted(uint objectId, uint spellId, uint iconId) => QueueUiEvent(UiEventKind.DragStart, objectId, spellId, iconId);
public static void QueueItemDropped(uint objectId, uint spellId, uint targetElementId) => QueueUiEvent(UiEventKind.ItemDropped, objectId, spellId, targetElementId);
private static void QueueUiEvent(UiEventKind kind, uint a, uint b, uint c)
{
if (!_initialized || _plugins.Count == 0 || Volatile.Read(ref _cleanupState) != 0)
return;
lock (PendingUiEventsLock)
{
if (_pendingUiEvents.Count >= MaxPendingUiEvents)
_pendingUiEvents.Dequeue();
_pendingUiEvents.Enqueue(new PendingUiEvent(kind, a, b, c));
}
}
// ── Delivery (plugin pump) ───────────────────────────────────────────
private static void ResolveUiExports(LoadedPlugin plugin)
{
if (plugin.UiExportsResolved || plugin.ModuleHandle == IntPtr.Zero)
return;
plugin.UiExportsResolved = true;
plugin.OnScreenChangedPtr = GetProcAddress(plugin.ModuleHandle, "RynthPluginOnScreenChanged");
plugin.OnClientCleanupPtr = GetProcAddress(plugin.ModuleHandle, "RynthPluginOnClientCleanup");
plugin.OnTooltipShowPtr = GetProcAddress(plugin.ModuleHandle, "RynthPluginOnTooltipShow");
plugin.OnTooltipHidePtr = GetProcAddress(plugin.ModuleHandle, "RynthPluginOnTooltipHide");
plugin.OnDragStartPtr = GetProcAddress(plugin.ModuleHandle, "RynthPluginOnDragStart");
plugin.OnItemDroppedPtr = GetProcAddress(plugin.ModuleHandle, "RynthPluginOnItemDropped");
int count = (plugin.OnScreenChangedPtr != IntPtr.Zero ? 1 : 0) + (plugin.OnClientCleanupPtr != IntPtr.Zero ? 1 : 0)
+ (plugin.OnTooltipShowPtr != IntPtr.Zero ? 1 : 0) + (plugin.OnTooltipHidePtr != IntPtr.Zero ? 1 : 0)
+ (plugin.OnDragStartPtr != IntPtr.Zero ? 1 : 0) + (plugin.OnItemDroppedPtr != IntPtr.Zero ? 1 : 0);
if (count > 0)
RynthLog.Plugin($"PluginManager: {plugin.DisplayName} takes {count} v77 UI callback(s).");
}
private static unsafe void DispatchQueuedUiEvents()
{
if (!_initialized || _plugins.Count == 0)
return;
PendingUiEvent[] pending;
lock (PendingUiEventsLock)
{
if (_pendingUiEvents.Count == 0)
return;
pending = _pendingUiEvents.ToArray();
_pendingUiEvents.Clear();
}
foreach (PendingUiEvent evt in pending)
{
for (int i = 0; i < _plugins.Count; i++)
{
var plugin = _plugins[i];
if (!plugin.Initialized || plugin.Failed)
continue;
ResolveUiExports(plugin);
IntPtr fn = evt.Kind switch
{
UiEventKind.ScreenChanged => plugin.OnScreenChangedPtr,
UiEventKind.TooltipShow => plugin.OnTooltipShowPtr,
UiEventKind.TooltipHide => plugin.OnTooltipHidePtr,
UiEventKind.DragStart => plugin.OnDragStartPtr,
_ => plugin.OnItemDroppedPtr,
};
if (fn == IntPtr.Zero)
continue;
LoadedPlugin? outer = EnterDispatch(plugin);
try
{
switch (evt.Kind)
{
case UiEventKind.ScreenChanged:
((delegate* unmanaged[Cdecl]<int, int, void>)fn)((int)evt.A, (int)evt.B);
break;
case UiEventKind.TooltipShow:
((delegate* unmanaged[Cdecl]<uint, uint, void>)fn)(evt.A, evt.B);
break;
case UiEventKind.TooltipHide:
((delegate* unmanaged[Cdecl]<void>)fn)();
break;
case UiEventKind.DragStart:
case UiEventKind.ItemDropped:
((delegate* unmanaged[Cdecl]<uint, uint, uint, void>)fn)(evt.A, evt.B, evt.C);
break;
}
}
catch (Exception ex)
{
plugin.Failed = true;
RynthLog.Plugin($"PluginManager: {plugin.DisplayName} On{evt.Kind} threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}");
}
finally
{
LeaveDispatch(outer);
}
}
}
}
// ── Client::Cleanup ──────────────────────────────────────────────────
/// <summary>
/// AC's main thread, inside the Client::Cleanup detour before AC tears anything down.
/// Plugins are called from the plugin pump (a managed thread: a NativeAOT engine must not
/// run plugin code on AC's threads, the 2026-05-16 fail-fast), never from two threads at
/// once. So: the pump delivers RynthPluginOnClientCleanup at the top of its next frame
/// (ProcessClientCleanup, every ~16 ms) while this waits for up to half of
/// <paramref name="timeoutMs"/>. A pump that doesn't come (no frames: the device is
/// gone) leaves it to this thread, which delivers it holding the pump's frame guard
/// (EngineFrameController.TryRunOutsidePumpFrame). Exactly once either way; after the
/// full timeout AC's cleanup goes ahead regardless.
/// </summary>
public static void DispatchClientCleanup(int timeoutMs)
{
if (!_initialized || _plugins.Count == 0)
{
Volatile.Write(ref _cleanupState, 2);
return;
}
if (Interlocked.CompareExchange(ref _cleanupState, 1, 0) != 0)
return;
int pump = Volatile.Read(ref _tickThread);
if (pump == 0 || pump == Environment.CurrentManagedThreadId)
{
TakeAndDeliverClientCleanup("the calling thread (no separate pump)");
return;
}
long start = Environment.TickCount64;
long pumpUntil = start + timeoutMs / 2, until = start + timeoutMs;
while (Volatile.Read(ref _cleanupState) != 2)
{
long now = Environment.TickCount64;
if (now >= pumpUntil
&& ImGuiBackend.EngineFrameController.TryRunOutsidePumpFrame(() => TakeAndDeliverClientCleanup("AC's main thread (the pump didn't come)")))
return;
if (now >= until)
{
RynthLog.Plugin($"PluginManager: OnClientCleanup not delivered within {timeoutMs} ms (a pump frame is running); AC's cleanup goes ahead, the pump delivers it at its next frame.");
return;
}
Thread.Sleep(5);
}
}
/// <summary>
/// Plugin pump, top of ProcessPendingActions. True once Client::Cleanup started: the
/// rest of the frame's events are dropped (AC is tearing down what they describe).
/// </summary>
private static bool ProcessClientCleanup()
{
if (Volatile.Read(ref _cleanupState) == 0)
return UiFlowHooks.ClientCleanupStarted;
TakeAndDeliverClientCleanup("the plugin pump");
return true;
}
// 1 -> 2 exactly once, whoever gets there first.
private static void TakeAndDeliverClientCleanup(string where)
{
if (Interlocked.CompareExchange(ref _cleanupState, 2, 1) != 1)
return;
DeliverClientCleanup(where);
}
private static unsafe void DeliverClientCleanup(string where)
{
lock (PendingUiEventsLock)
_pendingUiEvents.Clear();
int told = 0;
for (int i = 0; i < _plugins.Count; i++)
{
var plugin = _plugins[i];
if (!plugin.Initialized || plugin.Failed)
continue;
ResolveUiExports(plugin);
if (plugin.OnClientCleanupPtr == IntPtr.Zero)
continue;
LoadedPlugin? outer = EnterDispatch(plugin);
try
{
((delegate* unmanaged[Cdecl]<void>)plugin.OnClientCleanupPtr)();
told++;
}
catch (Exception ex)
{
plugin.Failed = true;
RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnClientCleanup threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}");
}
finally
{
LeaveDispatch(outer);
}
}
RynthLog.Plugin($"PluginManager: OnClientCleanup delivered to {told} plugin(s) from {where}; no more plugin ticks or events.");
}
// ── Table functions ──────────────────────────────────────────────────
/// <summary>v77: see PluginContract.GetScreenModeFn.</summary>
private static unsafe int GetScreenModeAction(int* previousMode)
{
if (previousMode != null)
*previousMode = UiFlowHooks.PreviousMode;
return UiFlowHooks.CurrentMode;
}
/// <summary>v77: see PluginContract.GetUiHookFlagsFn.</summary>
private static uint GetUiHookFlagsAction()
{
uint flags = 0;
if (UiFlowHooks.ScreenHookLive) flags |= 1u << 0;
else flags |= 1u << 1; // the +0x8C poll drives OnScreenChanged
if (UiFlowHooks.CleanupHookLive) flags |= 1u << 2;
if (UiElementHooks.TooltipShowLive) flags |= 1u << 3;
if (UiElementHooks.TooltipHideLive) flags |= 1u << 4;
if (UiElementHooks.DragStartLive) flags |= 1u << 5;
if (UiElementHooks.DropLive) flags |= 1u << 6;
if (UiFlowHooks.ClientCleanupStarted) flags |= 1u << 7;
return flags;
}
}

View file

@ -12,10 +12,11 @@ using System.Threading;
using RynthCore.Engine.Compatibility;
using RynthCore.Engine.UI.ScriptWindows;
using RynthCore.Engine.D3D9;
using RynthCore.PluginSdk.Manifest;
namespace RynthCore.Engine.Plugins;
internal static class PluginManager
internal static partial class PluginManager
{
// Held: set when AC hasn't printed the line yet (ChatCallbackHooks holds it until the
// plugins' verdict is in; see IncomingChatHold.cs). Null for lines AC already printed.
@ -259,6 +260,10 @@ internal static class PluginManager
private static GetCharacterTitlesCallbackDelegate? _getCharacterTitlesCallback; // v75
private static GetServerInfoCallbackDelegate? _getServerInfoCallback; // v75
private static CloseContainerCallbackDelegate? _closeContainerCallback; // v76
private static SetServerMessageInterestCallbackDelegate? _setServerMessageInterestCallback; // v78
private static GetTrainingInfoCallbackDelegate? _getTrainingInfoCallback; // v79
private static RaiseCallbackDelegate? _raiseCallback; // v79
private static TrainSkillCallbackDelegate? _trainSkillCallback; // v79
private static GetVendorInfoCallbackDelegate? _getVendorInfoCallback;
private static GetVendorItemsCallbackDelegate? _getVendorItemsCallback;
private static VendorBuyCallbackDelegate? _vendorBuyCallback;
@ -521,6 +526,10 @@ internal static class PluginManager
public static void ProcessPendingActions(IntPtr imguiContext, IntPtr d3dDevice, IntPtr gameHwnd)
{
// v77: Client::Cleanup started (UiFlowHooks): tell the plugins once, then no more events.
if (ProcessClientCleanup())
return;
UiLifecycleHooks.Poll();
LoginLifecycleHooks.Poll();
SessionStateRegistry.Poll();
@ -539,6 +548,11 @@ internal static class PluginManager
// • View BEFORE Stop — a container open-then-close in one frame must
// end "closed"; draining Stop-then-View left the plugin believing the
// container was still open.
// v78 server messages first: the wire comes before the client's handling of it,
// which is what the queued events below report. Cheap when nobody asked for any.
try { Net.ServerMessageStream.Pump(_initialized && ServerMessageSubscriberCount() > 0); }
catch (Exception ex) { RynthLog.Compat($"PluginManager: server message pump failed - {ex.GetType().Name}: {ex.Message}"); }
DispatchQueuedBusyCountIncremented();
DispatchQueuedBusyCountDecremented();
DispatchQueuedCombatModeChange();
@ -558,6 +572,7 @@ internal static class PluginManager
DispatchQueuedEnchantmentAdded();
DispatchQueuedEnchantmentRemoved();
DispatchQueuedChatWindowText();
DispatchQueuedUiEvents(); // v77 screen / tooltip / drag / drop (PluginManager.UiHooks.cs)
if (_rescanRequested)
{
@ -1004,6 +1019,10 @@ internal static class PluginManager
public static void TickAll()
{
TickCount++;
Volatile.Write(ref _tickThread, Environment.CurrentManagedThreadId);
// v77: after Client::Cleanup no plugin ticks (AC is tearing its UI down); Shutdown still comes.
if (UiFlowHooks.ClientCleanupStarted)
return;
// Fire the delayed login self-identify once AC's vitals UI has settled
// (armed in DispatchLoginCompleteToLoadedPlugins; deferred past the
@ -1219,6 +1238,35 @@ internal static class PluginManager
return IntPtr.Zero;
}
/// <summary>
/// Reload deferral (2026-10-05, ReloadDeferral): asks every running plugin's optional
/// <c>const char* RynthPluginReloadBlocker(void)</c> export whether a hot reload now would
/// hurt. Null or "" = safe; a plugin without the export never objects. Fixed signature, so no
/// mismatch can reach the stack; the plugin owns the buffer and it is copied at once. Called
/// on the loader's reload thread before the engine tears down, while every plugin is loaded.
/// </summary>
internal static unsafe IReadOnlyList<(string Plugin, string Reason)> QueryReloadBlockers()
{
var result = new List<(string, string)>();
LoadedPlugin[] plugins;
try { plugins = _plugins.ToArray(); }
catch { return result; } // the list changed under us (a plugin loading): don't hold the reload on it
foreach (var p in plugins)
{
try
{
if (p.ModuleHandle == IntPtr.Zero || !p.Initialized || p.Failed) continue;
IntPtr fn = GetProcAddress(p.ModuleHandle, "RynthPluginReloadBlocker");
if (fn == IntPtr.Zero) continue;
IntPtr text = ((delegate* unmanaged[Cdecl]<IntPtr>)fn)();
string? reason = text != IntPtr.Zero ? Marshal.PtrToStringAnsi(text) : null;
if (!string.IsNullOrWhiteSpace(reason)) result.Add((p.DisplayName, reason.Trim()));
}
catch { /* a plugin that can't answer doesn't hold the reload */ }
}
return result;
}
private static void LogFromPlugin(IntPtr messageUtf8)
{
string? msg = Marshal.PtrToStringAnsi(messageUtf8);
@ -2286,6 +2334,7 @@ internal static class PluginManager
// bundled Plugins\ folder — that historically caused stray DLLs to
// load on next start (or after hot-reload) without the user knowing.
var extraPaths = EngineSettings.PluginPaths;
var candidates = new List<string>(extraPaths.Count);
for (int i = 0; i < extraPaths.Count; i++)
{
string dllPath = extraPaths[i];
@ -2308,21 +2357,109 @@ internal static class PluginManager
break;
}
}
for (int j = 0; j < candidates.Count && !alreadyLoaded; j++)
{
if (string.Equals(Path.GetFileName(candidates[j]), extraFileName, StringComparison.OrdinalIgnoreCase))
alreadyLoaded = true;
}
if (alreadyLoaded)
{
RynthLog.Plugin($"PluginManager: Extra plugin {extraFileName} already loaded from default directory — skipping.");
continue;
}
candidates.Add(dllPath);
}
// Manifests (embedded in the DLLs, read without loading them): refuse a plugin that needs
// a newer engine API or a missing plugin, and put required plugins first. Without
// manifests the list loads exactly as before.
PluginManifestGate.LoadPlan plan = PluginManifestGate.Plan(candidates, PluginContractVersion.Current, RawFileVersion);
foreach (string line in plan.Log)
RynthLog.Plugin($"PluginManager: {line}");
foreach (PluginRefusal refusal in plan.Refused)
RefusePlugin(Path.GetFileName(refusal.Plugin.Key), refusal.Reason);
foreach ((string dllPath, RynthPluginManifest? manifest) in plan.Load)
{
// A required plugin that failed to load (PluginLoader said no) takes its dependents with it.
string? missing = PluginManifestGate.CheckRequiredStarted(manifest, name => FindPlugin(name) != null ? true : null);
if (missing != null)
{
RefusePlugin(Path.GetFileName(dllPath), missing);
continue;
}
RynthLog.Plugin($"PluginManager: Loading extra plugin: {dllPath}");
var plugin = PluginLoader.LoadSingle(dllPath, _shadowRootDir, _loadGeneration);
if (plugin != null)
{
plugin.Manifest = manifest;
if (manifest != null && !string.Equals(manifest.Name, plugin.DisplayName, StringComparison.OrdinalIgnoreCase))
RynthLog.Plugin($"PluginManager: {plugin.FileName}: manifest name '{manifest.Name}' differs from RynthPluginName '{plugin.DisplayName}'; dependencies use the manifest's.");
_plugins.Add(plugin);
}
}
PublishPluginsRenderSnapshot();
}
// ── Plugin manifests ─────────────────────────────────────────────────
/// <summary>Refusals not yet said in chat; said once each, at login (see AnnouncePluginRefusals).</summary>
private static readonly List<string> _pendingRefusalNotices = new();
private static readonly HashSet<string> _announcedRefusals = new(StringComparer.Ordinal);
private static void RefusePlugin(string fileName, string reason)
{
RynthLog.Plugin($"PluginManager: NOT starting {fileName}: {reason} (this RynthCore is plugin API {PluginContractVersion.Current}).");
lock (_pendingRefusalNotices)
{
if (!_announcedRefusals.Contains(reason) && !_pendingRefusalNotices.Contains(reason))
_pendingRefusalNotices.Add(reason);
}
if (_loginCompleteObserved)
AnnouncePluginRefusals();
}
/// <summary>Says each refusal once in chat ("[RynthCore] RynthOracle needs a newer RynthCore (API 77) - not started."). Pump thread.</summary>
private static void AnnouncePluginRefusals()
{
List<string> lines;
lock (_pendingRefusalNotices)
{
if (_pendingRefusalNotices.Count == 0) return;
lines = new List<string>(_pendingRefusalNotices);
_pendingRefusalNotices.Clear();
foreach (string l in lines) _announcedRefusals.Add(l);
}
foreach (string line in lines)
AcMainThreadQueue.EnqueueWriteToChat($"[RynthCore] {line} - not started.", 1);
}
/// <summary>The loaded plugin going by <paramref name="name"/>: manifest name, else its file's name, else RynthPluginName.</summary>
private static LoadedPlugin? FindPlugin(string name)
{
for (int i = 0; i < _plugins.Count; i++)
{
LoadedPlugin p = _plugins[i];
if (p.Manifest != null && string.Equals(p.Manifest.Name, name, StringComparison.OrdinalIgnoreCase)) return p;
}
for (int i = 0; i < _plugins.Count; i++)
{
LoadedPlugin p = _plugins[i];
if (string.Equals(RynthPluginManifest.NameFromFile(p.SourceFilePath), name, StringComparison.OrdinalIgnoreCase)
|| string.Equals(p.DisplayName, name, StringComparison.OrdinalIgnoreCase))
return p;
}
return null;
}
private static string RawFileVersion(string path)
{
try { return System.Diagnostics.FileVersionInfo.GetVersionInfo(path).ProductVersion ?? ""; }
catch { return ""; }
}
private static void InitializeLoadedPlugins()
{
if (_plugins.Count == 0)
@ -2337,6 +2474,20 @@ internal static class PluginManager
for (int i = 0; i < _plugins.Count; i++)
{
var plugin = _plugins[i];
// Manifest: a plugin whose required plugin didn't start isn't started either (they
// come first: LoadPluginsFromDisk ordered them). No manifest, no check.
string? blocked = PluginManifestGate.CheckRequiredStarted(plugin.Manifest, name =>
FindPlugin(name) is { } dep ? dep.Initialized && !dep.Failed : null);
if (blocked != null)
{
plugin.Failed = true;
plugin.NotStartedReason = blocked;
RefusePlugin(plugin.FileName, blocked);
continue;
}
plugin.NotStartedReason = "";
LoadedPlugin? outer = EnterDispatch(plugin);
try
{
@ -2451,6 +2602,7 @@ internal static class PluginManager
return;
_loginDispatchPending = false;
AnnouncePluginRefusals(); // plugins the manifests kept out, once each, now that chat is up
for (int i = 0; i < _plugins.Count; i++)
{
@ -2633,6 +2785,12 @@ internal static class PluginManager
unsafe { _getCharacterTitlesCallback ??= GetCharacterTitlesAction; }
unsafe { _getServerInfoCallback ??= GetServerInfoAction; }
_closeContainerCallback ??= CloseContainerAction;
unsafe { _getScreenModeCallback ??= GetScreenModeAction; } // v77 (PluginManager.UiHooks.cs)
_getUiHookFlagsCallback ??= GetUiHookFlagsAction;
unsafe { _setServerMessageInterestCallback ??= SetServerMessageInterestAction; }
unsafe { _getTrainingInfoCallback ??= GetTrainingInfoAction; } // v79
unsafe { _raiseCallback ??= RaiseAction; }
_trainSkillCallback ??= TrainSkillAction;
_getVendorInfoCallback ??= GetVendorInfoAction;
_getVendorItemsCallback ??= GetVendorItemsAction;
_vendorBuyCallback ??= VendorBuyAction;
@ -2770,6 +2928,12 @@ internal static class PluginManager
_api.GetCharacterTitlesFn = Marshal.GetFunctionPointerForDelegate(_getCharacterTitlesCallback);
_api.GetServerInfoFn = Marshal.GetFunctionPointerForDelegate(_getServerInfoCallback);
_api.CloseContainerFn = Marshal.GetFunctionPointerForDelegate(_closeContainerCallback);
_api.GetScreenModeFn = Marshal.GetFunctionPointerForDelegate(_getScreenModeCallback);
_api.GetUiHookFlagsFn = Marshal.GetFunctionPointerForDelegate(_getUiHookFlagsCallback);
_api.SetServerMessageInterestFn = Marshal.GetFunctionPointerForDelegate(_setServerMessageInterestCallback);
_api.GetTrainingInfoFn = Marshal.GetFunctionPointerForDelegate(_getTrainingInfoCallback);
_api.RaiseFn = Marshal.GetFunctionPointerForDelegate(_raiseCallback);
_api.TrainSkillFn = Marshal.GetFunctionPointerForDelegate(_trainSkillCallback);
_api.GetVendorInfoFn = Marshal.GetFunctionPointerForDelegate(_getVendorInfoCallback);
_api.GetVendorItemsFn = Marshal.GetFunctionPointerForDelegate(_getVendorItemsCallback);
_api.VendorBuyFn = Marshal.GetFunctionPointerForDelegate(_vendorBuyCallback);
@ -3828,6 +3992,133 @@ internal static class PluginManager
/// <summary>v72: see PluginContract.TradeCloseFn.</summary>
private static int TradeCloseAction() => ToAbiBool(PlayerTrade.Close());
// ── v79: spending experience (Compatibility/TrainingApi.cs) ─────────
/// <summary>v79: see PluginContract.GetTrainingInfoFn.</summary>
private static unsafe int GetTrainingInfoAction(TrainingInfoNative* info, TrainingEntryNative* entries, int maxEntries)
{
try
{
return TrainingApi.GetInfo(info, entries, maxEntries);
}
catch
{
return 0;
}
}
/// <summary>v79: see PluginContract.RaiseFn.</summary>
private static unsafe int RaiseAction(uint kind, uint stype, uint ranks, long expectedXp, long* xpSent)
{
try
{
RaiseStatus r = TrainingApi.Raise(kind, stype, ranks, expectedXp, out long sent);
if (xpSent != null) *xpSent = sent;
return (int)r;
}
catch (Exception ex)
{
RynthLog.Compat($"Raise failed - {ex.GetType().Name}: {ex.Message}");
return (int)RaiseStatus.SendFailed;
}
}
/// <summary>v79: see PluginContract.TrainSkillFn.</summary>
private static int TrainSkillAction(uint stype, int expectedCredits)
{
try
{
return (int)TrainingApi.TrainSkill(stype, expectedCredits);
}
catch (Exception ex)
{
RynthLog.Compat($"TrainSkill failed - {ex.GetType().Name}: {ex.Message}");
return (int)RaiseStatus.SendFailed;
}
}
/// <summary>v78: see PluginContract.SetServerMessageInterestFn.</summary>
private static unsafe int SetServerMessageInterestAction(uint* opcodes, int opcodeCount, uint* gameEvents, int eventCount)
{
try
{
LoadedPlugin? owner = CurrentDispatch;
if (owner == null)
return -1;
if (opcodeCount == 0 && eventCount == 0)
{
owner.ServerMessageInterest?.Clear();
RynthLog.Plugin($"PluginManager: {owner.DisplayName} stopped server messages.");
return 1;
}
if (owner.OnServerMessagePtr == IntPtr.Zero)
owner.OnServerMessagePtr = GetProcAddress(owner.ModuleHandle, "RynthPluginOnServerMessage");
if (owner.OnServerMessagePtr == IntPtr.Zero)
return 0;
var interest = owner.ServerMessageInterest ??= new Net.ServerMessageInterest();
if (!interest.Set(opcodes, opcodeCount, gameEvents, eventCount))
return -3;
RynthLog.Plugin($"PluginManager: {owner.DisplayName} wants server messages: " +
(interest.All ? "all" : $"{interest.OpcodeCount} opcode(s), {interest.EventCount} game event(s){(interest.AllGameEvents ? " + all game events" : "")}"));
return EngineSettings.ServerMessageStream ? 1 : 2;
}
catch (Exception ex)
{
RynthLog.Plugin($"PluginManager: SetServerMessageInterest failed - {ex.GetType().Name}: {ex.Message}");
return -3;
}
}
/// <summary>v78: initialized, healthy plugins with a non-empty server-message interest.</summary>
internal static int ServerMessageSubscriberCount()
{
int n = 0;
for (int i = 0; i < _plugins.Count; i++)
{
var p = _plugins[i];
if (p.Initialized && !p.Failed && p.OnServerMessagePtr != IntPtr.Zero &&
p.ServerMessageInterest is { IsEmpty: false })
n++;
}
return n;
}
/// <summary>
/// v78: one reassembled server message to the plugins that asked for it (called from
/// ServerMessageStream.Pump, on this pump). <paramref name="body"/> is the message after
/// its opcode, valid only during the call. Returns how many plugins were called.
/// </summary>
internal static unsafe int DispatchServerMessage(uint opcode, uint eventType, byte* body, int length)
{
int called = 0;
for (int i = 0; i < _plugins.Count; i++)
{
var plugin = _plugins[i];
if (!plugin.Initialized || plugin.Failed || plugin.OnServerMessagePtr == IntPtr.Zero)
continue;
var interest = plugin.ServerMessageInterest;
if (interest == null || !interest.Wants(opcode, eventType))
continue;
LoadedPlugin? outer = EnterDispatch(plugin);
try
{
((delegate* unmanaged[Cdecl]<uint, byte*, int, void>)plugin.OnServerMessagePtr)(opcode, body, length);
called++;
}
catch (Exception ex)
{
plugin.Failed = true;
RynthLog.Error($"PluginManager: {plugin.DisplayName} OnServerMessage threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)} - disabled.");
}
finally
{
LeaveDispatch(outer);
}
}
return called;
}
/// <summary>v76: close an external container (see PluginContract.CloseContainerFn).</summary>
private static int CloseContainerAction(uint containerId)
{

View file

@ -0,0 +1,119 @@
// ============================================================================
// RynthCore.Engine - Plugins/PluginManifestGate.cs
// The engine's use of plugin manifests (RynthCore.PluginSdk.Manifest, compiled in):
// - before any plugin DLL is loaded, read each one's embedded manifest from the
// file (no LoadLibrary: a refused NativeAOT plugin would otherwise keep a whole
// runtime in acclient's 4 GB for good) and decide which may load, in what order;
// - before a plugin's Init, check the plugins it requires started.
// A plugin without a manifest is never refused and keeps its place in the list,
// so a plugin list with no manifests loads exactly as before.
//
// BCL + the manifest files only, so tools\PluginManifestTests compiles it too.
// PluginManager owns the logging and the chat notice.
// ============================================================================
using System;
using System.Collections.Generic;
using System.IO;
using RynthCore.PluginSdk.Manifest;
namespace RynthCore.Engine.Plugins;
internal static class PluginManifestGate
{
internal sealed class LoadPlan
{
/// <summary>Paths to load, in order, with their manifests (null for a plugin without one).</summary>
public List<(string Path, RynthPluginManifest? Manifest)> Load { get; } = new();
/// <summary>Plugins not loaded, with the reason (one sentence, fit for chat).</summary>
public List<PluginRefusal> Refused { get; } = new();
/// <summary>Log lines: manifests found, broken manifests, notes.</summary>
public List<string> Log { get; } = new();
}
/// <summary>
/// Reads the manifests of <paramref name="paths"/> and resolves them against
/// <paramref name="engineApi"/>. <paramref name="fileVersion"/> gives a DLL's version resource
/// (for dependency versions of plugins whose manifest has none); null skips it.
/// </summary>
public static LoadPlan Plan(IReadOnlyList<string> paths, uint engineApi, Func<string, string>? fileVersion = null)
{
var plan = new LoadPlan();
var candidates = new List<PluginCandidate>(paths.Count);
int withManifest = 0;
foreach (string path in paths)
{
RynthPluginManifest? manifest = null;
try
{
manifest = PluginManifestReader.Read(path);
}
catch (InvalidDataException ex)
{
// A broken manifest is a build problem, not the player's: load it the old way.
plan.Log.Add($"{Path.GetFileName(path)}: manifest unreadable ({ex.Message}) - loading it as a plugin without one.");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
plan.Log.Add($"{Path.GetFileName(path)}: could not read its manifest ({ex.Message}) - loading it as a plugin without one.");
}
string fv = "";
if (fileVersion != null && string.IsNullOrEmpty(manifest?.Version))
{
try { fv = fileVersion(path) ?? ""; } catch { fv = ""; }
}
if (manifest != null)
{
withManifest++;
plan.Log.Add($"{Path.GetFileName(path)}: manifest {Describe(manifest)}.");
}
candidates.Add(new PluginCandidate(path, manifest, fv));
}
PluginResolution res = PluginManifestResolver.Resolve(candidates, engineApi);
foreach (PluginCandidate c in res.Order)
plan.Load.Add((c.Key, c.Manifest));
plan.Refused.AddRange(res.Refused);
foreach (string note in res.Notes)
plan.Log.Add(note);
if (withManifest == 0 && paths.Count > 0)
plan.Log.Add("no plugin has a manifest; loading them as listed.");
return plan;
}
/// <summary>
/// Null when every plugin <paramref name="manifest"/> requires has started; otherwise why not.
/// <paramref name="started"/> answers by plugin name: true started, false loaded but not
/// started (failed or refused at Init), null not loaded at all.
/// </summary>
public static string? CheckRequiredStarted(RynthPluginManifest? manifest, Func<string, bool?> started)
{
if (manifest == null) return null;
foreach (RynthPluginDependency d in manifest.Dependencies)
{
if (d.Optional) continue;
bool? s = started(d.Name);
if (s == true) continue;
return s == false
? $"{manifest.Name} needs {d.Name}, which failed to start"
: $"{manifest.Name} needs {d.Name}, which is not loaded";
}
return null;
}
/// <summary>"RynthOracle 2026.10.5.1, API 71+, needs RynthAi (optional)".</summary>
public static string Describe(RynthPluginManifest m)
{
string api = m.MaxEngineApi != 0 ? $"API {m.MinEngineApi}-{m.MaxEngineApi}" : $"API {m.MinEngineApi}+";
string s = $"{m.Name}{(m.Version.Length > 0 ? " " + m.Version : "")}, {api}";
if (m.Dependencies.Count > 0)
{
var parts = new List<string>(m.Dependencies.Count);
foreach (RynthPluginDependency d in m.Dependencies)
parts.Add(d.Name + (d.MinVersion.Length > 0 ? " " + d.MinVersion + "+" : "") + (d.Optional ? " (optional)" : ""));
s += ", needs " + string.Join(", ", parts);
}
return s;
}
}