RynthCore as of 2026-10-04 (internal 843c801): RynthNav auto-travel and the navigation map, plugin API v75 (server and titles), launcher with Available plugins, download progress and the update on the front page, opt-in usage statistics, NPC names, radar colours, title-bar text size, FPS limiter, client action unlocks, release 2026.10.4.6
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
9b5e2765b7
commit
a24ed6df7c
322 changed files with 83009 additions and 7504 deletions
|
|
@ -7,10 +7,15 @@ namespace RynthCore.Engine.Plugins;
|
|||
|
||||
internal static class EngineSettings
|
||||
{
|
||||
private static readonly string SettingsPath = Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
|
||||
"RynthCore",
|
||||
"engine.json");
|
||||
// RYNTHCORE_ENGINE_SETTINGS points a test client at its own engine.json (its own
|
||||
// plugin list, no Avalonia, ...) without touching the one real clients share.
|
||||
private static readonly string SettingsPath =
|
||||
Environment.GetEnvironmentVariable("RYNTHCORE_ENGINE_SETTINGS") is { Length: > 0 } overridePath
|
||||
? overridePath
|
||||
: Path.Combine(
|
||||
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
|
||||
"RynthCore",
|
||||
"engine.json");
|
||||
|
||||
private static List<string> _pluginPaths = new();
|
||||
private static bool _enableImGuiShell = true;
|
||||
|
|
@ -22,8 +27,10 @@ internal static class EngineSettings
|
|||
private static int _engineHookCount = int.MaxValue;
|
||||
private static bool _enableImGuiBackend = true;
|
||||
private static bool _enableHangMinidump = true;
|
||||
private static bool _drawCustomVitalBars = true;
|
||||
private static bool _preventIdleLogoff = true;
|
||||
private static DecalBridgeMode _decalBridgeMode = DecalBridgeMode.Auto;
|
||||
private static bool _decalInGameImGui = true;
|
||||
private static bool _decalStandDown = true;
|
||||
private static bool _loaded;
|
||||
|
||||
public static IReadOnlyList<string> PluginPaths
|
||||
|
|
@ -80,10 +87,25 @@ internal static class EngineSettings
|
|||
get
|
||||
{
|
||||
EnsureLoaded();
|
||||
#if ENGINE_CORECLR
|
||||
// Avalonia can't live in an unloadable engine (docs/UNLOADABLE_ENGINE_PLAN.md,
|
||||
// Phase 5): Skia/HarfBuzz keep strong GC handles for their native callbacks, so
|
||||
// the generation never unloads, and the next generation's copy finds the old
|
||||
// one's assemblies ("Call from invalid thread"). The in-game panels are ImGui;
|
||||
// pop-outs return as ImGui windows (IMGUI_PARITY_PLAN P5).
|
||||
if (_enableAvaloniaOverlay && System.Threading.Interlocked.Exchange(ref _avaloniaOffLogged, 1) == 0)
|
||||
RynthLog.Info("EngineSettings: EnableAvaloniaOverlay ignored - the CoreCLR engine runs without Avalonia (it can't be unloaded).");
|
||||
return false;
|
||||
#else
|
||||
return _enableAvaloniaOverlay;
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
#if ENGINE_CORECLR
|
||||
private static int _avaloniaOffLogged;
|
||||
#endif
|
||||
|
||||
/// <summary>When false, D3D9Bootstrapper.Start() is skipped at LoginComplete so neither
|
||||
/// Direct3DCreate9/CreateDevice nor IDirect3DDevice9::EndScene get hooked. Eliminates the
|
||||
/// entire D3D9 detour path, ImGui per-frame work, and the in-AC overlay bar. Compatibility
|
||||
|
|
@ -143,6 +165,14 @@ internal static class EngineSettings
|
|||
EnsureLoaded();
|
||||
return _enableImGuiBackend;
|
||||
}
|
||||
set
|
||||
{
|
||||
// Set in game with /rc imgui on|off; persisted to engine.json.
|
||||
EnsureLoaded(); // populate _pluginPaths before Save() rewrites the file
|
||||
if (_enableImGuiBackend == value) return;
|
||||
_enableImGuiBackend = value;
|
||||
Save();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>When true, MainThreadHangWatchdog writes a minidump to
|
||||
|
|
@ -158,27 +188,6 @@ internal static class EngineSettings
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>When true, the engine draws the custom D3D9 Health/Stamina/Mana HUD
|
||||
/// (<see cref="D3D9.VitalHud"/>) in EndScene. Toggleable live via "/rc vitals";
|
||||
/// the setter persists to engine.json so it survives relaunch. Default true.
|
||||
/// Only takes visible effect on a clean (no-Decal) client where the
|
||||
/// D3D9/EndScene path runs.</summary>
|
||||
public static bool DrawCustomVitalBars
|
||||
{
|
||||
get
|
||||
{
|
||||
EnsureLoaded();
|
||||
return _drawCustomVitalBars;
|
||||
}
|
||||
set
|
||||
{
|
||||
EnsureLoaded(); // populate _pluginPaths before Save() rewrites the file
|
||||
if (_drawCustomVitalBars == value) return;
|
||||
_drawCustomVitalBars = value;
|
||||
Save();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>When true (default), the engine keeps the retail client's idle clock fresh
|
||||
/// while in the world, so ClientUISystem::UseTime's 20-minute idle auto-logoff
|
||||
/// (InactiveTimeBeforeLogout) can't log off a character a bot is playing: the bot's
|
||||
|
|
@ -193,6 +202,56 @@ internal static class EngineSettings
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>"DecalBridge" in engine.json: Auto (default), On or Off. Only matters when
|
||||
/// Decal is loaded in the same client (docs/DECAL_BRIDGE_PLAN.md):
|
||||
/// Auto - bridge mode when the RynthCore Decal bridge is registered and says hello
|
||||
/// within a short wait; otherwise the old coexistence mode.
|
||||
/// On - bridge mode whenever Decal is loaded (no fallback; for testing).
|
||||
/// Off - never bridge mode (the old coexistence mode).
|
||||
/// Without Decal the setting is never read past this flag.</summary>
|
||||
public static DecalBridgeMode DecalBridgeMode
|
||||
{
|
||||
get
|
||||
{
|
||||
EnsureLoaded();
|
||||
return _decalBridgeMode;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>"DecalInGameImGui" in engine.json (default true since 2026-09-30, after the
|
||||
/// Reset, UB and soak checks in docs/DECAL_BRIDGE_PLAN.md). Only read when Decal is loaded
|
||||
/// in the same client and bridge mode is on: true installs the normal EndScene hook and
|
||||
/// ImGui renderer there (the device is found without creating one); false keeps the old
|
||||
/// Decal-coexistence "no D3D9" path. RYNTHCORE_DECAL_IMGUI=1/0 overrides it for one client.
|
||||
/// Without Decal it is never read.</summary>
|
||||
public static bool DecalInGameImGui
|
||||
{
|
||||
get
|
||||
{
|
||||
string? env = Environment.GetEnvironmentVariable("RYNTHCORE_DECAL_IMGUI");
|
||||
if (env == "1") return true;
|
||||
if (env == "0") return false;
|
||||
EnsureLoaded();
|
||||
return _decalInGameImGui;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>"DecalStandDown" in engine.json (default true, 2026-10-03). Only read when
|
||||
/// Decal is loaded in the same client and the Decal bridge is NOT active (not registered
|
||||
/// as the client sees it, no hello, protocol mismatch): true makes the engine stand down
|
||||
/// (EntryPoint.InitWorker) - no plugins, no overlay, none of the hooks that collide with
|
||||
/// Decal; only what the "bridge isn't loaded" chat line needs. The old coexistence path
|
||||
/// (no overlay, then crashes) ran there before. false brings that path back.
|
||||
/// DecalBridge=Off always keeps the old path (tests). Without Decal it is never read.</summary>
|
||||
public static bool DecalStandDown
|
||||
{
|
||||
get
|
||||
{
|
||||
EnsureLoaded();
|
||||
return _decalStandDown;
|
||||
}
|
||||
}
|
||||
|
||||
public static void AddPluginPath(string path)
|
||||
{
|
||||
EnsureLoaded();
|
||||
|
|
@ -297,12 +356,24 @@ internal static class EngineSettings
|
|||
_enableHangMinidump = hmEl.GetBoolean();
|
||||
}
|
||||
|
||||
if (doc.RootElement.TryGetProperty("DrawCustomVitalBars", out var cvbEl) &&
|
||||
(cvbEl.ValueKind == JsonValueKind.True || cvbEl.ValueKind == JsonValueKind.False))
|
||||
|
||||
if (doc.RootElement.TryGetProperty("DecalBridge", out var dbEl))
|
||||
{
|
||||
_drawCustomVitalBars = cvbEl.GetBoolean();
|
||||
if (dbEl.ValueKind == JsonValueKind.True) _decalBridgeMode = DecalBridgeMode.On;
|
||||
else if (dbEl.ValueKind == JsonValueKind.False) _decalBridgeMode = DecalBridgeMode.Off;
|
||||
else if (dbEl.ValueKind == JsonValueKind.String &&
|
||||
Enum.TryParse(dbEl.GetString(), ignoreCase: true, out DecalBridgeMode dbm))
|
||||
_decalBridgeMode = dbm;
|
||||
}
|
||||
|
||||
if (doc.RootElement.TryGetProperty("DecalInGameImGui", out var dimEl) &&
|
||||
(dimEl.ValueKind == JsonValueKind.True || dimEl.ValueKind == JsonValueKind.False))
|
||||
_decalInGameImGui = dimEl.GetBoolean();
|
||||
|
||||
if (doc.RootElement.TryGetProperty("DecalStandDown", out var dsdEl) &&
|
||||
(dsdEl.ValueKind == JsonValueKind.True || dsdEl.ValueKind == JsonValueKind.False))
|
||||
_decalStandDown = dsdEl.GetBoolean();
|
||||
|
||||
if (doc.RootElement.TryGetProperty("PreventIdleLogoff", out var pilEl) &&
|
||||
(pilEl.ValueKind == JsonValueKind.True || pilEl.ValueKind == JsonValueKind.False))
|
||||
{
|
||||
|
|
@ -339,8 +410,13 @@ internal static class EngineSettings
|
|||
w.WriteNumber("EngineHookCount", _engineHookCount);
|
||||
w.WriteBoolean("EnableImGuiBackend", _enableImGuiBackend);
|
||||
w.WriteBoolean("EnableHangMinidump", _enableHangMinidump);
|
||||
w.WriteBoolean("DrawCustomVitalBars", _drawCustomVitalBars);
|
||||
w.WriteBoolean("PreventIdleLogoff", _preventIdleLogoff);
|
||||
if (_decalBridgeMode != DecalBridgeMode.Auto) // default: leave the file as it was
|
||||
w.WriteString("DecalBridge", _decalBridgeMode.ToString());
|
||||
if (!_decalInGameImGui) // default true: leave the file as it was
|
||||
w.WriteBoolean("DecalInGameImGui", false);
|
||||
if (!_decalStandDown) // default true: leave the file as it was
|
||||
w.WriteBoolean("DecalStandDown", false);
|
||||
w.WriteEndObject();
|
||||
}
|
||||
File.WriteAllBytes(SettingsPath, ms.ToArray());
|
||||
|
|
@ -351,3 +427,6 @@ internal static class EngineSettings
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>engine.json "DecalBridge" (see <see cref="EngineSettings.DecalBridgeMode"/>).</summary>
|
||||
internal enum DecalBridgeMode { Auto = 0, On = 1, Off = 2 }
|
||||
|
|
|
|||
203
src/RynthCore.Engine/Plugins/ManagedPlugins.cs
Normal file
203
src/RynthCore.Engine/Plugins/ManagedPlugins.cs
Normal file
|
|
@ -0,0 +1,203 @@
|
|||
// ============================================================================
|
||||
// RynthCore.Engine - Plugins/ManagedPlugins.cs
|
||||
//
|
||||
// Managed plugins (docs/UNLOADABLE_ENGINE_PLAN.md, Phase 4). Under the CoreCLR engine
|
||||
// a plugin can be a plain managed assembly instead of a NativeAOT DLL: the same
|
||||
// source, built with -p:PublishAot=false. It keeps its C ABI: the
|
||||
// [UnmanagedCallersOnly(EntryPoint = "RynthPluginInit")] etc. methods the NativeAOT
|
||||
// build exports are found by reflection instead of GetProcAddress, so PluginLoader,
|
||||
// PluginManager and the panels' export lookups work unchanged through a stand-in
|
||||
// module handle.
|
||||
//
|
||||
// Each plugin loads into its own collectible AssemblyLoadContext (its dependencies,
|
||||
// e.g. RynthCore.PluginSdk or MoonSharp, from its own folder), unloaded after its
|
||||
// RynthPluginShutdown. Unlike a NativeAOT plugin (its own runtime, never freed) it
|
||||
// shares the engine's runtime and GC and goes away with a reload.
|
||||
// ============================================================================
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
#if ENGINE_CORECLR
|
||||
using System.Runtime.Loader;
|
||||
#endif
|
||||
|
||||
namespace RynthCore.Engine.Plugins;
|
||||
|
||||
internal static class ManagedPlugins
|
||||
{
|
||||
// Stand-in handles: real module bases are 64 KB aligned, these never are.
|
||||
private static int _nextHandle = 0x7F000001;
|
||||
private static readonly object Sync = new();
|
||||
private static readonly Dictionary<IntPtr, Entry> Loaded = new();
|
||||
|
||||
private sealed class Entry
|
||||
{
|
||||
public required string Name;
|
||||
public required Dictionary<string, IntPtr> Exports;
|
||||
#if ENGINE_CORECLR
|
||||
public required PluginLoadContext Context;
|
||||
#endif
|
||||
}
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true, EntryPoint = "GetProcAddress")]
|
||||
private static extern IntPtr Kernel32GetProcAddress(IntPtr hModule, string lpProcName);
|
||||
|
||||
/// <summary>GetProcAddress for plugin handles: a managed plugin's export map, else kernel32.</summary>
|
||||
public static IntPtr GetProcAddress(IntPtr handle, string name)
|
||||
{
|
||||
lock (Sync)
|
||||
{
|
||||
if (Loaded.TryGetValue(handle, out Entry? e))
|
||||
return e.Exports.TryGetValue(name, out IntPtr fn) ? fn : IntPtr.Zero;
|
||||
}
|
||||
return Kernel32GetProcAddress(handle, name);
|
||||
}
|
||||
|
||||
public static bool IsManagedHandle(IntPtr handle)
|
||||
{
|
||||
lock (Sync) return Loaded.ContainsKey(handle);
|
||||
}
|
||||
|
||||
/// <summary>True when <paramref name="path"/> is a .NET assembly (PE with a CLR header).</summary>
|
||||
public static bool IsManagedAssembly(string path)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
||||
using var pe = new System.Reflection.PortableExecutable.PEReader(fs);
|
||||
return pe.HasMetadata && pe.PEHeaders.CorHeader != null;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Loads a managed plugin; returns its stand-in module handle, or zero.</summary>
|
||||
public static IntPtr Load(string path)
|
||||
{
|
||||
string fileName = Path.GetFileName(path);
|
||||
#if ENGINE_CORECLR
|
||||
try
|
||||
{
|
||||
var context = new PluginLoadContext(fileName, Path.GetDirectoryName(path)!);
|
||||
Assembly assembly = context.LoadFromFile(path);
|
||||
var exports = new Dictionary<string, IntPtr>(StringComparer.Ordinal);
|
||||
foreach (Type type in assembly.GetTypes())
|
||||
{
|
||||
foreach (MethodInfo m in type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.DeclaredOnly))
|
||||
{
|
||||
if (m.GetCustomAttribute<UnmanagedCallersOnlyAttribute>()?.EntryPoint is { Length: > 0 } entry)
|
||||
exports[entry] = m.MethodHandle.GetFunctionPointer();
|
||||
}
|
||||
}
|
||||
IntPtr handle;
|
||||
lock (Sync)
|
||||
{
|
||||
handle = (IntPtr)_nextHandle;
|
||||
_nextHandle += 2;
|
||||
Loaded[handle] = new Entry { Name = fileName, Exports = exports, Context = context };
|
||||
}
|
||||
RynthLog.Plugin($"ManagedPlugins: {fileName} loaded into its own collectible context ({exports.Count} exports).");
|
||||
return handle;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Plugin($"ManagedPlugins: FAILED to load {fileName}: {ex}");
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
#else
|
||||
RynthLog.Plugin($"ManagedPlugins: {fileName} is a managed plugin; it needs the CoreCLR engine (this is the NativeAOT one). Skipping.");
|
||||
return IntPtr.Zero;
|
||||
#endif
|
||||
}
|
||||
|
||||
private static readonly List<Entry> PendingUnload = new();
|
||||
|
||||
/// <summary>
|
||||
/// Retires a managed plugin (after its RynthPluginShutdown). Its context is only
|
||||
/// unloaded by <see cref="UnloadRetired"/> at the very end of the engine's shutdown:
|
||||
/// until then the plugin pump, the pop-outs' last frames and cached export pointers
|
||||
/// can still call into it, and once a context is unloaded any GC may free its code
|
||||
/// (2026-09-29: RynthAi's shutdown GC freed the others mid-teardown -> runtime abort).
|
||||
/// </summary>
|
||||
public static void Unload(IntPtr handle)
|
||||
{
|
||||
lock (Sync)
|
||||
{
|
||||
// Stays in Loaded (its exports still resolve) until UnloadRetired.
|
||||
if (Loaded.TryGetValue(handle, out Entry? e) && !PendingUnload.Contains(e))
|
||||
PendingUnload.Add(e);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Unloads every retired plugin's context. Last step of EngineLifecycle.Shutdown.</summary>
|
||||
public static void UnloadRetired()
|
||||
{
|
||||
List<Entry> retired;
|
||||
lock (Sync)
|
||||
{
|
||||
retired = new List<Entry>(PendingUnload);
|
||||
PendingUnload.Clear();
|
||||
foreach (var kv in new List<KeyValuePair<IntPtr, Entry>>(Loaded))
|
||||
if (retired.Contains(kv.Value)) Loaded.Remove(kv.Key);
|
||||
}
|
||||
#if ENGINE_CORECLR
|
||||
foreach (Entry e in retired)
|
||||
e.Context.Unload();
|
||||
if (retired.Count > 0)
|
||||
RynthLog.Plugin($"ManagedPlugins: {retired.Count} plugin context(s) unloading: {string.Join(", ", retired.ConvertAll(e => e.Name))}.");
|
||||
#endif
|
||||
}
|
||||
|
||||
#if ENGINE_CORECLR
|
||||
/// <summary>A plugin and its private dependencies (from the plugin's folder).</summary>
|
||||
private sealed class PluginLoadContext : AssemblyLoadContext
|
||||
{
|
||||
private readonly string _dir;
|
||||
|
||||
public PluginLoadContext(string name, string dir) : base("plugin " + name, isCollectible: true) => _dir = dir;
|
||||
|
||||
public Assembly LoadFromFile(string path)
|
||||
{
|
||||
// From streams, so the plugin's folder stays unlocked (rebuilds overwrite it).
|
||||
using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
||||
string pdb = Path.ChangeExtension(path, ".pdb");
|
||||
if (!File.Exists(pdb)) return LoadFromStream(fs);
|
||||
using var ps = new FileStream(pdb, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
||||
return LoadFromStream(fs, ps);
|
||||
}
|
||||
|
||||
private static readonly HashSet<string> PrivateFramework = new(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
"System.Text.Json", "System.Text.Encodings.Web", "System.IO.Pipelines",
|
||||
};
|
||||
|
||||
protected override Assembly? Load(AssemblyName name)
|
||||
{
|
||||
// The plugin's own dependencies (SDK, MoonSharp...) load privately; so do the
|
||||
// framework libraries that cache the types they see process-wide
|
||||
// (System.Text.Json roots a collectible context from the default one: Phase 0).
|
||||
// The rest of the framework comes from the default context.
|
||||
if (PrivateFramework.Contains(name.Name!))
|
||||
{
|
||||
string fx = Path.Combine(Path.GetDirectoryName(typeof(object).Assembly.Location)!, name.Name + ".dll");
|
||||
return File.Exists(fx) ? LoadFromAssemblyPath(fx) : null;
|
||||
}
|
||||
string candidate = Path.Combine(_dir, name.Name + ".dll");
|
||||
return File.Exists(candidate) ? LoadFromFile(candidate) : null;
|
||||
}
|
||||
|
||||
protected override IntPtr LoadUnmanagedDll(string unmanagedDllName)
|
||||
{
|
||||
string candidate = Path.Combine(_dir, unmanagedDllName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)
|
||||
? unmanagedDllName
|
||||
: unmanagedDllName + ".dll");
|
||||
return File.Exists(candidate) ? LoadUnmanagedDllFromPath(candidate) : IntPtr.Zero;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
|
@ -581,8 +581,8 @@ internal struct RynthCoreAPI
|
|||
public IntPtr SendPluginCommandFn;
|
||||
|
||||
/// <summary>Function pointer: int GetObjectDataIdProperty(uint objectId, uint stype, uint* value)
|
||||
/// Reads a STypeDID property that lives in the object's PublicWeenieDesc (currently Icon=8 →
|
||||
/// _iconID). Read directly from the embedded PWD struct — network-populated, so it works on
|
||||
/// Reads a STypeDID property that lives in the object's PublicWeenieDesc (Icon=8 → _iconID;
|
||||
/// since 2026-09-30 also IconOverlay=50 and IconUnderlay=52, 0 = none). Read directly from the embedded PWD struct — network-populated, so it works on
|
||||
/// UNequipped/never-appraised pack items with no qualities pointer and no main-thread native
|
||||
/// call. Returns 1 on success (value = the DataID, e.g. 0x06xxxxxx), 0 otherwise. Requires API
|
||||
/// v65+. APPENDED-AT-END for ABI safety.</summary>
|
||||
|
|
@ -634,6 +634,229 @@ internal struct RynthCoreAPI
|
|||
/// Fills the state of the most recent VendorBuy/VendorSell request. Returns 1 if a
|
||||
/// request has been made this session, 0 if not. Any thread. Requires API v67+.</summary>
|
||||
public IntPtr GetVendorTradeStatusFn;
|
||||
|
||||
/// <summary>Function pointer: void* GetPluginInterface(const char* pluginName, const char* iface, uint version)
|
||||
/// Asks a named plugin for a typed interface table (e.g. RynthAi's "RynthAi.Script" v1 for
|
||||
/// RynthLua) through the fixed-signature export
|
||||
/// <c>void* RynthPluginQueryInterface(const char* iface, uint version)</c>. Null when the plugin
|
||||
/// isn't loaded or doesn't offer it. The table belongs to the target plugin; call its functions
|
||||
/// only from the plugin pump thread. Requires API v68+.</summary>
|
||||
public IntPtr GetPluginInterfaceFn;
|
||||
|
||||
/// <summary>v69: <c>int GetLiveObjectIds(uint* buffer, int capacity)</c>: copies up to
|
||||
/// <paramref name="capacity"/> ids of the objects in the client's object table (the engine's
|
||||
/// snapshot, refreshed on the game thread) and returns the total count, so a caller whose
|
||||
/// buffer was too small can retry with a bigger one. Requires API v69+.</summary>
|
||||
public IntPtr GetLiveObjectIdsFn;
|
||||
|
||||
// ── v70: action outcomes and wield-to-slot ──────────────────────────
|
||||
// Since v70 the engine also raises RynthPluginOnEnchantmentAdded / Removed (the
|
||||
// player's enchantment GameEvents 0x02C2-0x02C8 and 0x0312; see SmartBoxHooks).
|
||||
|
||||
/// <summary>v70: <c>int GetLastUseDone(int* seq, uint* error)</c>: the most recent server
|
||||
/// UseDone (GameEvent 0x01C7): its sequence number (the same count GetUseDoneSeq returns)
|
||||
/// and its WeenieError code (0 = the action completed; e.g. 0x1D YoureTooBusy, 0x400
|
||||
/// YouDontHaveAllTheComponents). Both come from one atomic snapshot, so they always belong
|
||||
/// together. Returns 1 when the engine watches UseDone (seq 0 = none yet), 0 when it can't.
|
||||
/// Any thread. Requires API v70+.</summary>
|
||||
public IntPtr GetLastUseDoneFn;
|
||||
|
||||
/// <summary>v70: <c>int GetLastWeenieError(int* seq, uint* error, uint* eventType, uint* objectId)</c>:
|
||||
/// the most recent refusal the server sent: WeenieError (eventType 0x028A, e.g. 0x402
|
||||
/// YourSpellFizzled — a fizzled cast still ends with UseDone(0)), WeenieErrorWithString
|
||||
/// (0x028B) or InventoryServerSaveFailed (0x00A0, objectId = the item). seq counts them
|
||||
/// (0 = none yet). Returns 1 when the engine watches these, 0 when it can't. Any thread.
|
||||
/// Requires API v70+.</summary>
|
||||
public IntPtr GetLastWeenieErrorFn;
|
||||
|
||||
/// <summary>v70: <c>int WieldItem(uint objectId, uint equipMask)</c>: wield the item into the
|
||||
/// given EquipMask slot(s) (the 0x001A GetAndWieldItem game action, as a paperdoll drag
|
||||
/// sends it; e.g. 0x00200000 Shield, 0x00100000 MeleeWeapon). Queued for AC's main thread
|
||||
/// when called from another thread. Returns 1 if sent or queued. The server answers with
|
||||
/// the wield or InventoryServerSaveFailed (see GetLastWeenieError). Requires API v70+.</summary>
|
||||
public IntPtr WieldItemFn;
|
||||
|
||||
// ── v71: script windows (docs: RynthSuite Docs/RYNTHLUA_WINDOWS_DESIGN.md §4) ──
|
||||
// A plugin draws ImGui windows by pushing a display list; the engine replays it every
|
||||
// frame on AC's thread and sends input back as events. The engine never calls into the
|
||||
// plugin for this and never keeps `data` / `buffer`: bytes are copied during the call.
|
||||
|
||||
/// <summary>v71: <c>int UiSubmit(const uint8_t* data, int length)</c>: the owner's complete
|
||||
/// window set (display-list format 1, UI/ScriptWindows/DisplayListParser.cs). Only from the
|
||||
/// plugin's own tick or event on the pump thread. Returns 0, or -1 malformed, -2 not called
|
||||
/// from a dispatch, -3 over a limit (nothing applied), -4 unsupported format version.
|
||||
/// Requires API v71+.</summary>
|
||||
public IntPtr UiSubmitFn;
|
||||
|
||||
/// <summary>v71: <c>int UiPollEvents(uint8_t* buffer, int capacity, int* remaining)</c>:
|
||||
/// copies whole events (never a partial one) and returns the bytes written;
|
||||
/// <c>*remaining</c> = events still queued. Same thread rule as UiSubmit. Requires API v71+.</summary>
|
||||
public IntPtr UiPollEventsFn;
|
||||
|
||||
/// <summary>v71: <c>int UiGetInfo(UiInfoNative* info)</c>: the caller sets info->Size to the
|
||||
/// size it knows; the engine fills up to that and returns the bytes written (0 when there is
|
||||
/// no ImGui). Any thread. Requires API v71+.</summary>
|
||||
public IntPtr UiGetInfoFn;
|
||||
|
||||
// ── v72: player-to-player trade (docs: Compatibility/PlayerTrade.cs) ──
|
||||
// The state comes from the server's trade GameEvents, read in the existing game-event
|
||||
// detour on AC's main thread; plugins poll it (Generation / Sequence / counters tell them
|
||||
// what changed). The actions go through the client's own CM_Trade / ClientTradeSystem
|
||||
// functions and are queued for AC's main thread when called from another thread.
|
||||
|
||||
/// <summary>v72: <c>int GetTradeState(TradeStateNative* state)</c>: the caller sets
|
||||
/// state->Size to the size it knows; the engine fills up to that and returns the bytes
|
||||
/// written (0 on a bad argument). Any thread. Requires API v72+.</summary>
|
||||
public IntPtr GetTradeStateFn;
|
||||
|
||||
/// <summary>v72: <c>int GetTradeItems(int side, uint* buffer, int capacity)</c>: copies up to
|
||||
/// <paramref name="capacity"/> item ids from one side of the window (1 = yours, 2 = the
|
||||
/// partner's) and returns that side's total count; -1 for a bad side. Any thread.
|
||||
/// Requires API v72+.</summary>
|
||||
public IntPtr GetTradeItemsFn;
|
||||
|
||||
/// <summary>v72: <c>int TradeOpen(uint targetId)</c>: ask a player to trade (0x01F6
|
||||
/// OpenTradeNegotiations; the server walks you into range). Returns 1 if sent or queued.
|
||||
/// Requires API v72+.</summary>
|
||||
public IntPtr TradeOpenFn;
|
||||
|
||||
/// <summary>v72: <c>int TradeAdd(uint itemId, uint slot)</c>: put one of your items in the
|
||||
/// open trade window (0x01F8 AddToTrade; slot 0 = next free). The server answers with
|
||||
/// AddToTrade or TradeFailure (see GetTradeState). Returns 1 if sent or queued.
|
||||
/// Requires API v72+.</summary>
|
||||
public IntPtr TradeAddFn;
|
||||
|
||||
/// <summary>v72: <c>int TradeAccept(void)</c>: accept the trade as it stands (the window's
|
||||
/// Accept button, 0x01FA). Returns 1 if sent or queued. Requires API v72+.</summary>
|
||||
public IntPtr TradeAcceptFn;
|
||||
|
||||
/// <summary>v72: <c>int TradeDecline(void)</c>: withdraw your acceptance (0x01FB).
|
||||
/// Returns 1 if sent or queued. Requires API v72+.</summary>
|
||||
public IntPtr TradeDeclineFn;
|
||||
|
||||
/// <summary>v72: <c>int TradeReset(void)</c>: empty both sides of the window (0x0204).
|
||||
/// Returns 1 if sent or queued. Requires API v72+.</summary>
|
||||
public IntPtr TradeResetFn;
|
||||
|
||||
/// <summary>v72: <c>int TradeClose(void)</c>: end the trade (0x01F7 CloseTradeNegotiations).
|
||||
/// Returns 1 if sent or queued. Requires API v72+.</summary>
|
||||
public IntPtr TradeCloseFn;
|
||||
|
||||
/// <summary>v73: <c>int GetObjectInstanceIdProperty(uint objectId, uint stype, uint* value)</c>:
|
||||
/// a PropertyInstanceId (another object's id: Container 2, Wielder 3, Monarch 26, HouseOwner 32,
|
||||
/// PetOwner 44, the player's Allegiance/Patron/..., anything an UpdatePropertyInstanceID set).
|
||||
/// Any thread; served from the engine's caches and PublicWeenieDesc snapshot. 1 = found (non-zero).
|
||||
/// Requires API v73+.</summary>
|
||||
public IntPtr GetObjectInstanceIdPropertyFn;
|
||||
|
||||
/// <summary>v74: <c>int GetVTankState(int* sequence)</c>: VTank's macro, as the Decal bridge
|
||||
/// sees it (Compatibility/VTankWatch.cs; signal = VTank's documented /vt start and /vt stop
|
||||
/// through Decal's chat parser). Returns flags: bit0 = the engine watches (Decal bridge mode),
|
||||
/// bit1 = VTank's macro is running. 0 without Decal. <c>*sequence</c> (may be null) is bumped
|
||||
/// on every change. Any thread. Requires API v74+.</summary>
|
||||
public IntPtr GetVTankStateFn;
|
||||
|
||||
/// <summary>v75: <c>int GetCharacterTitles(uint* ids, int maxCount, uint* currentTitle)</c>: the
|
||||
/// titles the player holds, from the server's title events (0x0029 at login, 0x002B per new
|
||||
/// title; Compatibility/CharacterTitles.cs). Copies up to maxCount ids (ids may be null to
|
||||
/// ask for the count) and returns how many the character holds, or -1 when the list isn't
|
||||
/// known for the current character. *currentTitle (may be null) = the displayed title.
|
||||
/// Any thread. Requires API v75+.</summary>
|
||||
public IntPtr GetCharacterTitlesFn;
|
||||
|
||||
/// <summary>v75: <c>int GetServerInfo(byte* worldName, int capacity)</c>: which server this
|
||||
/// is (Compatibility/ServerInfo.cs). Returns flags: bit0 = Aelrynth (host, announced world
|
||||
/// name or the Bank mod's properties), bit1 = Aelrynth's staging world, bit2 = the server
|
||||
/// announced its world name, which is then copied to worldName (UTF-8, NUL-terminated, cut
|
||||
/// to capacity - 1; worldName may be null). Never the launcher's profile name. Any thread.
|
||||
/// Requires API v75+.</summary>
|
||||
public IntPtr GetServerInfoFn;
|
||||
}
|
||||
|
||||
/// <summary>v72 <see cref="TradeStateNative.Flags"/> bits.</summary>
|
||||
internal static class TradeStateFlags
|
||||
{
|
||||
public const uint Open = 1u << 0;
|
||||
public const uint YouAccepted = 1u << 1;
|
||||
public const uint PartnerAccepted = 1u << 2;
|
||||
/// <summary>The engine sees the trade GameEvents (its game-event hook is installed).</summary>
|
||||
public const uint Watching = 1u << 3;
|
||||
/// <summary>All six trade actions are bound on this client.</summary>
|
||||
public const uint ActionsAvailable = 1u << 4;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// v72 <c>GetTradeState</c> result. Pack 4, 96 bytes; later versions only append.
|
||||
/// Mirrored by RynthCore.PluginSdk (TradeStateNative in RynthCoreApiNative.cs).
|
||||
/// </summary>
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
||||
internal unsafe struct TradeStateNative
|
||||
{
|
||||
/// <summary>In: the caller's sizeof. Out: bytes written.</summary>
|
||||
public uint Size;
|
||||
/// <summary><see cref="TradeStateFlags"/>.</summary>
|
||||
public uint Flags;
|
||||
/// <summary>+1 for every trade that opens (RegisterTrade).</summary>
|
||||
public uint Generation;
|
||||
/// <summary>+1 for every trade event (and TradeComplete).</summary>
|
||||
public uint Sequence;
|
||||
/// <summary>The other player; 0 when no trade is open.</summary>
|
||||
public uint PartnerId;
|
||||
/// <summary>Who opened the trade.</summary>
|
||||
public uint InitiatorId;
|
||||
public int SelfItemCount;
|
||||
public int PartnerItemCount;
|
||||
/// <summary>The last trade GameEvent type (0x01FD-0x0208).</summary>
|
||||
public uint LastEventType;
|
||||
/// <summary>TradeFailure events so far; the last one's item and WeenieError follow.</summary>
|
||||
public uint FailureCount;
|
||||
public uint LastFailureItemId;
|
||||
public uint LastFailureReason;
|
||||
/// <summary>EndTradeReason of the last CloseTrade: 1 normal, 2 entered combat, 0x51 cancelled.</summary>
|
||||
public uint LastCloseReason;
|
||||
public uint LastAcceptedBy;
|
||||
public uint LastDeclinedBy;
|
||||
public uint LastResetBy;
|
||||
/// <summary>Trades completed so far (WeenieError 0x0529 TradeComplete).</summary>
|
||||
public uint CompletedCount;
|
||||
/// <summary>Times the partner has accepted so far (AcceptTrade from the partner).</summary>
|
||||
public uint PartnerAcceptCount;
|
||||
public fixed uint Reserved[6];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// v71 <c>UiGetInfo</c> result. Pack 4, 480 bytes in format 1; later versions only append.
|
||||
/// Mirrored by RynthCore.PluginSdk (UiInfoNative in RynthCoreApiNative.cs).
|
||||
/// </summary>
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
||||
internal unsafe struct UiInfoNative
|
||||
{
|
||||
/// <summary>In: the caller's sizeof. Out: bytes written.</summary>
|
||||
public uint Size;
|
||||
/// <summary>bit0 ImGui available, bit1 in world, bit2 pop-outs available.</summary>
|
||||
public uint Flags;
|
||||
/// <summary>Highest display-list format the engine replays.</summary>
|
||||
public ushort MaxFormatVersion;
|
||||
/// <summary>The ops replayed within MaxFormatVersion: 2 = + Image, ImageButton, InputInt, InputFloat,
|
||||
/// DragInt, DragFloat (2026-09-30). 0 on older engines (the field was reserved) = Phase 1 ops only.</summary>
|
||||
public ushort OpLevel;
|
||||
public uint MaxOpsPerWindow;
|
||||
public uint MaxBytesPerWindow;
|
||||
public uint MaxWindowsPerOwner;
|
||||
public uint MaxBytesPerSubmit;
|
||||
public float DisplayWidth;
|
||||
public float DisplayHeight;
|
||||
public float UiScale;
|
||||
public float TextLineHeight;
|
||||
public float FrameHeight;
|
||||
public float ItemSpacingX;
|
||||
public float ItemSpacingY;
|
||||
public float FramePaddingX;
|
||||
public float FramePaddingY;
|
||||
/// <summary>Default font advance of ' '..'~' (95), pixels at UiScale.</summary>
|
||||
public fixed float AsciiAdvance[95];
|
||||
public uint FrameCounter;
|
||||
public fixed uint Reserved[8];
|
||||
}
|
||||
|
||||
// ─── Vendor trading ABI structs (v67) ───────────────────────────────────
|
||||
|
|
@ -735,7 +958,7 @@ internal unsafe struct VendorTradeStatusNative
|
|||
/// <summary>Current API version. Bump when adding fields to RynthCoreAPI.</summary>
|
||||
internal static class PluginContractVersion
|
||||
{
|
||||
public const uint Current = 67;
|
||||
public const uint Current = 75;
|
||||
}
|
||||
|
||||
internal static class ClientActionHookFlags
|
||||
|
|
@ -1188,6 +1411,45 @@ internal unsafe delegate int GetObjectDataIdPropertyCallbackDelegate(uint object
|
|||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate IntPtr GetPluginExportJsonCallbackDelegate(IntPtr pluginNameAnsi, IntPtr exportNameAnsi);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate IntPtr GetPluginInterfaceCallbackDelegate(IntPtr pluginNameAnsi, IntPtr ifaceAnsi, uint version);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int GetLiveObjectIdsCallbackDelegate(uint* buffer, int capacity);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int GetLastUseDoneCallbackDelegate(int* seq, uint* error);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int GetLastWeenieErrorCallbackDelegate(int* seq, uint* error, uint* eventType, uint* objectId);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int WieldItemCallbackDelegate(uint objectId, uint equipMask);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int UiSubmitCallbackDelegate(byte* data, int length);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int UiPollEventsCallbackDelegate(byte* buffer, int capacity, int* remaining);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int UiGetInfoCallbackDelegate(UiInfoNative* info);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int GetTradeStateCallbackDelegate(TradeStateNative* state);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int GetTradeItemsCallbackDelegate(int side, uint* buffer, int capacity);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int TradeOpenCallbackDelegate(uint targetId);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int TradeAddCallbackDelegate(uint itemId, uint slot);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate int TradeSimpleCallbackDelegate();
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int GetVendorInfoCallbackDelegate(VendorInfoNative* info);
|
||||
|
||||
|
|
@ -1202,3 +1464,12 @@ internal unsafe delegate uint VendorSellCallbackDelegate(uint vendorId, uint* it
|
|||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int GetVendorTradeStatusCallbackDelegate(VendorTradeStatusNative* status);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int GetVTankStateCallbackDelegate(int* sequence);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int GetCharacterTitlesCallbackDelegate(uint* ids, int maxCount, uint* currentTitle);
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal unsafe delegate int GetServerInfoCallbackDelegate(byte* worldName, int capacity);
|
||||
|
|
|
|||
|
|
@ -19,8 +19,11 @@ internal static class PluginLoader
|
|||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool FreeLibrary(IntPtr hModule);
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
|
||||
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
private static extern IntPtr GetModuleHandleW(string lpModuleName);
|
||||
|
||||
// Managed plugins (CoreCLR engine) answer from their export map; see ManagedPlugins.
|
||||
private static IntPtr GetProcAddress(IntPtr hModule, string lpProcName) => ManagedPlugins.GetProcAddress(hModule, lpProcName);
|
||||
|
||||
/// <summary>
|
||||
/// Scans <paramref name="pluginsDir"/> for *.dll files, loads each one,
|
||||
|
|
@ -86,6 +89,11 @@ internal static class PluginLoader
|
|||
/// </summary>
|
||||
public static void Unload(LoadedPlugin plugin)
|
||||
{
|
||||
if (ManagedPlugins.IsManagedHandle(plugin.ModuleHandle))
|
||||
{
|
||||
ManagedPlugins.Unload(plugin.ModuleHandle); // a managed plugin really goes away
|
||||
return;
|
||||
}
|
||||
if (plugin.ModuleHandle != IntPtr.Zero)
|
||||
{
|
||||
RynthLog.Verbose($"PluginLoader: Skipping FreeLibrary on {plugin.FileName} (NativeAOT — module pages leaked intentionally).");
|
||||
|
|
@ -308,22 +316,40 @@ internal static class PluginLoader
|
|||
RynthLog.Verbose($"PluginLoader: Loading {fileName}...");
|
||||
|
||||
string shadowPath;
|
||||
try
|
||||
IntPtr handle;
|
||||
bool reused = false;
|
||||
if (ManagedPlugins.IsManagedAssembly(sourcePath))
|
||||
{
|
||||
shadowPath = CreateShadowCopy(sourcePath, sessionShadowDir);
|
||||
// A managed plugin: loaded fresh (from streams, no shadow copy) into its own
|
||||
// collectible context every time; nothing to reuse, nothing leaked.
|
||||
shadowPath = sourcePath;
|
||||
handle = ManagedPlugins.Load(sourcePath);
|
||||
if (handle == IntPtr.Zero)
|
||||
return null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
else if (reused = TryFindLoadedCopy(sourcePath, sessionShadowDir, out handle, out shadowPath))
|
||||
{
|
||||
RynthLog.Plugin($"PluginLoader: FAILED to stage {fileName} ({ex.Message})");
|
||||
return null;
|
||||
RynthLog.Plugin($"PluginLoader: {fileName} unchanged - reusing the copy already loaded from '{shadowPath}' (no new runtime).");
|
||||
}
|
||||
else
|
||||
{
|
||||
try
|
||||
{
|
||||
shadowPath = CreateShadowCopy(sourcePath, sessionShadowDir);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Plugin($"PluginLoader: FAILED to stage {fileName} ({ex.Message})");
|
||||
return null;
|
||||
}
|
||||
|
||||
IntPtr handle = LoadLibraryW(shadowPath);
|
||||
if (handle == IntPtr.Zero)
|
||||
{
|
||||
int err = Marshal.GetLastWin32Error();
|
||||
RynthLog.Plugin($"PluginLoader: FAILED to load {fileName} (Win32 error {err})");
|
||||
return null;
|
||||
handle = LoadLibraryW(shadowPath);
|
||||
if (handle == IntPtr.Zero)
|
||||
{
|
||||
int err = Marshal.GetLastWin32Error();
|
||||
RynthLog.Plugin($"PluginLoader: FAILED to load {fileName} (Win32 error {err})");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve required exports
|
||||
|
|
@ -333,7 +359,8 @@ internal static class PluginLoader
|
|||
if (initPtr == IntPtr.Zero || shutdownPtr == IntPtr.Zero)
|
||||
{
|
||||
RynthLog.Plugin($"PluginLoader: {fileName} missing required exports (RynthPluginInit/RynthPluginShutdown) — skipping.");
|
||||
FreeLibrary(handle);
|
||||
if (ManagedPlugins.IsManagedHandle(handle)) ManagedPlugins.Unload(handle);
|
||||
else if (!reused) FreeLibrary(handle);
|
||||
return null;
|
||||
}
|
||||
|
||||
|
|
@ -507,6 +534,59 @@ internal static class PluginLoader
|
|||
return plugin;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A copy of <paramref name="sourcePath"/> that an earlier engine generation (or
|
||||
/// plugin rescan) of this process loaded and that is byte-for-byte the same
|
||||
/// file: re-initialize that module instead of loading a new one. A NativeAOT
|
||||
/// DLL can never be unloaded, so every fresh copy keeps a whole runtime and its
|
||||
/// GC heap in acclient's 4 GB for good; before this an engine hot-reload
|
||||
/// loaded all six plugins again and cost ~600 MB (2026-09-28). A plugin's
|
||||
/// RynthPluginRuntime builds a new plugin object on every Init, so a reused
|
||||
/// module starts clean apart from its static caches.
|
||||
/// </summary>
|
||||
private static bool TryFindLoadedCopy(string sourcePath, string sessionShadowDir, out IntPtr handle, out string shadowPath)
|
||||
{
|
||||
handle = IntPtr.Zero;
|
||||
shadowPath = "";
|
||||
try
|
||||
{
|
||||
string fileName = Path.GetFileName(sourcePath);
|
||||
string? root = Path.GetDirectoryName(sessionShadowDir);
|
||||
if (root == null || !Directory.Exists(root)) return false;
|
||||
string mine = Path.GetFullPath(sessionShadowDir);
|
||||
var sourceInfo = new FileInfo(sourcePath);
|
||||
byte[]? source = null;
|
||||
|
||||
foreach (string dir in Directory.GetDirectories(root, $"session-*-pid{Environment.ProcessId}-*"))
|
||||
{
|
||||
if (string.Equals(Path.GetFullPath(dir), mine, StringComparison.OrdinalIgnoreCase)) continue;
|
||||
string candidate = Path.Combine(dir, fileName);
|
||||
var info = new FileInfo(candidate);
|
||||
if (!info.Exists || info.Length != sourceInfo.Length) continue;
|
||||
IntPtr h = GetModuleHandleW(candidate);
|
||||
if (h == IntPtr.Zero) continue;
|
||||
source ??= ReadShared(sourcePath);
|
||||
if (!source.AsSpan().SequenceEqual(ReadShared(candidate))) continue;
|
||||
handle = h;
|
||||
shadowPath = candidate;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
RynthLog.Plugin($"PluginLoader: reuse check for {Path.GetFileName(sourcePath)} failed ({ex.GetType().Name}: {ex.Message}) - loading a new copy.");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static byte[] ReadShared(string path)
|
||||
{
|
||||
using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
||||
var bytes = new byte[fs.Length];
|
||||
fs.ReadExactly(bytes);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
private static string PrepareShadowDirectory(string shadowRootDir, int generation)
|
||||
{
|
||||
// Include EntryPoint.InitCount so each engine instance gets its own
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
Loading…
Reference in a new issue