From 2c3d2410a87cdbdd85bcb2069fe059ad99186fdf Mon Sep 17 00:00:00 2001 From: tombohar Date: Wed, 22 Apr 2026 21:28:29 -0400 Subject: [PATCH 01/11] Add radar rect API, jump primitives, account profile tweaks - Hook gmRadarUI::DrawObjects to capture the UI singleton; expose host.TryGetRadarRect via UIElement::GetSurfaceBox (API v53). - Plumb CommenceJump/DoJump/LaunchJumpWithMotion through ClientActionHooks and PlayerPhysicsHooks. - Account profile dialog + LaunchAccountProfile adjustments. - Viewport platform backend tweak. --- .../AccountProfileDialog.axaml.cs | 15 +- .../MainWindow.axaml.cs | 35 +++- src/RynthCore.App/LaunchAccountProfile.cs | 7 +- .../Compatibility/ClientActionHooks.cs | 15 ++ .../Compatibility/CommandInterpreterHooks.cs | 32 ++++ .../Compatibility/PlayerPhysicsHooks.cs | 159 ++++++++++++++++++ .../Compatibility/RadarHooks.cs | 135 +++++++++++++++ src/RynthCore.Engine/EntryPoint.cs | 1 + .../ImGui/ViewportPlatformBackend.cs | 16 +- .../Plugins/PluginContract.cs | 38 ++++- src/RynthCore.Engine/Plugins/PluginManager.cs | 39 +++++ src/RynthCore.PluginSdk/RynthCoreApiNative.cs | 4 + src/RynthCore.PluginSdk/RynthCoreHost.cs | 59 +++++++ 13 files changed, 540 insertions(+), 15 deletions(-) create mode 100644 src/RynthCore.Engine/Compatibility/RadarHooks.cs diff --git a/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml.cs b/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml.cs index b6538cf..44ed1e8 100644 --- a/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml.cs +++ b/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml.cs @@ -55,16 +55,23 @@ internal partial class AccountProfileDialog : Window private void PopulateCharacterDropdown(string accountName, string serverName, string selectedCharacter) { List chars = LoadDetectedCharacters(accountName, serverName); - if (string.IsNullOrWhiteSpace(selectedCharacter) && chars.Count == 1) - selectedCharacter = chars[0]; // Ensure the existing saved name appears even if the scan file is empty - if (!string.IsNullOrEmpty(selectedCharacter) && !chars.Contains(selectedCharacter)) + if (!string.IsNullOrEmpty(selectedCharacter) + && selectedCharacter != LaunchAccountProfile.NoneOption + && !chars.Contains(selectedCharacter)) + { chars.Insert(0, selectedCharacter); + } + + // "(None)" sentinel at the top so users can opt out of auto-login per account + chars.Insert(0, LaunchAccountProfile.NoneOption); CharacterBox.ItemsSource = chars; - if (!string.IsNullOrEmpty(selectedCharacter) && chars.Contains(selectedCharacter)) + if (string.IsNullOrEmpty(selectedCharacter) || selectedCharacter == LaunchAccountProfile.NoneOption) + CharacterBox.SelectedItem = LaunchAccountProfile.NoneOption; + else if (chars.Contains(selectedCharacter)) CharacterBox.SelectedItem = selectedCharacter; } diff --git a/src/RynthCore.App.Avalonia/MainWindow.axaml.cs b/src/RynthCore.App.Avalonia/MainWindow.axaml.cs index 5ba19a2..8cdbaca 100644 --- a/src/RynthCore.App.Avalonia/MainWindow.axaml.cs +++ b/src/RynthCore.App.Avalonia/MainWindow.axaml.cs @@ -607,11 +607,20 @@ internal partial class MainWindow : Window } // Preserve any already-saved character name even if scan hasn't seen it yet - if (!string.IsNullOrEmpty(account.CharacterName) && !dropdownItems.Contains(account.CharacterName)) + if (!string.IsNullOrEmpty(account.CharacterName) + && account.CharacterName != LaunchAccountProfile.NoneOption + && !dropdownItems.Contains(account.CharacterName)) + { dropdownItems.Insert(0, account.CharacterName); + } + + // "(None)" at the top — selecting it opts out of auto-login for this account + dropdownItems.Insert(0, LaunchAccountProfile.NoneOption); charDropdown.ItemsSource = dropdownItems; - if (!string.IsNullOrEmpty(account.CharacterName) && dropdownItems.Contains(account.CharacterName)) + if (account.CharacterName == LaunchAccountProfile.NoneOption) + charDropdown.SelectedItem = LaunchAccountProfile.NoneOption; + else if (!string.IsNullOrEmpty(account.CharacterName) && dropdownItems.Contains(account.CharacterName)) charDropdown.SelectedItem = account.CharacterName; charDropdown.SelectionChanged += (_, _) => @@ -1595,16 +1604,26 @@ internal partial class MainWindow : Window if (!_launchTargetCharacterDropdowns.TryGetValue(account.Id, out ComboBox? dropdown)) continue; - if (!string.IsNullOrWhiteSpace(account.CharacterName) && !detectedCharacters.Contains(account.CharacterName)) + if (!string.IsNullOrWhiteSpace(account.CharacterName) + && account.CharacterName != LaunchAccountProfile.NoneOption + && !detectedCharacters.Contains(account.CharacterName)) + { detectedCharacters.Insert(0, account.CharacterName); + } + + // "(None)" at the top — selecting it opts out of auto-login for this account + detectedCharacters.Insert(0, LaunchAccountProfile.NoneOption); _suppressLaunchTargetCharacterSelectionChanged = true; try { dropdown.ItemsSource = detectedCharacters; - dropdown.SelectedItem = !string.IsNullOrWhiteSpace(account.CharacterName) && detectedCharacters.Contains(account.CharacterName) - ? account.CharacterName - : null; + if (account.CharacterName == LaunchAccountProfile.NoneOption) + dropdown.SelectedItem = LaunchAccountProfile.NoneOption; + else + dropdown.SelectedItem = !string.IsNullOrWhiteSpace(account.CharacterName) && detectedCharacters.Contains(account.CharacterName) + ? account.CharacterName + : null; } finally { @@ -1621,6 +1640,10 @@ internal partial class MainWindow : Window private string ResolveTargetCharacterForLaunch(LaunchAccountProfile account, LaunchServerProfile? server) { + // User explicitly opted out of auto-login → blank target so engine skips it. + if (account.CharacterName == LaunchAccountProfile.NoneOption) + return string.Empty; + List detectedCharacters = GetDetectedCharacters(account.AccountName, server?.Name ?? string.Empty); string bestKnownCharacter = GetPreferredCharacterName(account, server, null, null, detectedCharacters); if (!string.IsNullOrWhiteSpace(bestKnownCharacter) && diff --git a/src/RynthCore.App/LaunchAccountProfile.cs b/src/RynthCore.App/LaunchAccountProfile.cs index d89f267..ed6c24a 100644 --- a/src/RynthCore.App/LaunchAccountProfile.cs +++ b/src/RynthCore.App/LaunchAccountProfile.cs @@ -4,6 +4,11 @@ namespace RynthCore.App; internal sealed class LaunchAccountProfile { + /// Sentinel stored in CharacterName when the user has explicitly opted out of auto-login. + /// At launch time, ResolveTargetCharacterForLaunch translates this to an empty string so + /// the engine's CharacterCapture sees a blank TargetCharacter and skips auto-login entirely. + public const string NoneOption = "(None — no auto-login)"; + public string Id { get; set; } = Guid.NewGuid().ToString("N"); public string AccountName { get; set; } = string.Empty; public string Password { get; set; } = string.Empty; @@ -15,7 +20,7 @@ internal sealed class LaunchAccountProfile { get { - string launchLabel = !string.IsNullOrWhiteSpace(CharacterName) + string launchLabel = !string.IsNullOrWhiteSpace(CharacterName) && CharacterName != NoneOption ? CharacterName : Alias; diff --git a/src/RynthCore.Engine/Compatibility/ClientActionHooks.cs b/src/RynthCore.Engine/Compatibility/ClientActionHooks.cs index ecedb46..e79042d 100644 --- a/src/RynthCore.Engine/Compatibility/ClientActionHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ClientActionHooks.cs @@ -136,6 +136,21 @@ internal static class ClientActionHooks return CommandInterpreterHooks.TapJump(); } + public static bool CommenceJump() + { + return CommandInterpreterHooks.CommenceJump(); + } + + public static bool DoJump(bool autonomous) + { + return CommandInterpreterHooks.DoJump(autonomous); + } + + public static bool LaunchJumpWithMotion(bool shift, bool holdW, bool holdX, bool holdZ, bool holdC) + { + return PlayerPhysicsHooks.LaunchJumpWithMotion(shift, holdW, holdX, holdZ, holdC); + } + public static bool SetMotion(uint motion, bool enabled) { return CommandInterpreterHooks.SetMotion(motion, enabled); diff --git a/src/RynthCore.Engine/Compatibility/CommandInterpreterHooks.cs b/src/RynthCore.Engine/Compatibility/CommandInterpreterHooks.cs index 956a644..832717e 100644 --- a/src/RynthCore.Engine/Compatibility/CommandInterpreterHooks.cs +++ b/src/RynthCore.Engine/Compatibility/CommandInterpreterHooks.cs @@ -244,6 +244,38 @@ internal static class CommandInterpreterHooks } } + public static bool CommenceJump() + { + if (!TryBindDelegates()) + return false; + + try + { + _commenceJump!(_boundCmdInterp); + return true; + } + catch + { + return false; + } + } + + public static bool DoJump(bool autonomous) + { + if (!TryBindDelegates()) + return false; + + try + { + _doJump!(_boundCmdInterp, autonomous ? 1 : 0); + return true; + } + catch + { + return false; + } + } + private static bool TryBindDelegates() { IntPtr selectedStaticAddr = IntPtr.Zero; diff --git a/src/RynthCore.Engine/Compatibility/PlayerPhysicsHooks.cs b/src/RynthCore.Engine/Compatibility/PlayerPhysicsHooks.cs index 3d73436..3bd166f 100644 --- a/src/RynthCore.Engine/Compatibility/PlayerPhysicsHooks.cs +++ b/src/RynthCore.Engine/Compatibility/PlayerPhysicsHooks.cs @@ -17,15 +17,43 @@ internal static class PlayerPhysicsHooks private const int ReferencePhysicsGetHeading = 0x00512010; private const int ReferencePhysicsSetHeading = 0x00514C60; + // CPhysicsObj::m_pMovementManager lives at +0xC4 (same offset UB's Jumper uses). + // The CMotionInterp pointer is the first field of MovementManager. + private const int MovementManagerOffset = 0xC4; + + // CMotionInterp::get_max_speed — Chorizite RVA 0x001278C0, our client is +0x1000 + // from Chorizite (confirmed via set_heading/get_heading/CommenceJump addresses). + private const int ReferenceGetMaxSpeed = 0x005288C0; + + // Fields in CMotionInterp holding the "current motion command" for each + // channel. Writing these right before DoJump tells the physics simulation + // to launch the jump with that velocity baked in. + private const int CMotionForwardIdOffset = 76; // 0x4C + private const int CMotionForwardSpeedOffset = 80; // 0x50 + private const int CMotionStrafeIdOffset = 84; // 0x54 + private const int CMotionStrafeSpeedOffset = 88; // 0x58 + private const int CMotionTurnOffset = 92; // 0x5C + + // Raw motion-command IDs the physics simulation reads from CMotionInterp. + // Sourced from UB's UBHelper.Jumper — these are *not* the SetMotion IDs. + private const int MotionIdForward = 0x44000007; + private const int MotionIdBackward = 0x45000005; + private const int MotionIdIdle = 0x41000003; + private const int MotionIdSidestep = 0x6500000F; + [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate float PhysicsGetHeadingDelegate(IntPtr physicsObjPtr); [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate void PhysicsSetHeadingDelegate(IntPtr physicsObjPtr, float headingDegrees, int sendEvent); + [UnmanagedFunctionPointer(CallingConvention.ThisCall)] + private delegate double GetMaxSpeedDelegate(IntPtr cmotionInterpPtr); + private static string _statusMessage = "Not probed yet."; private static PhysicsGetHeadingDelegate? _getHeading; private static PhysicsSetHeadingDelegate? _setHeading; + private static GetMaxSpeedDelegate? _getMaxSpeed; public static bool IsInitialized { get; private set; } public static bool HasGetHeading => _getHeading != null; @@ -185,6 +213,137 @@ internal static class PlayerPhysicsHooks } } + public static bool HasLaunchJumpWithMotion => SmartBoxLocator.IsPointerInModule(new(ReferenceGetMaxSpeed)); + + /// + /// Writes motion-vector fields directly into CMotionInterp, calls DoJump(1), + /// then clears them back out. Mirrors UB's UBHelper.Jumper algorithm, minus + /// the power-bar hook (the plugin drives timing with a ms delay). + /// + /// This is the only reliable way to jump *with forward/back/strafe momentum* + /// in AC — SetMotion routes through the command interpreter, which doesn't + /// bake velocity into the physics simulation in time for DoJump. + /// + public static bool LaunchJumpWithMotion(bool shift, bool holdW, bool holdX, bool holdZ, bool holdC) + { + if (!TryGetCMotionInterp(out IntPtr cmi)) + { + RynthLog.Compat("LaunchJumpWithMotion: CMotionInterp unavailable"); + return false; + } + + if (!TryGetMaxSpeed(cmi, out double maxSpeed)) + { + RynthLog.Compat("LaunchJumpWithMotion: get_max_speed failed"); + return false; + } + + double num = maxSpeed / 4.0; + + IntPtr pForwardId = cmi + CMotionForwardIdOffset; + IntPtr pForwardSpeed = cmi + CMotionForwardSpeedOffset; + IntPtr pStrafeId = cmi + CMotionStrafeIdOffset; + IntPtr pStrafeSpeed = cmi + CMotionStrafeSpeedOffset; + IntPtr pTurn = cmi + CMotionTurnOffset; + + try + { + // Forward/back channel + if (holdW || holdX) + { + if (holdW) + { + Marshal.WriteInt32(pForwardId, MotionIdForward); + WriteFloat(pForwardSpeed, shift ? 1f : (float)num); + } + else + { + Marshal.WriteInt32(pForwardId, MotionIdBackward); + WriteFloat(pForwardSpeed, shift ? -1f : (float)(-0.65 * num)); + } + } + else + { + Marshal.WriteInt32(pForwardId, MotionIdIdle); + } + + // Strafe channel + if (holdZ || holdC) + { + Marshal.WriteInt32(pStrafeId, MotionIdSidestep); + double s = num * 1.248; + if (shift) s *= 0.5; + if (s > 3.0) s = 3.0; + WriteFloat(pStrafeSpeed, holdC ? (float)s : (float)(-s)); + } + else + { + Marshal.WriteInt32(pStrafeId, 0); + } + + Marshal.WriteInt32(pTurn, 0); + + bool jumped = CommandInterpreterHooks.DoJump(true); + + // Clear immediately so the character doesn't keep walking on landing. + if (holdZ || holdC) Marshal.WriteInt32(pStrafeId, 0); + if (holdW || holdX) Marshal.WriteInt32(pForwardId, MotionIdIdle); + + return jumped; + } + catch (Exception ex) + { + RynthLog.Compat($"LaunchJumpWithMotion: write failed: {ex.Message}"); + return false; + } + } + + private static bool TryGetCMotionInterp(out IntPtr cmotionInterp) + { + cmotionInterp = IntPtr.Zero; + + if (!SmartBoxLocator.TryGetPlayer(out IntPtr player, out _, out string failure)) + { + _statusMessage = failure; + return false; + } + + try + { + IntPtr movementManager = Marshal.ReadIntPtr(player + MovementManagerOffset); + if (movementManager == IntPtr.Zero) return false; + cmotionInterp = Marshal.ReadIntPtr(movementManager); + return cmotionInterp != IntPtr.Zero; + } + catch + { + return false; + } + } + + private static bool TryGetMaxSpeed(IntPtr cmotionInterp, out double maxSpeed) + { + maxSpeed = 0; + + if (_getMaxSpeed == null) + { + IntPtr ptr = new(ReferenceGetMaxSpeed); + if (!SmartBoxLocator.IsPointerInModule(ptr)) + return false; + _getMaxSpeed = Marshal.GetDelegateForFunctionPointer(ptr); + } + + try + { + maxSpeed = _getMaxSpeed(cmotionInterp); + return true; + } + catch + { + return false; + } + } + private static void WriteFloat(IntPtr address, float value) { Marshal.WriteInt32(address, BitConverter.SingleToInt32Bits(value)); diff --git a/src/RynthCore.Engine/Compatibility/RadarHooks.cs b/src/RynthCore.Engine/Compatibility/RadarHooks.cs new file mode 100644 index 0000000..df49db8 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/RadarHooks.cs @@ -0,0 +1,135 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/RadarHooks.cs +// +// Hooks gmRadarUI::DrawObjects to capture the singleton 'this' pointer. +// Exposes TryGetRadarRect, which asks UIElement::GetSurfaceBox for the +// radar element's current screen rect (used to overlay dungeon walls on +// the retail radar). +// +// VA derivation (map offset + 0x00401000 = live VA): +// 000D8FE0 gmRadarUI::DrawObjects(UISurface*) → 0x004D9FE0 +// 00061220 UIElement::GetSurfaceBox(Box2D*) → 0x00462220 +// ============================================================================ + +using System; +using System.Runtime.InteropServices; +using System.Threading; +using RynthCore.Engine.Hooking; + +namespace RynthCore.Engine.Compatibility; + +internal static class RadarHooks +{ + private const int GmRadarUIDrawObjectsVa = 0x004D9FE0; + private const int UIElementGetSurfaceBoxVa = 0x00462220; + + [UnmanagedFunctionPointer(CallingConvention.ThisCall)] + private delegate void GmRadarUIDrawObjectsDelegate(IntPtr thisPtr, IntPtr uiSurface); + + private static GmRadarUIDrawObjectsDelegate? _originalDrawObjects; + private static GmRadarUIDrawObjectsDelegate? _drawObjectsDetour; // held alive to prevent GC + private static IntPtr _gmRadarUIInstance; + private static bool _hookInstalled; + private static string _statusMessage = "Not initialized."; + + public static bool IsInstalled => _hookInstalled; + public static string StatusMessage => _statusMessage; + + /// + /// The captured gmRadarUI singleton. Zero until the radar has rendered at + /// least once this session (usually within the first frame after login). + /// + public static IntPtr GmRadarUIInstance => _gmRadarUIInstance; + + public static void Initialize() + { + if (_hookInstalled) + return; + + if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection)) + { + _statusMessage = "acclient.exe not available."; + return; + } + + int funcOff = GmRadarUIDrawObjectsVa - textSection.TextBaseVa; + if (funcOff < 0 || funcOff >= textSection.Bytes.Length) + { + _statusMessage = $"gmRadarUI::DrawObjects VA out of range @ 0x{GmRadarUIDrawObjectsVa:X8}."; + RynthLog.Compat($"Compat: radar hook failed - {_statusMessage}"); + return; + } + + byte firstByte = textSection.Bytes[funcOff]; + if (firstByte is 0x00 or 0xCC or 0xC3) + { + _statusMessage = $"gmRadarUI::DrawObjects looks invalid @ 0x{GmRadarUIDrawObjectsVa:X8} (opcode 0x{firstByte:X2})."; + RynthLog.Compat($"Compat: radar hook failed - {_statusMessage}"); + return; + } + + try + { + IntPtr targetAddress = new IntPtr(textSection.TextBaseVa + funcOff); + _drawObjectsDetour = DrawObjectsDetour; + IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_drawObjectsDetour); + _originalDrawObjects = Marshal.GetDelegateForFunctionPointer( + MinHook.HookCreate(targetAddress, detourPtr)); + Thread.MemoryBarrier(); + MinHook.Enable(targetAddress); + + _hookInstalled = true; + _statusMessage = $"Hooked gmRadarUI::DrawObjects @ 0x{targetAddress.ToInt32():X8}."; + RynthLog.Verbose($"Compat: radar hook ready @ 0x{targetAddress.ToInt32():X8}, firstByte=0x{firstByte:X2}"); + } + catch (Exception ex) + { + _statusMessage = ex.Message; + RynthLog.Compat($"Compat: radar hook failed - {ex.Message}"); + } + } + + private static void DrawObjectsDetour(IntPtr thisPtr, IntPtr uiSurface) + { + if (thisPtr != IntPtr.Zero) + _gmRadarUIInstance = thisPtr; + + _originalDrawObjects!(thisPtr, uiSurface); + } + + /// + /// Returns the retail radar element's current screen rect (x0,y0,x1,y1 in + /// pixels, exclusive on x1/y1). Calls UIElement::GetSurfaceBox on the + /// captured singleton. Returns false until the radar has rendered at least + /// once, or if the rect looks invalid. + /// + public static unsafe bool TryGetRadarRect(out int x0, out int y0, out int x1, out int y1) + { + x0 = y0 = x1 = y1 = 0; + IntPtr inst = _gmRadarUIInstance; + if (inst == IntPtr.Zero) + return false; + + // Box2D is four int32s laid out (x0, y0, x1, y1). GetSurfaceBox follows + // MSVC's "return struct by value" ABI: caller passes the output slot as + // the first stack argument; the callee fills it and returns the same ptr. + int* box = stackalloc int[4]; + box[0] = box[1] = box[2] = box[3] = 0; + + try + { + ((delegate* unmanaged[Thiscall])UIElementGetSurfaceBoxVa)(inst, box); + } + catch + { + return false; + } + + int bx0 = box[0], by0 = box[1], bx1 = box[2], by1 = box[3]; + if (bx1 <= bx0 || by1 <= by0 || bx1 > 10000 || by1 > 10000 || bx0 < -1000 || by0 < -1000) + return false; + + x0 = bx0; y0 = by0; x1 = bx1; y1 = by1; + return true; + } +} diff --git a/src/RynthCore.Engine/EntryPoint.cs b/src/RynthCore.Engine/EntryPoint.cs index c98ebdb..65c6050 100644 --- a/src/RynthCore.Engine/EntryPoint.cs +++ b/src/RynthCore.Engine/EntryPoint.cs @@ -273,6 +273,7 @@ public static class EntryPoint RunInitStep("combat-mode hooks", CombatModeHooks.Initialize); RunInitStep("teleport-state hooks", TeleportStateHooks.Initialize); RunInitStep("salvage hooks", SalvageHooks.Initialize); + RunInitStep("radar hooks", RadarHooks.Initialize); RunInitStep("do-motion hooks", DoMotionHooks.Initialize); RunInitStep("smartbox-setstate hooks", SmartBoxSetStateHooks.Initialize); RunInitStep("appraisal hooks", AppraisalHooks.Initialize); diff --git a/src/RynthCore.Engine/ImGui/ViewportPlatformBackend.cs b/src/RynthCore.Engine/ImGui/ViewportPlatformBackend.cs index 8b5db54..24993fb 100644 --- a/src/RynthCore.Engine/ImGui/ViewportPlatformBackend.cs +++ b/src/RynthCore.Engine/ImGui/ViewportPlatformBackend.cs @@ -470,14 +470,15 @@ internal static unsafe class ViewportPlatformBackend { uint flags = unchecked((uint)vp->Flags); bool noDecoration = (flags & (uint)ImGuiViewportFlags.NoDecoration) != 0; - bool noTaskbarIcon = (flags & (uint)ImGuiViewportFlags.NoTaskBarIcon) != 0; bool topMost = (flags & (uint)ImGuiViewportFlags.TopMost) != 0; uint dwStyle = noDecoration ? WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS : WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS; - uint dwExStyle = noTaskbarIcon ? WS_EX_TOOLWINDOW : WS_EX_APPWINDOW; + // Always use WS_EX_TOOLWINDOW so tear-off viewports don't clutter the taskbar / Alt-Tab + // list when users run many clients. Owned by _mainHwnd so it still closes with the game. + uint dwExStyle = WS_EX_TOOLWINDOW; if (topMost) dwExStyle |= WS_EX_TOPMOST; dwExStyle |= WS_EX_NOACTIVATE; @@ -746,7 +747,16 @@ internal static unsafe class ViewportPlatformBackend break; case WM_MOUSEACTIVATE: - return new IntPtr(MA_NOACTIVATE); + { + // If AC is the foreground app, don't steal its focus — just process the click. + // If the user is tabbed out (some other app is foreground), allow Windows to + // activate this viewport so the click actually brings it to the front. + IntPtr fg = GetForegroundWindow(); + IntPtr game = Win32Backend.GameHwnd; + if (game != IntPtr.Zero && fg == game) + return new IntPtr(MA_NOACTIVATE); + break; + } case WM_NCHITTEST: { diff --git a/src/RynthCore.Engine/Plugins/PluginContract.cs b/src/RynthCore.Engine/Plugins/PluginContract.cs index 1faf08e..febc423 100644 --- a/src/RynthCore.Engine/Plugins/PluginContract.cs +++ b/src/RynthCore.Engine/Plugins/PluginContract.cs @@ -461,6 +461,30 @@ internal struct RynthCoreAPI /// Returns total subpalette count, or -1 if no data was captured for this object. /// subIds[i] is the palette DID; offsets[i] is the range-start offset (used as slot index). public IntPtr GetObjectPalettesFn; + + /// Function pointer: int CommenceJump() + /// Calls ClientCombatSystem::CommenceJump (spacebar key-down). Starts the + /// power-bar charge cycle. Pair with DoJump(autonomous) to release. + public IntPtr CommenceJumpFn; + + /// Function pointer: int DoJump(int autonomous) + /// Calls ClientCombatSystem::DoJump (spacebar key-up). Releases a jump + /// at the current power-bar level. Pass autonomous=1 for the normal + /// player-driven jump (matches keyboard behavior). + public IntPtr DoJumpFn; + + /// Function pointer: int LaunchJumpWithMotion(int shift, int w, int x, int z, int c) + /// Writes motion vector directly into CMotionInterp, calls DoJump(1), then + /// clears the motion. This is the only way to jump with forward/back/strafe + /// momentum — SetMotion does not bake velocity into the physics sim in time + /// for DoJump. Mirrors UB's UBHelper.Jumper algorithm. + public IntPtr LaunchJumpWithMotionFn; + + /// Function pointer: int GetRadarRect(int* x0, int* y0, int* x1, int* y1) + /// Returns the retail gmRadarUI element's current screen rect in pixels + /// (x0,y0 top-left, x1,y1 bottom-right exclusive). Returns 1 on success, 0 + /// if the radar has not rendered yet this session. Requires API v53+. + public IntPtr GetRadarRectFn; } @@ -468,7 +492,7 @@ internal struct RynthCoreAPI /// Current API version. Bump when adding fields to RynthCoreAPI. internal static class PluginContractVersion { - public const uint Current = 50; + public const uint Current = 53; } internal static class ClientActionHookFlags @@ -625,6 +649,15 @@ internal delegate int SetAutoRunCallbackDelegate(int enabled); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate int TapJumpCallbackDelegate(); +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal delegate int CommenceJumpCallbackDelegate(); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal delegate int DoJumpCallbackDelegate(int autonomous); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal delegate int LaunchJumpWithMotionCallbackDelegate(int shift, int w, int x, int z, int c); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate int SetMotionCallbackDelegate(uint motion, int enabled); @@ -855,3 +888,6 @@ internal delegate void ForceResetBusyCountCallbackDelegate(); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal unsafe delegate int GetObjectPalettesCallbackDelegate(uint objectId, uint* subIds, uint* offsets, int maxCount); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate int GetRadarRectCallbackDelegate(int* x0, int* y0, int* x1, int* y1); diff --git a/src/RynthCore.Engine/Plugins/PluginManager.cs b/src/RynthCore.Engine/Plugins/PluginManager.cs index b68379f..310116d 100644 --- a/src/RynthCore.Engine/Plugins/PluginManager.cs +++ b/src/RynthCore.Engine/Plugins/PluginManager.cs @@ -113,6 +113,10 @@ internal static class PluginManager private static SetAutonomyLevelCallbackDelegate? _setAutonomyLevelCallback; private static SetAutoRunCallbackDelegate? _setAutoRunCallback; private static TapJumpCallbackDelegate? _tapJumpCallback; + private static CommenceJumpCallbackDelegate? _commenceJumpCallback; + private static DoJumpCallbackDelegate? _doJumpCallback; + private static LaunchJumpWithMotionCallbackDelegate? _launchJumpWithMotionCallback; + private static GetRadarRectCallbackDelegate? _getRadarRectCallback; private static SetMotionCallbackDelegate? _setMotionCallback; private static StopCompletelyCallbackDelegate? _stopCompletelyCallback; private static TurnToHeadingCallbackDelegate? _turnToHeadingCallback; @@ -1671,6 +1675,10 @@ internal static class PluginManager _setAutonomyLevelCallback ??= SetAutonomyLevel; _setAutoRunCallback ??= SetAutoRun; _tapJumpCallback ??= TapJump; + _commenceJumpCallback ??= CommenceJump; + _doJumpCallback ??= DoJump; + _launchJumpWithMotionCallback ??= LaunchJumpWithMotion; + _getRadarRectCallback ??= GetRadarRect; _setMotionCallback ??= SetMotion; _stopCompletelyCallback ??= StopCompletely; _turnToHeadingCallback ??= TurnToHeading; @@ -1839,6 +1847,10 @@ internal static class PluginManager _api.ForceResetBusyCountFn = Marshal.GetFunctionPointerForDelegate(_forceResetBusyCountCallback); _getObjectPalettesCallback ??= GetObjectPalettesAction; _api.GetObjectPalettesFn = Marshal.GetFunctionPointerForDelegate(_getObjectPalettesCallback); + _api.CommenceJumpFn = Marshal.GetFunctionPointerForDelegate(_commenceJumpCallback); + _api.DoJumpFn = Marshal.GetFunctionPointerForDelegate(_doJumpCallback); + _api.LaunchJumpWithMotionFn = Marshal.GetFunctionPointerForDelegate(_launchJumpWithMotionCallback); + _api.GetRadarRectFn = Marshal.GetFunctionPointerForDelegate(_getRadarRectCallback); } private static void ProbeClientHooks() @@ -2183,6 +2195,33 @@ internal static class PluginManager return ToAbiBool(ClientActionHooks.TapJump()); } + private static int CommenceJump() + { + return ToAbiBool(ClientActionHooks.CommenceJump()); + } + + private static int DoJump(int autonomous) + { + return ToAbiBool(ClientActionHooks.DoJump(autonomous != 0)); + } + + private static int LaunchJumpWithMotion(int shift, int w, int x, int z, int c) + { + return ToAbiBool(ClientActionHooks.LaunchJumpWithMotion(shift != 0, w != 0, x != 0, z != 0, c != 0)); + } + + private static unsafe int GetRadarRect(int* x0, int* y0, int* x1, int* y1) + { + if (x0 == null || y0 == null || x1 == null || y1 == null) + return 0; + + if (!RadarHooks.TryGetRadarRect(out int rx0, out int ry0, out int rx1, out int ry1)) + return 0; + + *x0 = rx0; *y0 = ry0; *x1 = rx1; *y1 = ry1; + return 1; + } + private static int SetMotion(uint motion, int enabled) { return ToAbiBool(ClientActionHooks.SetMotion(motion, enabled != 0)); diff --git a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs index 11d83c8..9331c38 100644 --- a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs +++ b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs @@ -100,4 +100,8 @@ public struct RynthCoreApiNative public IntPtr GetObjectBitfieldFn; public IntPtr ForceResetBusyCountFn; public IntPtr GetObjectPalettesFn; + public IntPtr CommenceJumpFn; + public IntPtr DoJumpFn; + public IntPtr LaunchJumpWithMotionFn; + public IntPtr GetRadarRectFn; } diff --git a/src/RynthCore.PluginSdk/RynthCoreHost.cs b/src/RynthCore.PluginSdk/RynthCoreHost.cs index e41bb40..ea5c07a 100644 --- a/src/RynthCore.PluginSdk/RynthCoreHost.cs +++ b/src/RynthCore.PluginSdk/RynthCoreHost.cs @@ -100,6 +100,10 @@ public readonly unsafe struct RynthCoreHost public bool HasGetCurrentCombatMode => _api.GetCurrentCombatModeFn != IntPtr.Zero; public bool HasSalvagePanel => _api.SalvagePanelOpenFn != IntPtr.Zero && _api.SalvagePanelAddItemFn != IntPtr.Zero && _api.SalvagePanelExecuteFn != IntPtr.Zero; public bool HasGetObjectPalettes => _api.Version >= 50 && _api.GetObjectPalettesFn != IntPtr.Zero; + public bool HasCommenceJump => _api.Version >= 51 && _api.CommenceJumpFn != IntPtr.Zero; + public bool HasDoJump => _api.Version >= 51 && _api.DoJumpFn != IntPtr.Zero; + public bool HasLaunchJumpWithMotion => _api.Version >= 52 && _api.LaunchJumpWithMotionFn != IntPtr.Zero; + public bool HasGetRadarRect => _api.Version >= 53 && _api.GetRadarRectFn != IntPtr.Zero; // ─── Methods ──────────────────────────────────────────────────────────── @@ -223,6 +227,61 @@ public readonly unsafe struct RynthCoreHost ((delegate* unmanaged[Cdecl])_api.TapJumpFn)() != 0; } + /// + /// Starts a charged jump (mirrors the keyboard spacebar-down path). + /// Follow with once the desired charge time has elapsed. + /// + public bool CommenceJump() + { + return _api.CommenceJumpFn != IntPtr.Zero && + ((delegate* unmanaged[Cdecl])_api.CommenceJumpFn)() != 0; + } + + /// + /// Releases a jump begun with (mirrors the keyboard spacebar-up path). + /// Pass autonomous=true to match UB's Jumper (player-authoritative extent). + /// + public bool DoJump(bool autonomous) + { + return _api.DoJumpFn != IntPtr.Zero && + ((delegate* unmanaged[Cdecl])_api.DoJumpFn)(autonomous ? 1 : 0) != 0; + } + + /// + /// Writes forward/back/strafe motion directly into CMotionInterp, calls + /// DoJump(autonomous=1), then clears the motion — mirrors UB's UBHelper.Jumper + /// algorithm. This is the only reliable way to jump *with momentum*; SetMotion + /// does not bake velocity into the physics simulation in time for DoJump. + /// Call this *in place of* when you want a directional jump. + /// + public bool LaunchJumpWithMotion(bool shift, bool holdW, bool holdX, bool holdZ, bool holdC) + { + return _api.LaunchJumpWithMotionFn != IntPtr.Zero && + ((delegate* unmanaged[Cdecl])_api.LaunchJumpWithMotionFn)( + shift ? 1 : 0, holdW ? 1 : 0, holdX ? 1 : 0, holdZ ? 1 : 0, holdC ? 1 : 0) != 0; + } + + /// + /// Returns the retail gmRadarUI element's current screen rect in pixels + /// (x0,y0 top-left, x1,y1 bottom-right exclusive). Returns false until the + /// radar has rendered at least once this session. + /// + public bool TryGetRadarRect(out int x0, out int y0, out int x1, out int y1) + { + x0 = y0 = x1 = y1 = 0; + if (_api.GetRadarRectFn == IntPtr.Zero) + return false; + + fixed (int* x0Ptr = &x0) + fixed (int* y0Ptr = &y0) + fixed (int* x1Ptr = &x1) + fixed (int* y1Ptr = &y1) + { + return ((delegate* unmanaged[Cdecl])_api.GetRadarRectFn)( + x0Ptr, y0Ptr, x1Ptr, y1Ptr) != 0; + } + } + public bool SetMotion(uint motion, bool enabled) { return _api.SetMotionFn != IntPtr.Zero && From 01c7a549bdf33cd6851652797e10bcdb0bfa1007 Mon Sep 17 00:00:00 2001 From: tombohar Date: Thu, 23 Apr 2026 21:08:26 -0400 Subject: [PATCH 02/11] Add radar/chat suppression hooks and custom-widget API - ChatHooks: captures gmMainChatUI via ListenToElementMessage and hides it via UIElement::SetVisible(false), re-asserted every frame from EndSceneHook. Suppression toggle restores visibility when flipped off. - RadarHooks: also suppresses gmRadarUI::DrawChildren (bezel/compass/coords) alongside DrawObjects so the whole retail radar goes blank. - PluginContract v55: SetRadarSuppressed + SetChatSuppressed fn pointers exposed to plugins via RynthCoreHost. --- .../Compatibility/ChatHooks.cs | 145 ++++++++++++++++++ .../Compatibility/RadarHooks.cs | 119 +++++++++++--- src/RynthCore.Engine/D3D9/EndSceneHook.cs | 4 + src/RynthCore.Engine/EntryPoint.cs | 1 + .../Plugins/PluginContract.cs | 20 ++- src/RynthCore.Engine/Plugins/PluginManager.cs | 16 ++ src/RynthCore.PluginSdk/RynthCoreApiNative.cs | 2 + src/RynthCore.PluginSdk/RynthCoreHost.cs | 27 ++++ 8 files changed, 313 insertions(+), 21 deletions(-) create mode 100644 src/RynthCore.Engine/Compatibility/ChatHooks.cs diff --git a/src/RynthCore.Engine/Compatibility/ChatHooks.cs b/src/RynthCore.Engine/Compatibility/ChatHooks.cs new file mode 100644 index 0000000..a1a569e --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/ChatHooks.cs @@ -0,0 +1,145 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/ChatHooks.cs +// +// Hooks gmMainChatUI::ListenToElementMessage purely to capture the widget's +// 'this' pointer on first UI dispatch. Per-frame visibility assertion is +// driven from EndSceneHook (ChatHooks.TickHide), which avoids the unsafe +// UseTime trampoline that was crashing with 0xC000001D — UseTime's prologue +// contains a relative jump MinHook on x86 mis-relocated. ListenToElementMessage +// is a large function with a standard MSVC prologue, safe to hook. +// +// VA derivation (map offset + 0x00401000 = live VA): +// 000CD6F0 gmMainChatUI::ListenToElementMessage(UIElementMessageInfo const &) +// → 0x004CE6F0 +// 00061390 UIElement::SetVisible(bool) → 0x00462390 +// ============================================================================ + +using System; +using System.Runtime.InteropServices; +using System.Threading; +using RynthCore.Engine.Hooking; + +namespace RynthCore.Engine.Compatibility; + +internal static class ChatHooks +{ + private const int GmMainChatUIListenMsgVa = 0x004CE6F0; + private const int UIElementSetVisibleVa = 0x00462390; + + [UnmanagedFunctionPointer(CallingConvention.ThisCall)] + private delegate void ListenToElementMessageDelegate(IntPtr thisPtr, IntPtr msgInfo); + + private static ListenToElementMessageDelegate? _originalListen; + private static ListenToElementMessageDelegate? _listenDetour; // held alive to prevent GC + + private static IntPtr _gmMainChatInstance; + private static bool _hookInstalled; + private static string _statusMessage = "Not initialized."; + + public static bool IsInstalled => _hookInstalled; + public static string StatusMessage => _statusMessage; + + /// + /// When true, TickHide() calls UIElement::SetVisible(false) on the captured + /// chat widget each frame, hiding the retail chatbox. Re-asserted every frame. + /// + public static bool SuppressOriginalChat; + + /// The captured gmMainChatUI singleton. Zero until the user interacts + /// with the chat at least once (hover, click, message dispatch). + public static IntPtr GmMainChatInstance => _gmMainChatInstance; + + public static void Initialize() + { + if (_hookInstalled) + return; + + if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection)) + { + _statusMessage = "acclient.exe not available."; + return; + } + + int funcOff = GmMainChatUIListenMsgVa - textSection.TextBaseVa; + if (funcOff < 0 || funcOff >= textSection.Bytes.Length) + { + _statusMessage = $"ListenToElementMessage VA out of range @ 0x{GmMainChatUIListenMsgVa:X8}."; + RynthLog.Compat($"Compat: chat hook failed - {_statusMessage}"); + return; + } + + byte firstByte = textSection.Bytes[funcOff]; + if (firstByte is 0x00 or 0xCC or 0xC3) + { + _statusMessage = $"ListenToElementMessage looks invalid @ 0x{GmMainChatUIListenMsgVa:X8} (opcode 0x{firstByte:X2})."; + RynthLog.Compat($"Compat: chat hook failed - {_statusMessage}"); + return; + } + + try + { + IntPtr targetAddress = new IntPtr(textSection.TextBaseVa + funcOff); + _listenDetour = ListenDetour; + IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_listenDetour); + _originalListen = Marshal.GetDelegateForFunctionPointer( + MinHook.HookCreate(targetAddress, detourPtr)); + Thread.MemoryBarrier(); + MinHook.Enable(targetAddress); + + _hookInstalled = true; + _statusMessage = $"Hooked gmMainChatUI::ListenToElementMessage @ 0x{targetAddress.ToInt32():X8}."; + RynthLog.Verbose($"Compat: chat hook ready @ 0x{targetAddress.ToInt32():X8}, firstByte=0x{firstByte:X2}"); + } + catch (Exception ex) + { + _statusMessage = ex.Message; + RynthLog.Compat($"Compat: chat hook failed - {ex.Message}"); + } + } + + private static void ListenDetour(IntPtr thisPtr, IntPtr msgInfo) + { + if (thisPtr != IntPtr.Zero) + _gmMainChatInstance = thisPtr; + + _originalListen!(thisPtr, msgInfo); + } + + /// True once we've issued SetVisible(false) — used so we know to + /// restore visibility one frame after the suppress flag flips off. + private static bool _isHiddenAsserted; + + /// + /// Per-frame visibility assertion — called from EndSceneHook every frame. + /// While suppression is on, calls SetVisible(false) every frame so the game + /// can't sneak the chat back on. When suppression flips off, calls + /// SetVisible(true) one time to restore the retail chatbox. + /// + public static unsafe void TickHide() + { + IntPtr inst = _gmMainChatInstance; + if (inst == IntPtr.Zero) return; + + if (SuppressOriginalChat) + { + try + { + ((delegate* unmanaged[Thiscall])UIElementSetVisibleVa)(inst, 0); + } + catch { /* best-effort */ } + _isHiddenAsserted = true; + return; + } + + // Suppression is off — if we previously hid it, show it again now. + if (_isHiddenAsserted) + { + try + { + ((delegate* unmanaged[Thiscall])UIElementSetVisibleVa)(inst, 1); + } + catch { /* best-effort */ } + _isHiddenAsserted = false; + } + } +} diff --git a/src/RynthCore.Engine/Compatibility/RadarHooks.cs b/src/RynthCore.Engine/Compatibility/RadarHooks.cs index df49db8..f1591bc 100644 --- a/src/RynthCore.Engine/Compatibility/RadarHooks.cs +++ b/src/RynthCore.Engine/Compatibility/RadarHooks.cs @@ -1,14 +1,18 @@ // ============================================================================ // RynthCore.Engine - Compatibility/RadarHooks.cs // -// Hooks gmRadarUI::DrawObjects to capture the singleton 'this' pointer. +// Hooks gmRadarUI::DrawObjects (blips) and gmRadarUI::DrawChildren (bezel, +// compass tokens, coord readouts) to capture the singleton 'this' pointer +// and, when SuppressOriginalDraw is set, blank the vanilla radar entirely +// so a plugin can own that rect. +// // Exposes TryGetRadarRect, which asks UIElement::GetSurfaceBox for the -// radar element's current screen rect (used to overlay dungeon walls on -// the retail radar). +// radar element's current screen rect. // // VA derivation (map offset + 0x00401000 = live VA): -// 000D8FE0 gmRadarUI::DrawObjects(UISurface*) → 0x004D9FE0 -// 00061220 UIElement::GetSurfaceBox(Box2D*) → 0x00462220 +// 000D8FE0 gmRadarUI::DrawObjects(UISurface*) → 0x004D9FE0 +// 000D9380 gmRadarUI::DrawChildren(Box2D&,Box2D&,SmartArray&,UISurface*) → 0x004DA380 +// 00061220 UIElement::GetSurfaceBox(Box2D*) → 0x00462220 // ============================================================================ using System; @@ -20,14 +24,21 @@ namespace RynthCore.Engine.Compatibility; internal static class RadarHooks { - private const int GmRadarUIDrawObjectsVa = 0x004D9FE0; + private const int GmRadarUIDrawObjectsVa = 0x004D9FE0; + private const int GmRadarUIDrawChildrenVa = 0x004DA380; private const int UIElementGetSurfaceBoxVa = 0x00462220; [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate void GmRadarUIDrawObjectsDelegate(IntPtr thisPtr, IntPtr uiSurface); - private static GmRadarUIDrawObjectsDelegate? _originalDrawObjects; - private static GmRadarUIDrawObjectsDelegate? _drawObjectsDetour; // held alive to prevent GC + [UnmanagedFunctionPointer(CallingConvention.ThisCall)] + private delegate void GmRadarUIDrawChildrenDelegate(IntPtr thisPtr, IntPtr clipRect, IntPtr clipInside, IntPtr boxArray, IntPtr uiSurface); + + private static GmRadarUIDrawObjectsDelegate? _originalDrawObjects; + private static GmRadarUIDrawObjectsDelegate? _drawObjectsDetour; // held alive to prevent GC + private static GmRadarUIDrawChildrenDelegate? _originalDrawChildren; + private static GmRadarUIDrawChildrenDelegate? _drawChildrenDetour; + private static IntPtr _gmRadarUIInstance; private static bool _hookInstalled; private static string _statusMessage = "Not initialized."; @@ -35,6 +46,13 @@ internal static class RadarHooks public static bool IsInstalled => _hookInstalled; public static string StatusMessage => _statusMessage; + /// + /// When true, the detours skip the original gmRadarUI draw calls, blanking + /// the vanilla radar so a custom renderer can own that rect. The UIElement + /// is still captured on entry, so GetSurfaceBox keeps working. + /// + public static bool SuppressOriginalDraw; + /// /// The captured gmRadarUI singleton. Zero until the radar has rendered at /// least once this session (usually within the first frame after login). @@ -52,20 +70,36 @@ internal static class RadarHooks return; } + bool drawObjectsOk = TryInstallDrawObjectsHook(textSection); + bool drawChildrenOk = TryInstallDrawChildrenHook(textSection); + + if (drawObjectsOk && drawChildrenOk) + { + _hookInstalled = true; + _statusMessage = "Hooked gmRadarUI::DrawObjects + DrawChildren."; + RynthLog.Verbose("Compat: radar hooks ready (DrawObjects + DrawChildren)."); + } + else + { + _statusMessage = $"Partial install — DrawObjects={drawObjectsOk}, DrawChildren={drawChildrenOk}."; + RynthLog.Compat($"Compat: radar hook {_statusMessage}"); + } + } + + private static bool TryInstallDrawObjectsHook(AcClientTextSection textSection) + { int funcOff = GmRadarUIDrawObjectsVa - textSection.TextBaseVa; if (funcOff < 0 || funcOff >= textSection.Bytes.Length) { - _statusMessage = $"gmRadarUI::DrawObjects VA out of range @ 0x{GmRadarUIDrawObjectsVa:X8}."; - RynthLog.Compat($"Compat: radar hook failed - {_statusMessage}"); - return; + RynthLog.Compat($"Compat: DrawObjects VA out of range @ 0x{GmRadarUIDrawObjectsVa:X8}."); + return false; } byte firstByte = textSection.Bytes[funcOff]; if (firstByte is 0x00 or 0xCC or 0xC3) { - _statusMessage = $"gmRadarUI::DrawObjects looks invalid @ 0x{GmRadarUIDrawObjectsVa:X8} (opcode 0x{firstByte:X2})."; - RynthLog.Compat($"Compat: radar hook failed - {_statusMessage}"); - return; + RynthLog.Compat($"Compat: DrawObjects looks invalid @ 0x{GmRadarUIDrawObjectsVa:X8} (opcode 0x{firstByte:X2})."); + return false; } try @@ -77,15 +111,46 @@ internal static class RadarHooks MinHook.HookCreate(targetAddress, detourPtr)); Thread.MemoryBarrier(); MinHook.Enable(targetAddress); - - _hookInstalled = true; - _statusMessage = $"Hooked gmRadarUI::DrawObjects @ 0x{targetAddress.ToInt32():X8}."; - RynthLog.Verbose($"Compat: radar hook ready @ 0x{targetAddress.ToInt32():X8}, firstByte=0x{firstByte:X2}"); + return true; } catch (Exception ex) { - _statusMessage = ex.Message; - RynthLog.Compat($"Compat: radar hook failed - {ex.Message}"); + RynthLog.Compat($"Compat: DrawObjects hook failed - {ex.Message}"); + return false; + } + } + + private static bool TryInstallDrawChildrenHook(AcClientTextSection textSection) + { + int funcOff = GmRadarUIDrawChildrenVa - textSection.TextBaseVa; + if (funcOff < 0 || funcOff >= textSection.Bytes.Length) + { + RynthLog.Compat($"Compat: DrawChildren VA out of range @ 0x{GmRadarUIDrawChildrenVa:X8}."); + return false; + } + + byte firstByte = textSection.Bytes[funcOff]; + if (firstByte is 0x00 or 0xCC or 0xC3) + { + RynthLog.Compat($"Compat: DrawChildren looks invalid @ 0x{GmRadarUIDrawChildrenVa:X8} (opcode 0x{firstByte:X2})."); + return false; + } + + try + { + IntPtr targetAddress = new IntPtr(textSection.TextBaseVa + funcOff); + _drawChildrenDetour = DrawChildrenDetour; + IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_drawChildrenDetour); + _originalDrawChildren = Marshal.GetDelegateForFunctionPointer( + MinHook.HookCreate(targetAddress, detourPtr)); + Thread.MemoryBarrier(); + MinHook.Enable(targetAddress); + return true; + } + catch (Exception ex) + { + RynthLog.Compat($"Compat: DrawChildren hook failed - {ex.Message}"); + return false; } } @@ -94,9 +159,23 @@ internal static class RadarHooks if (thisPtr != IntPtr.Zero) _gmRadarUIInstance = thisPtr; + if (SuppressOriginalDraw) + return; + _originalDrawObjects!(thisPtr, uiSurface); } + private static void DrawChildrenDetour(IntPtr thisPtr, IntPtr clipRect, IntPtr clipInside, IntPtr boxArray, IntPtr uiSurface) + { + if (thisPtr != IntPtr.Zero) + _gmRadarUIInstance = thisPtr; + + if (SuppressOriginalDraw) + return; + + _originalDrawChildren!(thisPtr, clipRect, clipInside, boxArray, uiSurface); + } + /// /// Returns the retail radar element's current screen rect (x0,y0,x1,y1 in /// pixels, exclusive on x1/y1). Calls UIElement::GetSurfaceBox on the diff --git a/src/RynthCore.Engine/D3D9/EndSceneHook.cs b/src/RynthCore.Engine/D3D9/EndSceneHook.cs index 8be4cf3..1b7faf4 100644 --- a/src/RynthCore.Engine/D3D9/EndSceneHook.cs +++ b/src/RynthCore.Engine/D3D9/EndSceneHook.cs @@ -2,6 +2,7 @@ using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; +using RynthCore.Engine.Compatibility; using RynthCore.Engine.Hooking; using RynthCore.Engine.ImGuiBackend; @@ -205,6 +206,9 @@ internal static class EndSceneHook _renderCount++; _frameCount++; + // Per-frame chatbox visibility assertion (no-op unless plugin enables suppression). + try { ChatHooks.TickHide(); } catch { /* never let this bring down EndScene */ } + if (_renderCount == 1 && _offscreenFilterDisabled && _skipCount > 0) { long installElapsedMs = Environment.TickCount64 - _installTick; diff --git a/src/RynthCore.Engine/EntryPoint.cs b/src/RynthCore.Engine/EntryPoint.cs index 65c6050..ea332dc 100644 --- a/src/RynthCore.Engine/EntryPoint.cs +++ b/src/RynthCore.Engine/EntryPoint.cs @@ -274,6 +274,7 @@ public static class EntryPoint RunInitStep("teleport-state hooks", TeleportStateHooks.Initialize); RunInitStep("salvage hooks", SalvageHooks.Initialize); RunInitStep("radar hooks", RadarHooks.Initialize); + RunInitStep("chat hooks", ChatHooks.Initialize); RunInitStep("do-motion hooks", DoMotionHooks.Initialize); RunInitStep("smartbox-setstate hooks", SmartBoxSetStateHooks.Initialize); RunInitStep("appraisal hooks", AppraisalHooks.Initialize); diff --git a/src/RynthCore.Engine/Plugins/PluginContract.cs b/src/RynthCore.Engine/Plugins/PluginContract.cs index febc423..5e45d76 100644 --- a/src/RynthCore.Engine/Plugins/PluginContract.cs +++ b/src/RynthCore.Engine/Plugins/PluginContract.cs @@ -485,6 +485,18 @@ internal struct RynthCoreAPI /// (x0,y0 top-left, x1,y1 bottom-right exclusive). Returns 1 on success, 0 /// if the radar has not rendered yet this session. Requires API v53+. public IntPtr GetRadarRectFn; + + /// Function pointer: void SetRadarSuppressed(int enabled) + /// When enabled=1, the engine skips the original gmRadarUI::DrawObjects call + /// so the vanilla radar stops rendering and a plugin can own that rect. + /// Requires API v54+. + public IntPtr SetRadarSuppressedFn; + + /// Function pointer: void SetChatSuppressed(int enabled) + /// When enabled=1, the engine calls UIElement::SetVisible(false) on the + /// gmMainChatUI each frame, hiding the retail chatbox entirely. + /// Requires API v55+. + public IntPtr SetChatSuppressedFn; } @@ -492,7 +504,7 @@ internal struct RynthCoreAPI /// Current API version. Bump when adding fields to RynthCoreAPI. internal static class PluginContractVersion { - public const uint Current = 53; + public const uint Current = 55; } internal static class ClientActionHookFlags @@ -891,3 +903,9 @@ internal unsafe delegate int GetObjectPalettesCallbackDelegate(uint objectId, ui [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal unsafe delegate int GetRadarRectCallbackDelegate(int* x0, int* y0, int* x1, int* y1); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal delegate void SetRadarSuppressedCallbackDelegate(int enabled); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal delegate void SetChatSuppressedCallbackDelegate(int enabled); diff --git a/src/RynthCore.Engine/Plugins/PluginManager.cs b/src/RynthCore.Engine/Plugins/PluginManager.cs index 310116d..75b4894 100644 --- a/src/RynthCore.Engine/Plugins/PluginManager.cs +++ b/src/RynthCore.Engine/Plugins/PluginManager.cs @@ -117,6 +117,8 @@ internal static class PluginManager private static DoJumpCallbackDelegate? _doJumpCallback; private static LaunchJumpWithMotionCallbackDelegate? _launchJumpWithMotionCallback; private static GetRadarRectCallbackDelegate? _getRadarRectCallback; + private static SetRadarSuppressedCallbackDelegate? _setRadarSuppressedCallback; + private static SetChatSuppressedCallbackDelegate? _setChatSuppressedCallback; private static SetMotionCallbackDelegate? _setMotionCallback; private static StopCompletelyCallbackDelegate? _stopCompletelyCallback; private static TurnToHeadingCallbackDelegate? _turnToHeadingCallback; @@ -1679,6 +1681,8 @@ internal static class PluginManager _doJumpCallback ??= DoJump; _launchJumpWithMotionCallback ??= LaunchJumpWithMotion; _getRadarRectCallback ??= GetRadarRect; + _setRadarSuppressedCallback ??= SetRadarSuppressed; + _setChatSuppressedCallback ??= SetChatSuppressed; _setMotionCallback ??= SetMotion; _stopCompletelyCallback ??= StopCompletely; _turnToHeadingCallback ??= TurnToHeading; @@ -1851,6 +1855,8 @@ internal static class PluginManager _api.DoJumpFn = Marshal.GetFunctionPointerForDelegate(_doJumpCallback); _api.LaunchJumpWithMotionFn = Marshal.GetFunctionPointerForDelegate(_launchJumpWithMotionCallback); _api.GetRadarRectFn = Marshal.GetFunctionPointerForDelegate(_getRadarRectCallback); + _api.SetRadarSuppressedFn = Marshal.GetFunctionPointerForDelegate(_setRadarSuppressedCallback); + _api.SetChatSuppressedFn = Marshal.GetFunctionPointerForDelegate(_setChatSuppressedCallback); } private static void ProbeClientHooks() @@ -2222,6 +2228,16 @@ internal static class PluginManager return 1; } + private static void SetRadarSuppressed(int enabled) + { + RadarHooks.SuppressOriginalDraw = enabled != 0; + } + + private static void SetChatSuppressed(int enabled) + { + ChatHooks.SuppressOriginalChat = enabled != 0; + } + private static int SetMotion(uint motion, int enabled) { return ToAbiBool(ClientActionHooks.SetMotion(motion, enabled != 0)); diff --git a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs index 9331c38..b7cf770 100644 --- a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs +++ b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs @@ -104,4 +104,6 @@ public struct RynthCoreApiNative public IntPtr DoJumpFn; public IntPtr LaunchJumpWithMotionFn; public IntPtr GetRadarRectFn; + public IntPtr SetRadarSuppressedFn; + public IntPtr SetChatSuppressedFn; } diff --git a/src/RynthCore.PluginSdk/RynthCoreHost.cs b/src/RynthCore.PluginSdk/RynthCoreHost.cs index ea5c07a..c0298e9 100644 --- a/src/RynthCore.PluginSdk/RynthCoreHost.cs +++ b/src/RynthCore.PluginSdk/RynthCoreHost.cs @@ -104,6 +104,8 @@ public readonly unsafe struct RynthCoreHost public bool HasDoJump => _api.Version >= 51 && _api.DoJumpFn != IntPtr.Zero; public bool HasLaunchJumpWithMotion => _api.Version >= 52 && _api.LaunchJumpWithMotionFn != IntPtr.Zero; public bool HasGetRadarRect => _api.Version >= 53 && _api.GetRadarRectFn != IntPtr.Zero; + public bool HasSetRadarSuppressed => _api.Version >= 54 && _api.SetRadarSuppressedFn != IntPtr.Zero; + public bool HasSetChatSuppressed => _api.Version >= 55 && _api.SetChatSuppressedFn != IntPtr.Zero; // ─── Methods ──────────────────────────────────────────────────────────── @@ -282,6 +284,31 @@ public readonly unsafe struct RynthCoreHost } } + /// + /// When enabled, the engine suppresses the vanilla gmRadarUI::DrawObjects + /// call so the radar rect is blank and a plugin can own it entirely. + /// + public void SetRadarSuppressed(bool enabled) + { + if (_api.SetRadarSuppressedFn == IntPtr.Zero) + return; + + ((delegate* unmanaged[Cdecl])_api.SetRadarSuppressedFn)(enabled ? 1 : 0); + } + + /// + /// When enabled, the engine hides the retail gmMainChatUI each frame via + /// UIElement::SetVisible(false). Re-asserted every frame so the game can't + /// sneak it back on. + /// + public void SetChatSuppressed(bool enabled) + { + if (_api.SetChatSuppressedFn == IntPtr.Zero) + return; + + ((delegate* unmanaged[Cdecl])_api.SetChatSuppressedFn)(enabled ? 1 : 0); + } + public bool SetMotion(uint motion, bool enabled) { return _api.SetMotionFn != IntPtr.Zero && From cd3ccfd550c908b5521167e855eef613efd0d0e8 Mon Sep 17 00:00:00 2001 From: tombohar Date: Sat, 25 Apr 2026 10:03:58 -0400 Subject: [PATCH 03/11] Add power bar suppression API, pin imgui.ini, bump SDK to v56 - New PowerbarHooks scaffold hooking gmPowerbarUI's RecvNotice_Begin/Level/ Finish trio. SetPowerbarSuppressed exposed via the plugin contract; current implementation no-ops the notices (a deeper SetVisible/HidePowerBar path crashed on the captured pointer, so full hide is parked for later). - ImGuiController pins io.IniFilename to a stable absolute path (C:\Games\RynthSuite\RynthAi\imgui.ini) so window positions, sizes, and dock layout persist across RL hot-reload and AC restarts. Default ImGui behavior wrote into the host process working dir which varied per launch. - PluginContract version bumped to 56 with SetPowerbarSuppressedFn added to RynthCoreAPI; SDK exposes Has/Set methods on RynthCoreHost. Co-Authored-By: Claude Opus 4.7 --- .../Compatibility/PowerbarHooks.cs | 224 ++++++++++++++++++ src/RynthCore.Engine/EntryPoint.cs | 1 + src/RynthCore.Engine/ImGui/ImGuiController.cs | 17 ++ .../Plugins/PluginContract.cs | 11 +- src/RynthCore.Engine/Plugins/PluginManager.cs | 12 + src/RynthCore.PluginSdk/RynthCoreApiNative.cs | 1 + src/RynthCore.PluginSdk/RynthCoreHost.cs | 13 +- 7 files changed, 276 insertions(+), 3 deletions(-) create mode 100644 src/RynthCore.Engine/Compatibility/PowerbarHooks.cs diff --git a/src/RynthCore.Engine/Compatibility/PowerbarHooks.cs b/src/RynthCore.Engine/Compatibility/PowerbarHooks.cs new file mode 100644 index 0000000..4cb7a40 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/PowerbarHooks.cs @@ -0,0 +1,224 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/PowerbarHooks.cs +// +// Hooks gmPowerbarUI's RecvNotice_* trio so that, when SuppressOriginalDraw +// is set, the vanilla attack/magic power bar never appears on screen. The +// bar is ENTIRELY initialized via these notices — BeginPowerbar shows it, +// SetPowerbarLevel updates it, FinishPowerbar hides it. By no-opping all +// three, the bar stays invisible. +// +// VA derivation (map offset + 0x00401000 = live VA — same as RadarHooks): +// 000DA390 gmPowerbarUI::RecvNotice_BeginPowerbar(PowerBarMode) → 0x004DB390 +// 000DA1B0 gmPowerbarUI::RecvNotice_SetPowerbarLevel(PowerBarMode,float)→ 0x004DB1B0 +// 000DA1E0 gmPowerbarUI::RecvNotice_FinishPowerbar(PowerBarMode) → 0x004DB1E0 +// ============================================================================ + +using System; +using System.Runtime.InteropServices; +using System.Threading; +using RynthCore.Engine.Hooking; + +namespace RynthCore.Engine.Compatibility; + +internal static class PowerbarHooks +{ + private const int GmPowerbarUIBeginVa = 0x004DB390; + private const int GmPowerbarUILevelVa = 0x004DB1B0; + private const int GmPowerbarUIFinishVa = 0x004DB1E0; + + // ClientCombatSystem direct hide. Map: 0016A5F0 + 0x00401000 = 0x0056B5F0. + // Thiscall void HidePowerBar() — call on the CCS singleton via the global + // pointer that ClientCombatHooks already locates at 0x0087166C. + private const int ClientCombatSystemHidePowerBarVa = 0x0056B5F0; + private const int CombatSystemPtrVa = 0x0087166C; + + [UnmanagedFunctionPointer(CallingConvention.ThisCall)] + private delegate void HidePowerBarDelegate(IntPtr thisPtr); + + private static IntPtr _gmPowerbarUIInstance; + + [UnmanagedFunctionPointer(CallingConvention.ThisCall)] + private delegate void NoticeBeginDelegate(IntPtr thisPtr, int powerBarMode); + + [UnmanagedFunctionPointer(CallingConvention.ThisCall)] + private delegate void NoticeLevelDelegate(IntPtr thisPtr, int powerBarMode, float level); + + [UnmanagedFunctionPointer(CallingConvention.ThisCall)] + private delegate void NoticeFinishDelegate(IntPtr thisPtr, int powerBarMode); + + private static NoticeBeginDelegate? _originalBegin; + private static NoticeBeginDelegate? _beginDetour; + private static NoticeLevelDelegate? _originalLevel; + private static NoticeLevelDelegate? _levelDetour; + private static NoticeFinishDelegate? _originalFinish; + private static NoticeFinishDelegate? _finishDetour; + + private static bool _hookInstalled; + private static string _statusMessage = "Not initialized."; + + public static bool IsInstalled => _hookInstalled; + public static string StatusMessage => _statusMessage; + + /// + /// When true, the detours skip the original gmPowerbarUI notices, so the + /// retail attack/magic power bar never appears. A plugin can render its + /// own equivalent (or just leave it hidden). + /// + public static bool SuppressOriginalDraw; + + public static void Initialize() + { + if (_hookInstalled) + return; + + if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection)) + { + _statusMessage = "acclient.exe not available."; + return; + } + + bool beginOk = TryInstallBeginHook(textSection); + bool levelOk = TryInstallLevelHook(textSection); + bool finishOk = TryInstallFinishHook(textSection); + + if (beginOk && levelOk && finishOk) + { + _hookInstalled = true; + _statusMessage = "Hooked gmPowerbarUI::RecvNotice_(Begin/Level/Finish)."; + RynthLog.Compat($"Compat: powerbar hooks ready (Begin=0x{GmPowerbarUIBeginVa:X8}, Level=0x{GmPowerbarUILevelVa:X8}, Finish=0x{GmPowerbarUIFinishVa:X8})."); + } + else + { + _statusMessage = $"Partial install — Begin={beginOk}, Level={levelOk}, Finish={finishOk}."; + RynthLog.Compat($"Compat: powerbar hook {_statusMessage}"); + } + } + + private static bool TryInstallBeginHook(AcClientTextSection textSection) + { + int funcOff = GmPowerbarUIBeginVa - textSection.TextBaseVa; + if (!IsValidPrologue(textSection, funcOff, "Begin", GmPowerbarUIBeginVa)) + return false; + + try + { + IntPtr targetAddress = new IntPtr(textSection.TextBaseVa + funcOff); + _beginDetour = BeginDetour; + IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_beginDetour); + _originalBegin = Marshal.GetDelegateForFunctionPointer( + MinHook.HookCreate(targetAddress, detourPtr)); + Thread.MemoryBarrier(); + MinHook.Enable(targetAddress); + return true; + } + catch (Exception ex) + { + RynthLog.Compat($"Compat: Powerbar Begin hook failed - {ex.Message}"); + return false; + } + } + + private static bool TryInstallLevelHook(AcClientTextSection textSection) + { + int funcOff = GmPowerbarUILevelVa - textSection.TextBaseVa; + if (!IsValidPrologue(textSection, funcOff, "Level", GmPowerbarUILevelVa)) + return false; + + try + { + IntPtr targetAddress = new IntPtr(textSection.TextBaseVa + funcOff); + _levelDetour = LevelDetour; + IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_levelDetour); + _originalLevel = Marshal.GetDelegateForFunctionPointer( + MinHook.HookCreate(targetAddress, detourPtr)); + Thread.MemoryBarrier(); + MinHook.Enable(targetAddress); + return true; + } + catch (Exception ex) + { + RynthLog.Compat($"Compat: Powerbar Level hook failed - {ex.Message}"); + return false; + } + } + + private static bool TryInstallFinishHook(AcClientTextSection textSection) + { + int funcOff = GmPowerbarUIFinishVa - textSection.TextBaseVa; + if (!IsValidPrologue(textSection, funcOff, "Finish", GmPowerbarUIFinishVa)) + return false; + + try + { + IntPtr targetAddress = new IntPtr(textSection.TextBaseVa + funcOff); + _finishDetour = FinishDetour; + IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_finishDetour); + _originalFinish = Marshal.GetDelegateForFunctionPointer( + MinHook.HookCreate(targetAddress, detourPtr)); + Thread.MemoryBarrier(); + MinHook.Enable(targetAddress); + return true; + } + catch (Exception ex) + { + RynthLog.Compat($"Compat: Powerbar Finish hook failed - {ex.Message}"); + return false; + } + } + + private static bool IsValidPrologue(AcClientTextSection textSection, int funcOff, string label, int va) + { + if (funcOff < 0 || funcOff >= textSection.Bytes.Length) + { + RynthLog.Compat($"Compat: Powerbar {label} VA out of range @ 0x{va:X8}."); + return false; + } + + byte firstByte = textSection.Bytes[funcOff]; + if (firstByte is 0x00 or 0xCC or 0xC3) + { + RynthLog.Compat($"Compat: Powerbar {label} looks invalid @ 0x{va:X8} (opcode 0x{firstByte:X2})."); + return false; + } + return true; + } + + // Per-call diagnostic — emits the first ~5 fires of each detour so we + // can confirm the hook is actually reached when the user expects the bar. + private static int _beginFires, _levelFires, _finishFires; + + private static void BeginDetour(IntPtr thisPtr, int powerBarMode) + { + if (thisPtr != IntPtr.Zero) _gmPowerbarUIInstance = thisPtr; + if (++_beginFires <= 5) + RynthLog.Compat($"Powerbar Begin fired #{_beginFires} (mode={powerBarMode}, suppress={SuppressOriginalDraw})"); + if (SuppressOriginalDraw) + return; + _originalBegin!(thisPtr, powerBarMode); + } + + private static void LevelDetour(IntPtr thisPtr, int powerBarMode, float level) + { + if (thisPtr != IntPtr.Zero) _gmPowerbarUIInstance = thisPtr; + if (++_levelFires <= 5) + RynthLog.Compat($"Powerbar Level fired #{_levelFires} (mode={powerBarMode}, level={level:F2}, suppress={SuppressOriginalDraw})"); + if (SuppressOriginalDraw) + return; + _originalLevel!(thisPtr, powerBarMode, level); + } + + private static void FinishDetour(IntPtr thisPtr, int powerBarMode) + { + if (thisPtr != IntPtr.Zero) _gmPowerbarUIInstance = thisPtr; + if (++_finishFires <= 5) + RynthLog.Compat($"Powerbar Finish fired #{_finishFires} (mode={powerBarMode}, suppress={SuppressOriginalDraw})"); + if (SuppressOriginalDraw) + return; + _originalFinish!(thisPtr, powerBarMode); + } + + // Per-frame SetVisible(false) on the captured pointer was crashing + // (0xC0000005 null-deref) — the instance grabbed from LevelDetour isn't + // safe to invoke UIElement::SetVisible on. Suppression is currently a + // no-op of the notices only; we'll need a different hide strategy later. +} diff --git a/src/RynthCore.Engine/EntryPoint.cs b/src/RynthCore.Engine/EntryPoint.cs index ea332dc..70bfd64 100644 --- a/src/RynthCore.Engine/EntryPoint.cs +++ b/src/RynthCore.Engine/EntryPoint.cs @@ -275,6 +275,7 @@ public static class EntryPoint RunInitStep("salvage hooks", SalvageHooks.Initialize); RunInitStep("radar hooks", RadarHooks.Initialize); RunInitStep("chat hooks", ChatHooks.Initialize); + RunInitStep("powerbar hooks", PowerbarHooks.Initialize); RunInitStep("do-motion hooks", DoMotionHooks.Initialize); RunInitStep("smartbox-setstate hooks", SmartBoxSetStateHooks.Initialize); RunInitStep("appraisal hooks", AppraisalHooks.Initialize); diff --git a/src/RynthCore.Engine/ImGui/ImGuiController.cs b/src/RynthCore.Engine/ImGui/ImGuiController.cs index 849b7ff..837a3f6 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiController.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiController.cs @@ -83,6 +83,23 @@ internal static class ImGuiController ImGuiNET.ImGui.SetCurrentContext(_context); ImGuiIOPtr io = ImGuiNET.ImGui.GetIO(); + // Pin imgui.ini to a stable absolute path so window positions/sizes + // persist across plugin reloads (RL) and AC restarts. The default + // ImGui behavior writes to the working directory which can differ + // between launches. Allocated once, kept alive for the process lifetime. + try + { + const string iniPath = @"C:\Games\RynthSuite\RynthAi\imgui.ini"; + System.IO.Directory.CreateDirectory(@"C:\Games\RynthSuite\RynthAi"); + IntPtr iniPtr = System.Runtime.InteropServices.Marshal.StringToHGlobalAnsi(iniPath); + unsafe { io.NativePtr->IniFilename = (byte*)iniPtr; } + RynthLog.Render($"ImGuiController: imgui.ini pinned to {iniPath}"); + } + catch (Exception ex) + { + RynthLog.Render($"ImGuiController: failed to pin imgui.ini path - {ex.Message}"); + } + io.ConfigFlags |= ImGuiConfigFlags.DockingEnable; io.ConfigFlags |= ImGuiConfigFlags.ViewportsEnable; // Popped-out plugin windows use WS_EX_TOOLWINDOW so they don't show diff --git a/src/RynthCore.Engine/Plugins/PluginContract.cs b/src/RynthCore.Engine/Plugins/PluginContract.cs index 5e45d76..8c2f364 100644 --- a/src/RynthCore.Engine/Plugins/PluginContract.cs +++ b/src/RynthCore.Engine/Plugins/PluginContract.cs @@ -497,6 +497,12 @@ internal struct RynthCoreAPI /// gmMainChatUI each frame, hiding the retail chatbox entirely. /// Requires API v55+. public IntPtr SetChatSuppressedFn; + + /// Function pointer: void SetPowerbarSuppressed(int enabled) + /// When enabled=1, the engine no-ops gmPowerbarUI's RecvNotice_(Begin/ + /// Level/Finish), so the retail attack/magic power bar never renders. + /// Requires API v56+. + public IntPtr SetPowerbarSuppressedFn; } @@ -504,7 +510,7 @@ internal struct RynthCoreAPI /// Current API version. Bump when adding fields to RynthCoreAPI. internal static class PluginContractVersion { - public const uint Current = 55; + public const uint Current = 56; } internal static class ClientActionHookFlags @@ -907,5 +913,8 @@ internal unsafe delegate int GetRadarRectCallbackDelegate(int* x0, int* y0, int* [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void SetRadarSuppressedCallbackDelegate(int enabled); +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal delegate void SetPowerbarSuppressedCallbackDelegate(int enabled); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void SetChatSuppressedCallbackDelegate(int enabled); diff --git a/src/RynthCore.Engine/Plugins/PluginManager.cs b/src/RynthCore.Engine/Plugins/PluginManager.cs index 75b4894..b7dfe5a 100644 --- a/src/RynthCore.Engine/Plugins/PluginManager.cs +++ b/src/RynthCore.Engine/Plugins/PluginManager.cs @@ -119,6 +119,7 @@ internal static class PluginManager private static GetRadarRectCallbackDelegate? _getRadarRectCallback; private static SetRadarSuppressedCallbackDelegate? _setRadarSuppressedCallback; private static SetChatSuppressedCallbackDelegate? _setChatSuppressedCallback; + private static SetPowerbarSuppressedCallbackDelegate? _setPowerbarSuppressedCallback; private static SetMotionCallbackDelegate? _setMotionCallback; private static StopCompletelyCallbackDelegate? _stopCompletelyCallback; private static TurnToHeadingCallbackDelegate? _turnToHeadingCallback; @@ -1683,6 +1684,7 @@ internal static class PluginManager _getRadarRectCallback ??= GetRadarRect; _setRadarSuppressedCallback ??= SetRadarSuppressed; _setChatSuppressedCallback ??= SetChatSuppressed; + _setPowerbarSuppressedCallback ??= SetPowerbarSuppressed; _setMotionCallback ??= SetMotion; _stopCompletelyCallback ??= StopCompletely; _turnToHeadingCallback ??= TurnToHeading; @@ -1857,6 +1859,7 @@ internal static class PluginManager _api.GetRadarRectFn = Marshal.GetFunctionPointerForDelegate(_getRadarRectCallback); _api.SetRadarSuppressedFn = Marshal.GetFunctionPointerForDelegate(_setRadarSuppressedCallback); _api.SetChatSuppressedFn = Marshal.GetFunctionPointerForDelegate(_setChatSuppressedCallback); + _api.SetPowerbarSuppressedFn = Marshal.GetFunctionPointerForDelegate(_setPowerbarSuppressedCallback); } private static void ProbeClientHooks() @@ -2238,6 +2241,15 @@ internal static class PluginManager ChatHooks.SuppressOriginalChat = enabled != 0; } + private static void SetPowerbarSuppressed(int enabled) + { + bool was = PowerbarHooks.SuppressOriginalDraw; + bool now = enabled != 0; + PowerbarHooks.SuppressOriginalDraw = now; + if (was != now) + RynthLog.Compat($"Compat: powerbar suppress -> {now}"); + } + private static int SetMotion(uint motion, int enabled) { return ToAbiBool(ClientActionHooks.SetMotion(motion, enabled != 0)); diff --git a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs index b7cf770..051f975 100644 --- a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs +++ b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs @@ -106,4 +106,5 @@ public struct RynthCoreApiNative public IntPtr GetRadarRectFn; public IntPtr SetRadarSuppressedFn; public IntPtr SetChatSuppressedFn; + public IntPtr SetPowerbarSuppressedFn; } diff --git a/src/RynthCore.PluginSdk/RynthCoreHost.cs b/src/RynthCore.PluginSdk/RynthCoreHost.cs index c0298e9..8d8b0d2 100644 --- a/src/RynthCore.PluginSdk/RynthCoreHost.cs +++ b/src/RynthCore.PluginSdk/RynthCoreHost.cs @@ -104,8 +104,9 @@ public readonly unsafe struct RynthCoreHost public bool HasDoJump => _api.Version >= 51 && _api.DoJumpFn != IntPtr.Zero; public bool HasLaunchJumpWithMotion => _api.Version >= 52 && _api.LaunchJumpWithMotionFn != IntPtr.Zero; public bool HasGetRadarRect => _api.Version >= 53 && _api.GetRadarRectFn != IntPtr.Zero; - public bool HasSetRadarSuppressed => _api.Version >= 54 && _api.SetRadarSuppressedFn != IntPtr.Zero; - public bool HasSetChatSuppressed => _api.Version >= 55 && _api.SetChatSuppressedFn != IntPtr.Zero; + public bool HasSetRadarSuppressed => _api.Version >= 54 && _api.SetRadarSuppressedFn != IntPtr.Zero; + public bool HasSetChatSuppressed => _api.Version >= 55 && _api.SetChatSuppressedFn != IntPtr.Zero; + public bool HasSetPowerbarSuppressed => _api.Version >= 56 && _api.SetPowerbarSuppressedFn != IntPtr.Zero; // ─── Methods ──────────────────────────────────────────────────────────── @@ -301,6 +302,14 @@ public readonly unsafe struct RynthCoreHost /// UIElement::SetVisible(false). Re-asserted every frame so the game can't /// sneak it back on. /// + public void SetPowerbarSuppressed(bool enabled) + { + if (_api.SetPowerbarSuppressedFn == IntPtr.Zero) + return; + + ((delegate* unmanaged[Cdecl])_api.SetPowerbarSuppressedFn)(enabled ? 1 : 0); + } + public void SetChatSuppressed(bool enabled) { if (_api.SetChatSuppressedFn == IntPtr.Zero) From 8260c60494da6cb587a8960237bb6278756b6921 Mon Sep 17 00:00:00 2001 From: tombohar Date: Sat, 25 Apr 2026 23:36:56 -0400 Subject: [PATCH 04/11] Fix logout crash, add OnLogout plugin export, and read true buffed skill MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The long-standing "DX9 error / client crash on logout" was ChatHooks.TickHide calling SetVisible() on a stale gmMainChatUI pointer that AC frees during the world-to-charselect transition. TickHide now gates on HasObservedLoginComplete and the cached instance is reset in DispatchPendingLogout. CrashLogger gained a register dump + EBP-frame walk + ESP sweep with module resolution that made this trace possible. Plugin contract bumped to v57 with optional RynthPluginOnLogout export. LogoutLifecycleHooks hooks CPlayerSystem::ExecuteLogOff (fires after the user confirms the logoff prompt — not RecvNotice_EndCharacterSession which fires on the menu click before the prompt) plus RecvNotice_Logoff as fallback. RynthCoreShell + PluginManager.RenderAll gate on HasObservedLoginComplete so the bar/plugins hide between sessions. ClientObjectHooks.TryGetObjectSkill now calls CACQualities::InqSkill(raw=0) for the truly buffed skill — the old code returned InitialLevel + LevelFromPracticePoints which is just the base trained level, missing attribute / augmentation / spell-buff contributions. CharacterCaptureHooks latches _autoLoginEverFired so manual logout doesn't re-fire auto-login from the next 0xF658 packet. AccountProfileDialog drops the now-redundant Character/Slot field. UpdateObjectInventoryHooks pack scan also matches by wielderID so wielded items are picked up. Co-Authored-By: Claude Sonnet 4.6 --- .../AccountProfileDialog.axaml | 4 +- .../AccountProfileDialog.axaml.cs | 113 ----------- .../Compatibility/CharacterCaptureHooks.cs | 17 ++ .../Compatibility/ChatHooks.cs | 23 +++ .../Compatibility/ClientObjectHooks.cs | 19 +- .../Compatibility/LoginLifecycleHooks.cs | 12 ++ .../Compatibility/LogoutLifecycleHooks.cs | 168 ++++++++++++++++ .../UpdateObjectInventoryHooks.cs | 13 +- src/RynthCore.Engine/CrashLogger.cs | 179 +++++++++++++++++- src/RynthCore.Engine/EntryPoint.cs | 1 + src/RynthCore.Engine/ImGui/RynthCoreShell.cs | 10 + src/RynthCore.Engine/Plugins/LoadedPlugin.cs | 1 + .../Plugins/PluginContract.cs | 5 +- src/RynthCore.Engine/Plugins/PluginLoader.cs | 5 + src/RynthCore.Engine/Plugins/PluginManager.cs | 87 +++++++++ src/RynthCore.PluginCore/RynthPluginBase.cs | 1 + .../RynthPluginRuntime.cs | 6 + 17 files changed, 539 insertions(+), 125 deletions(-) create mode 100644 src/RynthCore.Engine/Compatibility/LogoutLifecycleHooks.cs diff --git a/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml b/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml index d416d6a..c8bf062 100644 --- a/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml +++ b/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml @@ -2,7 +2,7 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="RynthCore.App.Avalonia.AccountProfileDialog" Width="520" - Height="360" + Height="310" CanResize="False" WindowStartupLocation="CenterOwner" Title="Account Profile" @@ -24,8 +24,6 @@ - - diff --git a/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml.cs b/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml.cs index 44ed1e8..156eb9c 100644 --- a/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml.cs +++ b/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml.cs @@ -1,8 +1,5 @@ using System.Collections.Generic; -using System.IO; using System.Linq; -using System.Text; -using System.Text.Json; using Avalonia.Controls; using RynthCore.App; @@ -30,119 +27,10 @@ internal partial class AccountProfileDialog : Window ? "No password is saved for this profile yet." : "A password is already saved for this profile. It stays hidden unless you replace or clear it."; - PopulateCharacterDropdown(profile.AccountName, GetSelectedServerName(), profile.CharacterName); - - // Re-populate characters when account name or server changes - AccountBox.TextChanged += (_, _) => - { - string currentChar = GetSelectedCharacterName(); - PopulateCharacterDropdown(AccountBox.Text?.Trim() ?? string.Empty, GetSelectedServerName(), currentChar); - }; - ServerComboBox.SelectionChanged += (_, _) => - { - PopulateCharacterDropdown(AccountBox.Text?.Trim() ?? string.Empty, GetSelectedServerName(), GetSelectedCharacterName()); - }; - SaveButton.Click += (_, _) => SaveAndClose(); CancelButton.Click += (_, _) => Close(false); } - private string GetSelectedServerName() => - ServerComboBox.SelectedIndex >= 0 && ServerComboBox.SelectedIndex < _servers.Count - ? _servers[ServerComboBox.SelectedIndex].Name - : string.Empty; - - private void PopulateCharacterDropdown(string accountName, string serverName, string selectedCharacter) - { - List chars = LoadDetectedCharacters(accountName, serverName); - - // Ensure the existing saved name appears even if the scan file is empty - if (!string.IsNullOrEmpty(selectedCharacter) - && selectedCharacter != LaunchAccountProfile.NoneOption - && !chars.Contains(selectedCharacter)) - { - chars.Insert(0, selectedCharacter); - } - - // "(None)" sentinel at the top so users can opt out of auto-login per account - chars.Insert(0, LaunchAccountProfile.NoneOption); - - CharacterBox.ItemsSource = chars; - - if (string.IsNullOrEmpty(selectedCharacter) || selectedCharacter == LaunchAccountProfile.NoneOption) - CharacterBox.SelectedItem = LaunchAccountProfile.NoneOption; - else if (chars.Contains(selectedCharacter)) - CharacterBox.SelectedItem = selectedCharacter; - } - - private string GetSelectedCharacterName() => - CharacterBox.SelectedItem as string ?? string.Empty; - - private static List LoadDetectedCharacters(string accountName, string serverName = "") - { - try - { - List cachedCharacters = CharacterCacheStore.Read(accountName, serverName); - if (cachedCharacters.Count > 0) - return cachedCharacters; - - // 3. ThwargLauncher character files - return ReadThwargCharacters(accountName, serverName); - } - catch - { - return []; - } - } - - private static List ReadThwargCharacters(string accountName, string serverName = "") - { - try - { - string charDir = Path.Combine( - System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData), - "ThwargLauncher", "characters"); - - if (!Directory.Exists(charDir)) - return []; - - var results = new List(); - foreach (string file in Directory.GetFiles(charDir, "*.txt")) - { - try - { - string json = File.ReadAllText(file); - using var doc = JsonDocument.Parse(json); - foreach (var entry in doc.RootElement.EnumerateObject()) - { - bool accountMatches = string.IsNullOrWhiteSpace(accountName) || - entry.Name.EndsWith("-" + accountName, System.StringComparison.OrdinalIgnoreCase); - bool serverMatches = string.IsNullOrWhiteSpace(serverName) || - entry.Name.StartsWith(serverName + "-", System.StringComparison.OrdinalIgnoreCase); - - if (!accountMatches || !serverMatches) continue; - if (!entry.Value.TryGetProperty("CharacterList", out var list)) continue; - - foreach (var charEl in list.EnumerateArray()) - { - if (charEl.TryGetProperty("Name", out var nameEl)) - { - string name = nameEl.GetString() ?? string.Empty; - if (!string.IsNullOrEmpty(name) && !results.Contains(name)) - results.Add(name); - } - } - } - } - catch { } - } - return results; - } - catch - { - return []; - } - } private void SaveAndClose() { if (string.IsNullOrWhiteSpace(AccountBox.Text)) @@ -164,7 +52,6 @@ internal partial class AccountProfileDialog : Window _profile.Password = PasswordBox.Text; } - _profile.CharacterName = GetSelectedCharacterName(); _profile.Alias = AliasBox.Text?.Trim() ?? string.Empty; Close(true); diff --git a/src/RynthCore.Engine/Compatibility/CharacterCaptureHooks.cs b/src/RynthCore.Engine/Compatibility/CharacterCaptureHooks.cs index 41b8235..f07a5a6 100644 --- a/src/RynthCore.Engine/Compatibility/CharacterCaptureHooks.cs +++ b/src/RynthCore.Engine/Compatibility/CharacterCaptureHooks.cs @@ -61,6 +61,14 @@ internal static class CharacterCaptureHooks private static int _autoLoginScheduled; + // Latches once auto-login has fired in this process. The character-list packet + // (0xF658) arrives every time the client sees char-select — including the + // logout-to-char-select transition — and without this latch we'd re-trigger + // auto-login the moment the user manually logs out. One-shot per process: if + // the user wants to swap characters, they can pick from char-select manually, + // or relaunch. + private static int _autoLoginEverFired; + public static void ProcessPotentialCharacterMessage(IntPtr blob, bool isGameEvent = false) { if (blob == IntPtr.Zero) @@ -269,6 +277,15 @@ internal static class CharacterCaptureHooks if (string.IsNullOrWhiteSpace(targetCharacter)) return; + // One-shot per process: if auto-login already fired (and the user has + // since logged back out), don't re-trigger. This keeps a manual logout + // from instantly re-logging the same character. + if (Interlocked.CompareExchange(ref _autoLoginEverFired, 1, 0) != 0) + { + RynthLog.Verbose($"CharacterCapture: Auto-login already fired this session — skipping for '{targetCharacter}'."); + return; + } + if (Interlocked.Exchange(ref _autoLoginScheduled, 1) != 0) return; diff --git a/src/RynthCore.Engine/Compatibility/ChatHooks.cs b/src/RynthCore.Engine/Compatibility/ChatHooks.cs index a1a569e..cc08e52 100644 --- a/src/RynthCore.Engine/Compatibility/ChatHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ChatHooks.cs @@ -117,6 +117,17 @@ internal static class ChatHooks /// public static unsafe void TickHide() { + // CRITICAL: do not call SetVisible while AC is between in-world sessions. + // _gmMainChatInstance points at AC's gmMainChatUI singleton, which AC + // frees during the logout-to-charselect transition. Calling SetVisible + // on the freed pointer dereferences a stale vtable (filled with reused + // float/zero data) and AVs inside UIElement::IsVisible. We resume the + // assertion only after the next SendLoginCompleteNotification, by which + // time AC has rebuilt gmMainChatUI and ListenDetour has re-captured the + // fresh pointer. + if (!LoginLifecycleHooks.HasObservedLoginComplete) + return; + IntPtr inst = _gmMainChatInstance; if (inst == IntPtr.Zero) return; @@ -142,4 +153,16 @@ internal static class ChatHooks _isHiddenAsserted = false; } } + + /// + /// Drops the cached gmMainChatUI singleton pointer. Called from the + /// logout pipeline so we don't reuse a freed pointer after the next login — + /// re-captures the fresh instance on the next + /// chat-UI message dispatch. + /// + public static void ResetCachedInstance() + { + _gmMainChatInstance = IntPtr.Zero; + _isHiddenAsserted = false; + } } diff --git a/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs b/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs index 346da27..d918b15 100644 --- a/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs @@ -561,14 +561,29 @@ internal static class ClientObjectHooks return false; training = unchecked((int)skill.AdvancementClass); - buffed = unchecked((int)(skill.InitialLevel + skill.LevelFromPracticePoints)); + + // Use CACQualities::InqSkill(stype, retval, raw=0) for the FULL buffed + // skill — that includes attribute contribution, augmentations, and + // spell-buff enchantments. The raw struct fields (InitialLevel + + // LevelFromPracticePoints) only give the base trained level and miss + // everything else, which is why this used to return ~208 for a + // character whose true buffed Creature Enchantment was 360+. + int rawBase = unchecked((int)(skill.InitialLevel + skill.LevelFromPracticePoints)); + int trulyBuffed = rawBase; + if (_inqSkillLevel != null) + { + int retval = 0; + if (_inqSkillLevel(qualitiesPtr, skillStype, &retval, 0) != 0) + trulyBuffed = retval; + } + buffed = trulyBuffed; if (_skillProbeLogCount < 6) { _skillProbeLogCount++; RynthLog.Verbose( $"Compat: skillTableProbe obj=0x{objectId:X8} skill={skillStype} qualities=0x{qualitiesPtr.ToInt32():X8} " + - $"table=0x{skillTablePtr.ToInt32():X8} buckets={tableSize} training={training} base={buffed}"); + $"table=0x{skillTablePtr.ToInt32():X8} buckets={tableSize} training={training} base={rawBase} buffed={buffed}"); } return true; diff --git a/src/RynthCore.Engine/Compatibility/LoginLifecycleHooks.cs b/src/RynthCore.Engine/Compatibility/LoginLifecycleHooks.cs index 81ba67c..e007172 100644 --- a/src/RynthCore.Engine/Compatibility/LoginLifecycleHooks.cs +++ b/src/RynthCore.Engine/Compatibility/LoginLifecycleHooks.cs @@ -92,6 +92,18 @@ internal static class LoginLifecycleHooks } } + /// + /// Clears the one-shot observation flag so the next SendLoginCompleteNotification + /// raises again. Called by the logout pipeline so the + /// following login (e.g. swapping characters) re-runs login-gated startup. + /// + public static void ResetObservation() + { + HasObservedLoginComplete = false; + _statusMessage = "Awaiting next SendLoginCompleteNotification."; + _waitingLogged = false; + } + public static void Poll() { if (HasObservedLoginComplete || !IsInstalled) diff --git a/src/RynthCore.Engine/Compatibility/LogoutLifecycleHooks.cs b/src/RynthCore.Engine/Compatibility/LogoutLifecycleHooks.cs new file mode 100644 index 0000000..58b1b9a --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/LogoutLifecycleHooks.cs @@ -0,0 +1,168 @@ +using System; +using System.Runtime.InteropServices; +using System.Threading; +using RynthCore.Engine.Hooking; + +namespace RynthCore.Engine.Compatibility; + +/// +/// Hooks the moments when the AC client commits to ending the in-world session, so the +/// engine can close its UI gate before AC starts rebuilding its UIElement tree — +/// touching world data while AC is mid-teardown crashes the client. +/// +/// We hook both: +/// - CPlayerSystem::ExecuteLogOff(void) — fires when the player has confirmed +/// the logoff prompt and the actual logoff begins. This is the earliest reliable +/// "we're committed to leaving the world" signal. (NOT +/// gmGamePlayUI::RecvNotice_EndCharacterSession — that fires when the user +/// clicks the Exit-to-Character-Selection menu item, BEFORE the confirmation +/// prompt; if we close the UI there and the user clicks "No" on the prompt, the +/// overlay is hidden while gameplay continues.) +/// - gmGamePlayUI::RecvNotice_Logoff(void) — server-driven full logoff +/// notice. Belt-and-braces in case ExecuteLogOff is bypassed in some flow. +/// +/// Either one raises once per logout cycle. +/// +/// Public symbol addresses taken from Chorizite's acclient.map: +/// - CPlayerSystem::ExecuteLogOff: file offset 0x0015D4A0, VA 0x0055E4A0 +/// - RecvNotice_Logoff: file offset 0x000EBBA0, VA 0x004ECBA0 +/// (Standard 0x56D000 acclient.exe build.) +/// +internal static class LogoutLifecycleHooks +{ + private const int ExpectedImageSize = 0x56D000; + private const int ExecuteLogOffFileOffset = 0x0015D4A0; + private const int RecvNoticeLogoffFileOffset = 0x000EBBA0; + + [UnmanagedFunctionPointer(CallingConvention.ThisCall)] + private delegate void ThisCallVoidDelegate(IntPtr thisPtr); + + private static ThisCallVoidDelegate? _originalExecuteLogOff; + private static ThisCallVoidDelegate? _executeLogOffDetour; + private static IntPtr _executeLogOffAddress; + + private static ThisCallVoidDelegate? _originalRecvNoticeLogoff; + private static ThisCallVoidDelegate? _recvNoticeLogoffDetour; + private static IntPtr _logoffAddress; + + private static string _statusMessage = "Not probed yet."; + + public static bool IsInstalled { get; private set; } + public static bool HasObservedLogout { get; private set; } + public static string StatusMessage => _statusMessage; + + /// Fires once per logout cycle, after the first observed logout signal returns from its original. + public static event Action? LogoutComplete; + + public static void Initialize() + { + if (IsInstalled) + return; + + if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection)) + { + _statusMessage = "acclient.exe not available."; + return; + } + + int imageSize = textSection.ImageSize; + if (imageSize != ExpectedImageSize) + RynthLog.Compat($"Compat: logout lifecycle hook using unverified acclient image size 0x{imageSize:X} (expected 0x{ExpectedImageSize:X})."); + + bool anyHooked = false; + anyHooked |= TryInstallHook(textSection, ExecuteLogOffFileOffset, ExecuteLogOffDetour, + out _executeLogOffAddress, out _executeLogOffDetour, out _originalExecuteLogOff, + "CPlayerSystem::ExecuteLogOff"); + anyHooked |= TryInstallHook(textSection, RecvNoticeLogoffFileOffset, RecvNoticeLogoffDetour, + out _logoffAddress, out _recvNoticeLogoffDetour, out _originalRecvNoticeLogoff, + "gmGamePlayUI::RecvNotice_Logoff"); + + if (anyHooked) + { + IsInstalled = true; + RynthLog.Compat($"Compat: logout lifecycle hook ready - ExecuteLogOff=0x{_executeLogOffAddress.ToInt32():X8} Logoff=0x{_logoffAddress.ToInt32():X8}"); + } + } + + private static bool TryInstallHook( + AcClientTextSection textSection, int fileOffset, ThisCallVoidDelegate detour, + out IntPtr address, out ThisCallVoidDelegate detourField, out ThisCallVoidDelegate? original, + string name) + { + try + { + address = new IntPtr(textSection.TextBaseVa + fileOffset); + detourField = detour; + + IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(detourField); + original = Marshal.GetDelegateForFunctionPointer(MinHook.HookCreate(address, detourPtr)); + Thread.MemoryBarrier(); + MinHook.Enable(address); + + _statusMessage = $"Hooked {name} @ 0x{address.ToInt32():X8}."; + return true; + } + catch (Exception ex) + { + address = IntPtr.Zero; + detourField = detour; + original = null; + _statusMessage = ex.Message; + RynthLog.Compat($"Compat: {name} hook failed - {ex.Message}"); + return false; + } + } + + /// Resets the observation flag so the next logout-class notice fires again. + public static void ResetObservation() + { + HasObservedLogout = false; + } + + private static void ExecuteLogOffDetour(IntPtr thisPtr) + { + if (!HasObservedLogout) + RynthLog.Compat("Compat: CPlayerSystem::ExecuteLogOff detour entered."); + + try { _originalExecuteLogOff!(thisPtr); } + catch { /* original must run */ } + + RaiseLogoutCompleteOnce("CPlayerSystem::ExecuteLogOff"); + } + + private static void RecvNoticeLogoffDetour(IntPtr thisPtr) + { + if (!HasObservedLogout) + RynthLog.Compat("Compat: RecvNotice_Logoff detour entered."); + + try { _originalRecvNoticeLogoff!(thisPtr); } + catch { /* original must run */ } + + RaiseLogoutCompleteOnce("gmGamePlayUI::RecvNotice_Logoff"); + } + + /// + /// Either notice may fire first (a session may receive both — ExecuteLogOff at + /// commit, RecvNotice_Logoff later from the server). Only the first one in a + /// logout cycle should drive the dispatch — subsequent ones are no-ops until + /// runs after the next login. + /// + private static void RaiseLogoutCompleteOnce(string source) + { + if (HasObservedLogout) + return; + + HasObservedLogout = true; + _statusMessage = $"Logout observed via {source}."; + RynthLog.Compat($"Compat: logout observed via {source} — raising LogoutComplete."); + + // Subscribers MUST keep their handler short — this fires on AC's UI thread. + // Long work (plugin teardown, disposing world data, etc.) must be deferred to + // the EndScene queue. + try { LogoutComplete?.Invoke(); } + catch (Exception ex) + { + RynthLog.Compat($"Compat: LogoutComplete handler threw {ex.GetType().Name}: {ex.Message}"); + } + } +} diff --git a/src/RynthCore.Engine/Compatibility/UpdateObjectInventoryHooks.cs b/src/RynthCore.Engine/Compatibility/UpdateObjectInventoryHooks.cs index 9dd2865..3af0d4c 100644 --- a/src/RynthCore.Engine/Compatibility/UpdateObjectInventoryHooks.cs +++ b/src/RynthCore.Engine/Compatibility/UpdateObjectInventoryHooks.cs @@ -178,9 +178,12 @@ internal static class UpdateObjectInventoryHooks } /// - /// Scan a range of object IDs, calling GetWeenieObject for each, and return - /// those whose containerID matches the target. This discovers items that were - /// created before the plugin loaded (e.g. pack contents at login). + /// Scan a range of object IDs and return those owned by the target container — + /// either as a contained child (containerID match) OR as a wielded child + /// (wielderID match). PublicWeenieDesc stores those as separate fields, so + /// matching only on containerID misses wielded items (weapons, armor, ammo). + /// Returning both keeps the plugin's container walk a single authoritative + /// list of "everything the player owns right now." /// private static int ScanByContainerId(uint containerId, Span itemIds) { @@ -190,9 +193,9 @@ internal static class UpdateObjectInventoryHooks for (uint id = 0x80000001; id <= 0x8000FFFF && written < itemIds.Length; id++) { if (id == containerId) continue; - if (!ClientObjectHooks.TryGetObjectOwnershipInfo(id, out uint cid, out _, out _)) + if (!ClientObjectHooks.TryGetObjectOwnershipInfo(id, out uint cid, out uint wid, out _)) continue; - if (cid == containerId) + if (cid == containerId || wid == containerId) itemIds[written++] = id; } diff --git a/src/RynthCore.Engine/CrashLogger.cs b/src/RynthCore.Engine/CrashLogger.cs index 35def58..57b925e 100644 --- a/src/RynthCore.Engine/CrashLogger.cs +++ b/src/RynthCore.Engine/CrashLogger.cs @@ -47,6 +47,9 @@ internal static class CrashLogger [DllImport("kernel32.dll", SetLastError = true)] private static extern bool GetModuleHandleExW(uint dwFlags, IntPtr lpModuleName, out IntPtr phModule); + [DllImport("kernel32.dll")] + private static extern IntPtr VirtualQuery(IntPtr lpAddress, out MEMORY_BASIC_INFORMATION lpBuffer, IntPtr dwLength); + [StructLayout(LayoutKind.Sequential)] private struct MODULEINFO { @@ -55,6 +58,34 @@ internal static class CrashLogger public IntPtr EntryPoint; } + [StructLayout(LayoutKind.Sequential)] + private struct MEMORY_BASIC_INFORMATION + { + public IntPtr BaseAddress; + public IntPtr AllocationBase; + public uint AllocationProtect; + public IntPtr RegionSize; + public uint State; + public uint Protect; + public uint Type; + } + + private const uint MEM_COMMIT = 0x00001000; + private const uint PAGE_NOACCESS = 0x00000001; + private const uint PAGE_GUARD = 0x00000100; + + // x86 CONTEXT field offsets (verified against winnt.h _CONTEXT layout). + // FloatSave occupies 112 bytes between the Dr* registers and SegGs. + private const int CTX_OFF_EDI = 156; + private const int CTX_OFF_ESI = 160; + private const int CTX_OFF_EBX = 164; + private const int CTX_OFF_EDX = 168; + private const int CTX_OFF_ECX = 172; + private const int CTX_OFF_EAX = 176; + private const int CTX_OFF_EBP = 180; + private const int CTX_OFF_EIP = 184; + private const int CTX_OFF_ESP = 196; + // GetModuleHandleEx flags private const uint GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS = 0x00000004; private const uint GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT = 0x00000002; @@ -121,7 +152,22 @@ internal static class CrashLogger RynthLog.Info( $"CRASH: code=0x{er.ExceptionCode:X8} addr=0x{er.ExceptionAddress.ToInt64():X8} " + - $"module={module} base=0x{moduleBase.ToInt64():X8} rva=0x{rva:X}"); + $"module={ShortModule(module)} base=0x{moduleBase.ToInt64():X8} rva=0x{rva:X}"); + + // Decode AV operation from ExceptionInformation[0..1] (first param = + // 0 read / 1 write / 8 DEP, second param = faulting data address). + // Only available when NumberParameters >= 2; safe to read the two + // dwords directly past the fixed EXCEPTION_RECORD header. + if (er.ExceptionCode == EXCEPTION_ACCESS_VIOLATION && er.NumberParameters >= 2) + { + int infoOffset = Marshal.SizeOf(); + uint avKind = (uint)Marshal.ReadInt32(ep.ExceptionRecord, infoOffset); + IntPtr avAddr = (IntPtr)Marshal.ReadInt32(ep.ExceptionRecord, infoOffset + 4); + string kind = avKind switch { 0 => "read", 1 => "write", 8 => "DEP", _ => $"?{avKind}" }; + RynthLog.Info($"CRASH AV: {kind} faultAddr=0x{avAddr.ToInt64():X8}"); + } + + DumpContext(ep.ContextRecord); } catch { @@ -131,6 +177,137 @@ internal static class CrashLogger return EXCEPTION_CONTINUE_SEARCH; } + /// + /// Reads the x86 CONTEXT* and emits register dump + EBP-frame walk + ESP + /// sweep. EBP frames cover compilers that preserve frame pointers (most + /// managed/CLR/NativeAOT frames); the ESP sweep is the fallback for + /// FPO-optimized native code (cimgui, acclient) where return addresses + /// still sit on the stack but EBP is repurposed. + /// + private static void DumpContext(IntPtr ctx) + { + if (ctx == IntPtr.Zero) return; + + uint eip, eax, ebx, ecx, edx, esi, edi, ebp, esp; + try + { + eip = (uint)Marshal.ReadInt32(ctx, CTX_OFF_EIP); + eax = (uint)Marshal.ReadInt32(ctx, CTX_OFF_EAX); + ebx = (uint)Marshal.ReadInt32(ctx, CTX_OFF_EBX); + ecx = (uint)Marshal.ReadInt32(ctx, CTX_OFF_ECX); + edx = (uint)Marshal.ReadInt32(ctx, CTX_OFF_EDX); + esi = (uint)Marshal.ReadInt32(ctx, CTX_OFF_ESI); + edi = (uint)Marshal.ReadInt32(ctx, CTX_OFF_EDI); + ebp = (uint)Marshal.ReadInt32(ctx, CTX_OFF_EBP); + esp = (uint)Marshal.ReadInt32(ctx, CTX_OFF_ESP); + } + catch + { + return; + } + + RynthLog.Info( + $"CRASH regs: eip=0x{eip:X8} eax=0x{eax:X8} ebx=0x{ebx:X8} ecx=0x{ecx:X8} " + + $"edx=0x{edx:X8} esi=0x{esi:X8} edi=0x{edi:X8}"); + RynthLog.Info($"CRASH regs: ebp=0x{ebp:X8} esp=0x{esp:X8}"); + + WalkEbpFrames((IntPtr)ebp); + SweepStack((IntPtr)esp); + } + + private static void WalkEbpFrames(IntPtr startEbp) + { + try + { + IntPtr cur = startEbp; + for (int frame = 0; frame < 16; frame++) + { + if (!IsReadable(cur, 8)) break; + IntPtr nextEbp = (IntPtr)Marshal.ReadInt32(cur); + IntPtr ret = (IntPtr)Marshal.ReadInt32(cur, 4); + if (ret == IntPtr.Zero) break; + + string mod = ResolveModule(ret, out IntPtr modBase); + if (modBase != IntPtr.Zero) + { + long fr = ret.ToInt64() - modBase.ToInt64(); + RynthLog.Info($" ebp[{frame:D2}] ret=0x{ret.ToInt64():X8} {ShortModule(mod)}+0x{fr:X}"); + } + else + { + RynthLog.Info($" ebp[{frame:D2}] ret=0x{ret.ToInt64():X8} "); + } + + // Stop if next frame pointer doesn't look like a higher stack address. + long delta = nextEbp.ToInt64() - cur.ToInt64(); + if (delta <= 0 || delta > 0x100000) break; + cur = nextEbp; + } + } + catch + { + } + } + + /// + /// Reads up to 96 dwords from ESP and logs each value that lands inside a + /// loaded module. For an indirect-call AV, [esp] is the return address into + /// the caller — usually the first hit identifies the bad call site. + /// + private static void SweepStack(IntPtr startEsp) + { + const int sweepDwords = 96; + try + { + int hits = 0; + for (int i = 0; i < sweepDwords; i++) + { + IntPtr addr = (IntPtr)(startEsp.ToInt64() + i * 4); + if (!IsReadable(addr, 4)) break; + IntPtr v = (IntPtr)Marshal.ReadInt32(addr); + if (v == IntPtr.Zero) continue; + + string mod = ResolveModule(v, out IntPtr modBase); + if (modBase == IntPtr.Zero) continue; + + long fr = v.ToInt64() - modBase.ToInt64(); + RynthLog.Info($" esp+0x{i*4:X3}: 0x{v.ToInt64():X8} {ShortModule(mod)}+0x{fr:X}"); + + if (++hits >= 24) break; // cap to keep log readable + } + } + catch + { + } + } + + private static bool IsReadable(IntPtr addr, int bytes) + { + try + { + if (VirtualQuery(addr, out MEMORY_BASIC_INFORMATION mbi, (IntPtr)Marshal.SizeOf()) == IntPtr.Zero) + return false; + if (mbi.State != MEM_COMMIT) return false; + if ((mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD)) != 0) return false; + + // Make sure the requested range doesn't cross out of the committed region. + long endRequested = addr.ToInt64() + bytes; + long endRegion = mbi.BaseAddress.ToInt64() + mbi.RegionSize.ToInt64(); + return endRequested <= endRegion; + } + catch + { + return false; + } + } + + private static string ShortModule(string fullPath) + { + if (string.IsNullOrEmpty(fullPath)) return ""; + int slash = fullPath.LastIndexOfAny(new[] { '\\', '/' }); + return slash >= 0 ? fullPath.Substring(slash + 1) : fullPath; + } + private static string ResolveModule(IntPtr address, out IntPtr moduleBase) { moduleBase = IntPtr.Zero; diff --git a/src/RynthCore.Engine/EntryPoint.cs b/src/RynthCore.Engine/EntryPoint.cs index 70bfd64..08c3bc9 100644 --- a/src/RynthCore.Engine/EntryPoint.cs +++ b/src/RynthCore.Engine/EntryPoint.cs @@ -266,6 +266,7 @@ public static class EntryPoint RunInitStep("RynthAi action hooks", ClientActionHooks.Initialize); RunInitStep("client helper hooks", () => ClientHelperHooks.Probe()); RunInitStep("login lifecycle hooks", LoginLifecycleHooks.Initialize); + RunInitStep("logout lifecycle hooks", LogoutLifecycleHooks.Initialize); RunInitStep("session state registry", SessionStateRegistry.Initialize); RunInitStep("UI lifecycle hooks", UiLifecycleHooks.Initialize); RunInitStep("logo bypass", LogoBypassHooks.Start); diff --git a/src/RynthCore.Engine/ImGui/RynthCoreShell.cs b/src/RynthCore.Engine/ImGui/RynthCoreShell.cs index 0413038..153029f 100644 --- a/src/RynthCore.Engine/ImGui/RynthCoreShell.cs +++ b/src/RynthCore.Engine/ImGui/RynthCoreShell.cs @@ -76,6 +76,16 @@ internal static class RynthCoreShell public static void Render(int frameCount) { ApplyTheme(); + + // Hide the entire shell while we are NOT in-world. Between RecvNotice_Logoff + // and the next SendLoginCompleteNotification the AC client tears down its + // world / UI state; rendering the bar (and the plugin shortcuts it hosts) + // during that window has been observed to crash D3D9 because plugin + // controls reach into half-released game data. + bool inWorld = LoginLifecycleHooks.HasObservedLoginComplete; + if (!inWorld) + return; + RenderControlBar(frameCount); if (_showDemoWindow) diff --git a/src/RynthCore.Engine/Plugins/LoadedPlugin.cs b/src/RynthCore.Engine/Plugins/LoadedPlugin.cs index 499b65e..e2c8a57 100644 --- a/src/RynthCore.Engine/Plugins/LoadedPlugin.cs +++ b/src/RynthCore.Engine/Plugins/LoadedPlugin.cs @@ -23,6 +23,7 @@ internal sealed class LoadedPlugin public PluginNameDelegate? GetName { get; set; } public PluginVersionDelegate? GetVersion { get; set; } public PluginOnLoginCompleteDelegate? OnLoginComplete { get; set; } + public PluginOnLogoutDelegate? OnLogout { get; set; } public PluginOnUIInitializedDelegate? OnUIInitialized { get; set; } public PluginOnBusyCountIncrementedDelegate? OnBusyCountIncremented { get; set; } public PluginOnBusyCountDecrementedDelegate? OnBusyCountDecremented { get; set; } diff --git a/src/RynthCore.Engine/Plugins/PluginContract.cs b/src/RynthCore.Engine/Plugins/PluginContract.cs index 8c2f364..53d337c 100644 --- a/src/RynthCore.Engine/Plugins/PluginContract.cs +++ b/src/RynthCore.Engine/Plugins/PluginContract.cs @@ -510,7 +510,7 @@ internal struct RynthCoreAPI /// Current API version. Bump when adding fields to RynthCoreAPI. internal static class PluginContractVersion { - public const uint Current = 56; + public const uint Current = 57; } internal static class ClientActionHookFlags @@ -551,6 +551,9 @@ internal delegate IntPtr PluginVersionDelegate(); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void PluginOnLoginCompleteDelegate(); +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal delegate void PluginOnLogoutDelegate(); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void PluginOnUIInitializedDelegate(); diff --git a/src/RynthCore.Engine/Plugins/PluginLoader.cs b/src/RynthCore.Engine/Plugins/PluginLoader.cs index 50fa296..8a23547 100644 --- a/src/RynthCore.Engine/Plugins/PluginLoader.cs +++ b/src/RynthCore.Engine/Plugins/PluginLoader.cs @@ -171,6 +171,10 @@ internal static class PluginLoader if (onLoginCompletePtr != IntPtr.Zero) plugin.OnLoginComplete = Marshal.GetDelegateForFunctionPointer(onLoginCompletePtr); + IntPtr onLogoutPtr = GetProcAddress(handle, "RynthPluginOnLogout"); + if (onLogoutPtr != IntPtr.Zero) + plugin.OnLogout = Marshal.GetDelegateForFunctionPointer(onLogoutPtr); + IntPtr onUiInitializedPtr = GetProcAddress(handle, "RynthPluginOnUIInitialized"); if (onUiInitializedPtr != IntPtr.Zero) plugin.OnUIInitialized = Marshal.GetDelegateForFunctionPointer(onUiInitializedPtr); @@ -358,6 +362,7 @@ internal static class PluginLoader { var parts = new List(4) { "init", "shutdown" }; if (p.OnLoginComplete != null) parts.Add("login"); + if (p.OnLogout != null) parts.Add("logout"); if (p.OnUIInitialized != null) parts.Add("ui"); if (p.OnBusyCountIncremented != null) parts.Add("busy+"); if (p.OnBusyCountDecremented != null) parts.Add("busy-"); diff --git a/src/RynthCore.Engine/Plugins/PluginManager.cs b/src/RynthCore.Engine/Plugins/PluginManager.cs index b7dfe5a..31d0a63 100644 --- a/src/RynthCore.Engine/Plugins/PluginManager.cs +++ b/src/RynthCore.Engine/Plugins/PluginManager.cs @@ -96,6 +96,7 @@ internal static class PluginManager private static bool _uiDispatchPending; private static bool _loginCompleteObserved; private static bool _loginDispatchPending; + private static bool _logoutDispatchPending; private static long _nextUpdateObjectDispatchTick; private static int _loadGeneration; private static RynthCoreAPI _api; @@ -225,6 +226,9 @@ internal static class PluginManager _loginCompleteObserved = LoginLifecycleHooks.HasObservedLoginComplete; _loginDispatchPending = _loginCompleteObserved; + LogoutLifecycleHooks.LogoutComplete -= OnLogoutObserved; + LogoutLifecycleHooks.LogoutComplete += OnLogoutObserved; + string normalizedEngineDir = Path.GetFullPath(engineDir); bool engineDirIsRuntime = string.Equals( Path.GetFileName(normalizedEngineDir.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)), @@ -293,6 +297,11 @@ internal static class PluginManager UiLifecycleHooks.Poll(); LoginLifecycleHooks.Poll(); SessionStateRegistry.Poll(); + + // Drain logout BEFORE any per-frame plugin activity so plugin teardown + // happens this frame and Tick/Render skip stale state. + if (_logoutDispatchPending && _initialized) + DispatchPendingLogout(); DispatchQueuedBusyCountDecremented(); DispatchQueuedBusyCountIncremented(); DispatchQueuedCombatModeChange(); @@ -694,6 +703,13 @@ internal static class PluginManager public static void RenderAll() { + // Suppress plugin rendering while we are not in-world. The window between + // RecvNotice_Logoff and the next SendLoginCompleteNotification is the + // crash zone: plugin draw paths reach into world data the AC client is + // simultaneously tearing down. + if (!_loginCompleteObserved) + return; + for (int i = 0; i < _plugins.Count; i++) { var plugin = _plugins[i]; @@ -717,6 +733,7 @@ internal static class PluginManager RynthLog.Plugin($"PluginManager: Shutting down {_plugins.Count} plugin(s)..."); UiLifecycleHooks.UiInitialized -= OnUIInitializedObserved; LoginLifecycleHooks.LoginComplete -= OnLoginCompleteObserved; + LogoutLifecycleHooks.LogoutComplete -= OnLogoutObserved; UnloadAllPlugins(); PluginLoader.CleanupShadowCopies(_shadowRootDir); _initialized = false; @@ -726,6 +743,7 @@ internal static class PluginManager _uiInitializedObserved = false; _loginDispatchPending = false; _loginCompleteObserved = false; + _logoutDispatchPending = false; _pluginsDir = ""; _shadowRootDir = ""; @@ -791,6 +809,75 @@ internal static class PluginManager RynthLog.Plugin("PluginManager: OnLoginComplete observed - queued login lifecycle callbacks."); } + /// + /// Hooked to . Runs on AC's UI + /// thread INSIDE gmGamePlayUI::RecvNotice_Logoff, so it must do as little + /// work as possible — anything heavier than flipping a flag will stall AC during + /// a critical state transition. The actual plugin teardown happens on the next + /// EndScene tick via . + /// + private static void OnLogoutObserved() + { + if (_logoutDispatchPending) + return; + + _logoutDispatchPending = true; + RynthLog.Plugin("PluginManager: OnLogout observed - queued for next EndScene frame."); + } + + /// + /// Drained from on the EndScene thread. + /// + private static void DispatchPendingLogout() + { + if (!_logoutDispatchPending) + return; + + _logoutDispatchPending = false; + + RynthLog.Plugin("PluginManager: dispatching OnLogout to plugins."); + DispatchLogoutToLoadedPlugins(); + + // Drop pointers to AC objects that the engine has cached and that AC + // frees during the world-to-charselect transition. ChatHooks caches + // gmMainChatUI for per-frame visibility assertion; using that pointer + // after AC has freed the widget AVs inside UIElement::IsVisible. The + // instance gets re-captured on the next ListenToElementMessage call + // after the next login completes. + Compatibility.ChatHooks.ResetCachedInstance(); + + // Reset login observation so the next SendLoginCompleteNotification kicks + // off a fresh login-complete cycle. + for (int i = 0; i < _plugins.Count; i++) + _plugins[i].LoginCompleteDispatched = false; + + _loginCompleteObserved = false; + _loginDispatchPending = false; + LoginLifecycleHooks.ResetObservation(); + LogoutLifecycleHooks.ResetObservation(); + } + + private static void DispatchLogoutToLoadedPlugins() + { + for (int i = 0; i < _plugins.Count; i++) + { + var plugin = _plugins[i]; + if (!plugin.Initialized || plugin.Failed || plugin.OnLogout == null) + continue; + + try + { + plugin.OnLogout(); + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} received OnLogout."); + } + catch (Exception ex) + { + plugin.Failed = true; + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnLogout threw {ex.GetType().Name}: {ex.Message}"); + } + } + } + private static void RescanPlugins(IntPtr imguiContext, IntPtr d3dDevice, IntPtr gameHwnd) { if (string.IsNullOrWhiteSpace(_pluginsDir)) diff --git a/src/RynthCore.PluginCore/RynthPluginBase.cs b/src/RynthCore.PluginCore/RynthPluginBase.cs index ff466a7..79fac48 100644 --- a/src/RynthCore.PluginCore/RynthPluginBase.cs +++ b/src/RynthCore.PluginCore/RynthPluginBase.cs @@ -37,6 +37,7 @@ public abstract class RynthPluginBase public virtual void OnTick() { } public virtual void OnUIInitialized() { } public virtual void OnLoginComplete() { } + public virtual void OnLogout() { } public virtual void OnBarAction() { } public virtual void OnRender() { } public virtual void OnChatWindowText(string? text, int chatType, ref int eat) { } diff --git a/src/RynthCore.PluginCore/RynthPluginRuntime.cs b/src/RynthCore.PluginCore/RynthPluginRuntime.cs index b7647df..f6c79eb 100644 --- a/src/RynthCore.PluginCore/RynthPluginRuntime.cs +++ b/src/RynthCore.PluginCore/RynthPluginRuntime.cs @@ -68,6 +68,12 @@ public unsafe sealed class RynthPluginRuntime _plugin!.OnLoginComplete(); } + public void OnLogout() + { + if (IsInitialized) + _plugin!.OnLogout(); + } + public void OnBarAction() { if (IsInitialized) From ac0d743e16a4fbfc485e12be27bd32af583cb443 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 4 Oct 2026 15:29:14 +0000 Subject: [PATCH 05/11] fix: replace dead tombohar URLs with aelrynth/sibling forks Point installer publisher URL at aelrynth.com/rynth.html and clone RynthSuite from the same GitHub owner in release CI. Canonical public source is https://aelrynth.com/git/RynthCore.git. Co-authored-by: BlankenshipG --- .github/workflows/release.yml | 7 +++++-- Changelog/2026-10-04-aelrynth-urls.md | 9 +++++++++ installer/RynthCore.iss | 3 ++- 3 files changed, 16 insertions(+), 3 deletions(-) create mode 100644 Changelog/2026-10-04-aelrynth-urls.md diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 965d92d..84e8d4b 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -37,9 +37,12 @@ jobs: $parent = Split-Path "$env:GITHUB_WORKSPACE" -Parent $dest = "$parent\RynthSuite" Write-Host "Cloning RynthSuite to: $dest" + # Sibling fork on the same GitHub owner (BlankenshipG in this environment). + # Canonical public source is https://aelrynth.com/git/RynthSuite.git — CI uses + # the GitHub sibling so the release build matches this fork pair. # If RynthSuite is private, set a GH_PAT secret and use the token URL: - # git clone https://x-access-token:${{ secrets.GH_PAT }}@github.com/tombohar/RynthSuite.git $dest - git clone https://github.com/tombohar/RynthSuite.git $dest + # git clone https://x-access-token:${{ secrets.GH_PAT }}@github.com/${{ github.repository_owner }}/RynthSuite.git $dest + git clone "https://github.com/${{ github.repository_owner }}/RynthSuite.git" $dest if ($LASTEXITCODE -ne 0) { throw "git clone RynthSuite failed" } # ── Toolchain ───────────────────────────────────────────────────────────── diff --git a/Changelog/2026-10-04-aelrynth-urls.md b/Changelog/2026-10-04-aelrynth-urls.md new file mode 100644 index 0000000..8670c97 --- /dev/null +++ b/Changelog/2026-10-04-aelrynth-urls.md @@ -0,0 +1,9 @@ +# Changelog — 2026-10-04 (docs/CI) + +## fix: point dead tombohar URLs at aelrynth / sibling fork + +- `installer/RynthCore.iss` `AppPublisherURL` → https://aelrynth.com/rynth.html +- `.github/workflows/release.yml` sibling clone → `github.com/${{ github.repository_owner }}/RynthSuite` +- Canonical public git remains https://aelrynth.com/git/RynthCore.git (see product page) + +No engine/SDK version bump (docs and CI URL-only). diff --git a/installer/RynthCore.iss b/installer/RynthCore.iss index 1985906..8269aef 100644 --- a/installer/RynthCore.iss +++ b/installer/RynthCore.iss @@ -13,7 +13,8 @@ AppId={{A8B4C2D1-E3F5-4678-9ABC-DEF012345678} AppName=RynthCore AppVersion=0.0.0 AppPublisher=RynthCore -AppPublisherURL=https://github.com/tombohar/RynthCore +; Canonical product/docs page (aelrynth.com); tombohar GitHub upstream is gone. +AppPublisherURL=https://aelrynth.com/rynth.html DefaultDirName=C:\Games\RynthCore DisableDirPage=no DefaultGroupName=RynthCore From 4ddbb52eb26a481b8e2457635cf24cb737ab369e Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sun, 4 Oct 2026 15:43:50 +0000 Subject: [PATCH 06/11] feat: port aelrynth 2026.9.27.2 snapshot onto GitHub history Overlay upstream/main (9b5e276) onto BlankenshipG main without rewriting history. Keep origin-only Decal/plugin/docs trees. Re-apply aelrynth.com and sibling-fork URL fixes that aelrynth git still has as tombohar links. Co-authored-by: BlankenshipG --- .github/workflows/ci-statusagent.yml | 59 + .github/workflows/release.yml | 100 +- .gitignore | 7 + BUILD.md | 195 +- Changelog/2026-10-04-aelrynth-sync.md | 12 + README.md | 93 +- RynthCore.sln | 89 +- docs/STATUS_AGENT.md | 225 + installer/Build-Installer.ps1 | 155 +- installer/New-UpdateSigningKey.ps1 | 103 + installer/Publish-Update.ps1 | 256 + installer/RynthCore.iss | 30 +- installer/Sign-Update.ps1 | 58 + native/SehTrampoline/Build-SehTrampoline.ps1 | 38 + native/SehTrampoline/SehTrampoline.c | 439 ++ scripts/Deploy-RynthCore.ps1 | 274 +- scripts/Show-AcMemoryTrend.ps1 | 344 ++ scripts/Watch-AcFreeze.ps1 | 338 ++ scripts/Watch-AcMemory.ps1 | 100 + spikes/WglDxInterop/D3D9.cs | 369 ++ spikes/WglDxInterop/Gl.cs | 201 + spikes/WglDxInterop/InteropTexture.cs | 165 + spikes/WglDxInterop/Program.cs | 337 ++ spikes/WglDxInterop/WglDxInterop.csproj | 24 + spikes/WglDxInterop/Win32.cs | 141 + spikes/WglDxInterop/findings.md | 76 + .../AccountProfileDialog.axaml | 19 +- .../AccountProfileDialog.axaml.cs | 72 + src/RynthCore.App.Avalonia/EngineJsonStore.cs | 123 + src/RynthCore.App.Avalonia/LauncherDiag.cs | 63 + .../LoginCommandsDialog.axaml | 87 + .../LoginCommandsDialog.axaml.cs | 286 ++ src/RynthCore.App.Avalonia/MainWindow.axaml | 73 +- .../MainWindow.axaml.cs | 2052 +++++++- src/RynthCore.App.Avalonia/MemorySparkline.cs | 330 ++ .../MemoryTabView.axaml | 232 + .../MemoryTabView.axaml.cs | 885 ++++ .../RynthCore.App.Avalonia.csproj | 3 + src/RynthCore.App.Avalonia/RynthUpdater.cs | 341 ++ src/RynthCore.App.Avalonia/UpdateTrust.cs | 19 + .../AcClientLaunchSettingsService.cs | 39 + src/RynthCore.App/AppSettings.cs | 36 + src/RynthCore.App/AppSettingsStore.cs | 64 +- src/RynthCore.App/BuildVersion.cs | 46 + src/RynthCore.App/CharacterCacheStore.cs | 29 +- src/RynthCore.App/DecalLocator.cs | 73 + src/RynthCore.App/InjectionMode.cs | 17 + src/RynthCore.App/LaunchAccountProfile.cs | 47 +- src/RynthCore.App/LaunchContextStore.cs | 22 +- src/RynthCore.App/SessionStateStore.cs | 25 +- .../Compatibility/AcActionTrace.cs | 79 + .../Compatibility/AcMainThreadQueue.cs | 620 +++ .../Compatibility/AccountHooks.cs | 67 +- .../Compatibility/AppraisalHooks.cs | 231 +- .../Compatibility/AutoIdService.cs | 36 +- .../Compatibility/BusyCountHooks.cs | 445 +- .../Compatibility/CObjectMaintHooks.cs | 220 + .../Compatibility/CastGate.cs | 89 + .../Compatibility/CharacterCaptureHooks.cs | 389 +- .../Compatibility/CharacterManagementHooks.cs | 157 +- .../Compatibility/ChatCallbackHooks.cs | 168 +- .../Compatibility/ChatCommandDispatcher.cs | 175 +- .../Compatibility/ChatFileDispatcher.cs | 188 + .../Compatibility/ChatHooks.cs | 138 +- .../Compatibility/ClientCombatHooks.cs | 73 +- .../Compatibility/ClientHelperHooks.cs | 379 +- .../Compatibility/ClientObjectHooks.cs | 1605 +++++- .../Compatibility/CombatActionHooks.cs | 455 +- .../Compatibility/CombatModeHooks.cs | 252 +- .../Compatibility/CommandInterpreterHooks.cs | 117 +- .../Compatibility/CreateObjectHooks.cs | 18 +- .../Compatibility/DatFileShareHooks.cs | 495 ++ .../Compatibility/DbCacheTeardownHooks.cs | 131 + .../Compatibility/DecalDetection.cs | 71 + .../Compatibility/DeleteObjectHooks.cs | 17 +- .../Compatibility/DoMotionHooks.cs | 70 +- .../Compatibility/EnchantmentHooks.cs | 66 +- .../Compatibility/EngineStatusMetrics.cs | 161 + .../Compatibility/GameTickHooks.cs | 186 + .../Compatibility/HeartbeatLogger.cs | 143 + .../Compatibility/HookResolver.cs | 190 + .../Compatibility/LoginLifecycleHooks.cs | 18 +- .../Compatibility/LogoBypassHooks.cs | 81 +- .../Compatibility/LogoffOriginProbe.cs | 802 +++ .../Compatibility/LogoutLifecycleHooks.cs | 172 +- .../Compatibility/MainThreadGuard.cs | 62 + .../Compatibility/MovementActionHooks.cs | 47 +- .../Compatibility/MultiClientHooks.cs | 115 +- .../Compatibility/ObjectQualityCache.cs | 38 +- .../Compatibility/OnLoginCommandRunner.cs | 154 + .../Compatibility/PlayerPhysicsHooks.cs | 117 +- .../Compatibility/PlayerVitalsHooks.cs | 315 +- .../Compatibility/PowerbarHooks.cs | 214 +- .../Compatibility/ProcessExitHooks.cs | 451 ++ .../Compatibility/RadarHooks.cs | 230 +- .../Compatibility/RawOpcodeTracker.cs | 14 +- .../Compatibility/RawPacketHooks.cs | 13 +- .../Compatibility/RecursionGuard.cs | 39 + .../Compatibility/RynthCoreChatCommands.cs | 84 + .../Compatibility/SalvageHooks.cs | 63 +- .../Compatibility/SehTrampoline.cs | 194 + .../Compatibility/SelectedTargetHooks.cs | 41 +- .../Compatibility/SessionStateRegistry.cs | 66 +- .../Compatibility/SmartBoxHooks.cs | 431 +- .../Compatibility/SmartBoxLocator.cs | 11 +- .../Compatibility/StringAnchorDiagnostic.cs | 108 + .../Compatibility/StringRefScanner.cs | 274 ++ .../Compatibility/TeleportStateHooks.cs | 43 +- .../Compatibility/TextParserGuardHooks.cs | 124 + .../Compatibility/ThreadStackSampler.cs | 244 + .../Compatibility/TimeSyncHooks.cs | 55 +- .../UpdateObjectInventoryHooks.cs | 68 +- .../UpdateObjectServerDispatchHooks.cs | 30 +- .../VectorUpdateServerDispatchHooks.cs | 19 +- .../Compatibility/VendorHooks.cs | 72 +- .../Compatibility/VendorTrade.cs | 1488 ++++++ .../Compatibility/ViewObjectContentsHooks.cs | 29 +- src/RynthCore.Engine/CrashDump.cs | 104 + src/RynthCore.Engine/CrashLogger.cs | 155 +- src/RynthCore.Engine/D3D9/BitmapFont.cs | 168 + src/RynthCore.Engine/D3D9/D3D9Bootstrapper.cs | 103 +- src/RynthCore.Engine/D3D9/EndSceneHook.cs | 124 +- .../D3D9/GameMatrixCapture.cs | 94 +- src/RynthCore.Engine/D3D9/Nav3DRenderer.cs | 241 +- .../D3D9/OverlayTextureRenderer.cs | 165 +- src/RynthCore.Engine/D3D9/VitalHud.cs | 706 +++ src/RynthCore.Engine/EngineLifecycle.cs | 196 + src/RynthCore.Engine/EntryPoint.cs | 1102 ++++- src/RynthCore.Engine/Hooking/MinHook.cs | 35 +- src/RynthCore.Engine/ImGui/DX9Backend.cs | 130 +- .../ImGui/EngineFrameController.cs | 582 +++ src/RynthCore.Engine/ImGui/RynthCoreShell.cs | 125 +- .../ImGui/ViewportPlatformBackend.cs | 10 +- src/RynthCore.Engine/ImGui/Win32Backend.cs | 703 ++- src/RynthCore.Engine/LogPaths.cs | 211 + .../MainThreadHangWatchdog.cs | 262 + .../Plugins/EngineSettings.cs | 255 +- src/RynthCore.Engine/Plugins/LoadedPlugin.cs | 4 + .../Plugins/PluginContract.cs | 283 +- src/RynthCore.Engine/Plugins/PluginLoader.cs | 231 +- src/RynthCore.Engine/Plugins/PluginManager.cs | 858 +++- src/RynthCore.Engine/RynthCore.Engine.csproj | 8 +- src/RynthCore.Engine/RynthLog.cs | 27 +- src/RynthCore.Engine/UI/AvaloniaOverlay.cs | 4353 ++++++++++++++++- .../UI/Dcomp/AcWindowTracker.cs | 201 + .../UI/Dcomp/DcompFloatingPanel.cs | 249 + .../UI/Dcomp/DcompOverlayApp.cs | 38 + .../UI/Dcomp/DcompOverlayBootstrap.cs | 181 + .../UI/Dcomp/DcompOverlayWindow.cs | 480 ++ src/RynthCore.Engine/UI/Dcomp/README.md | 38 + src/RynthCore.Engine/UI/LayeredWindow.cs | 1213 +++++ .../UI/OverlaySkiaPlatformGraphics.cs | 182 +- .../UI/OverlaySurfaceFrame.cs | 25 +- src/RynthCore.Engine/UI/PanelStateStore.cs | 281 ++ src/RynthCore.Engine/UI/Panels/ItemsPanel.cs | 824 ++++ src/RynthCore.Engine/UI/Panels/LogPanel.cs | 5 + src/RynthCore.Engine/UI/Panels/MetaPanel.cs | 1593 ++++++ .../UI/Panels/MetaSourceEditor.cs | 396 ++ .../UI/Panels/MonsterDamagePanel.cs | 1365 ++++++ .../UI/Panels/MonstersPanel.cs | 1064 ++++ src/RynthCore.Engine/UI/Panels/NavPanel.cs | 618 +++ src/RynthCore.Engine/UI/Panels/RadarPanel.cs | 1363 ++++++ .../UI/Panels/RynthAiPanel.cs | 2625 ++++++---- .../UI/Panels/RynthChatFiltersPanel.cs | 214 + .../UI/Panels/RynthChatPanel.cs | 1530 ++++++ .../UI/Panels/RynthNavPanel.cs | 330 ++ .../UI/Panels/RynthTrackerPanel.cs | 302 ++ .../UI/Panels/RynthVisionPanel.cs | 422 ++ .../UI/Panels/SettingsPanel.cs | 1435 ++++++ src/RynthCore.Engine/UI/Panels/StatusPanel.cs | 4 +- .../UI/SoftwareOverlaySurfaceBridge.cs | 59 +- .../RynthCore.HookManifest.csproj | 13 + .../Scanning/AcClientImageView.cs | 28 + .../Scanning/PatternScanner.cs | 105 + .../Scanning/RttiVtableScanner.cs | 170 + .../Scanning/StringRefScanner.cs | 171 + .../Schema/FunctionSnapshot.cs | 17 + .../Schema/HookManifest.cs | 27 + .../Schema/HookManifestEntry.cs | 25 + .../Schema/HookManifestJsonContext.cs | 20 + .../Schema/ResolvedAddress.cs | 6 + .../Schema/ValidationRecord.cs | 3 + .../EngineInjectionService.cs | 293 +- src/RynthCore.Injector/LaunchCommand.cs | 331 ++ src/RynthCore.Injector/Program.cs | 83 +- src/RynthCore.Loader/EntryPoint.cs | 573 +++ src/RynthCore.Loader/RynthCore.Loader.csproj | 29 + src/RynthCore.PluginCore/RynthPluginBase.cs | 12 +- .../RynthPluginRuntime.cs | 160 +- src/RynthCore.PluginSdk/RynthCoreApiNative.cs | 18 + src/RynthCore.PluginSdk/RynthCoreHost.cs | 445 +- src/RynthCore.PluginSdk/VendorTypes.cs | 238 + src/RynthCore.StatusAgent/AgentConfig.cs | 161 + src/RynthCore.StatusAgent/AgentLog.cs | 41 + src/RynthCore.StatusAgent/BackendPublisher.cs | 77 + src/RynthCore.StatusAgent/Dat/DatDatabase.cs | 395 ++ src/RynthCore.StatusAgent/Dat/DxtUtil.cs | 442 ++ src/RynthCore.StatusAgent/Dat/IconDecoder.cs | 115 + src/RynthCore.StatusAgent/IconService.cs | 125 + .../LocalStatusServer.cs | 784 +++ src/RynthCore.StatusAgent/MapService.cs | 123 + src/RynthCore.StatusAgent/Models.cs | 323 ++ src/RynthCore.StatusAgent/Program.cs | 293 ++ src/RynthCore.StatusAgent/README.md | 22 + src/RynthCore.StatusAgent/RunArchive.cs | 251 + .../RynthCore.StatusAgent.csproj | 33 + src/RynthCore.StatusAgent/ScreenCapture.cs | 214 + src/RynthCore.StatusAgent/StatusReader.cs | 294 ++ src/RynthCore.StatusAgent/VideoCapture.cs | 169 + .../VideoSocketService.cs | 118 + .../WebRtcVideoService.cs | 316 ++ .../HookResolver.Core/Diff/EngineLogParser.cs | 113 + .../Disassembly/IcedDisassembler.cs | 99 + .../Discovery/StringDiscoveryService.cs | 123 + .../Discovery/VtableDiscoveryService.cs | 69 + .../Offline/AcClientImage.cs | 6 + .../Offline/AcClientImageLoader.cs | 147 + .../Resolution/HookResolveOrchestrator.cs | 170 + .../Resolution/ManifestBuilder.cs | 46 + .../RynthCore.HookResolver.Core.csproj | 21 + tools/HookResolver.Core/Symbols/AllSymbols.cs | 554 +++ tools/HookResolver.Core/Symbols/HookSymbol.cs | 26 + .../Validation/IValidationRule.cs | 18 + .../Validation/Rules/CallTargetsRule.cs | 51 + .../Validation/Rules/PrologueBytesRule.cs | 44 + .../HookResolver.SmokeTest.csproj | 18 + tools/HookResolver.SmokeTest/Program.cs | 110 + tools/HookResolver.UI/App.axaml | 8 + tools/HookResolver.UI/App.axaml.cs | 20 + .../HookResolver.UI/DiscoveryCandidateRow.cs | 49 + tools/HookResolver.UI/HookRow.cs | 123 + tools/HookResolver.UI/MainViewModel.cs | 301 ++ tools/HookResolver.UI/MainWindow.axaml | 540 ++ tools/HookResolver.UI/MainWindow.axaml.cs | 283 ++ tools/HookResolver.UI/Program.cs | 16 + .../RynthCore.HookResolver.UI.csproj | 28 + tools/HookResolver.UI/VtableMethodRow.cs | 49 + tools/HookResolver.UI/app.manifest | 17 + tools/check-patterns.ps1 | 28 + tools/check_offthread_mutators.py | 173 + tools/pe_pattern.py | 412 ++ tools/soak_scorecard.py | 350 ++ tools/symbolicate.ps1 | 8 + tools/symbolicate.py | 204 + 244 files changed, 59585 insertions(+), 2942 deletions(-) create mode 100644 .github/workflows/ci-statusagent.yml create mode 100644 Changelog/2026-10-04-aelrynth-sync.md create mode 100644 docs/STATUS_AGENT.md create mode 100644 installer/New-UpdateSigningKey.ps1 create mode 100644 installer/Publish-Update.ps1 create mode 100644 installer/Sign-Update.ps1 create mode 100644 native/SehTrampoline/Build-SehTrampoline.ps1 create mode 100644 native/SehTrampoline/SehTrampoline.c create mode 100644 scripts/Show-AcMemoryTrend.ps1 create mode 100644 scripts/Watch-AcFreeze.ps1 create mode 100644 scripts/Watch-AcMemory.ps1 create mode 100644 spikes/WglDxInterop/D3D9.cs create mode 100644 spikes/WglDxInterop/Gl.cs create mode 100644 spikes/WglDxInterop/InteropTexture.cs create mode 100644 spikes/WglDxInterop/Program.cs create mode 100644 spikes/WglDxInterop/WglDxInterop.csproj create mode 100644 spikes/WglDxInterop/Win32.cs create mode 100644 spikes/WglDxInterop/findings.md create mode 100644 src/RynthCore.App.Avalonia/EngineJsonStore.cs create mode 100644 src/RynthCore.App.Avalonia/LauncherDiag.cs create mode 100644 src/RynthCore.App.Avalonia/LoginCommandsDialog.axaml create mode 100644 src/RynthCore.App.Avalonia/LoginCommandsDialog.axaml.cs create mode 100644 src/RynthCore.App.Avalonia/MemorySparkline.cs create mode 100644 src/RynthCore.App.Avalonia/MemoryTabView.axaml create mode 100644 src/RynthCore.App.Avalonia/MemoryTabView.axaml.cs create mode 100644 src/RynthCore.App.Avalonia/RynthUpdater.cs create mode 100644 src/RynthCore.App.Avalonia/UpdateTrust.cs create mode 100644 src/RynthCore.App/BuildVersion.cs create mode 100644 src/RynthCore.App/DecalLocator.cs create mode 100644 src/RynthCore.App/InjectionMode.cs create mode 100644 src/RynthCore.Engine/Compatibility/AcActionTrace.cs create mode 100644 src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs create mode 100644 src/RynthCore.Engine/Compatibility/CObjectMaintHooks.cs create mode 100644 src/RynthCore.Engine/Compatibility/CastGate.cs create mode 100644 src/RynthCore.Engine/Compatibility/ChatFileDispatcher.cs create mode 100644 src/RynthCore.Engine/Compatibility/DatFileShareHooks.cs create mode 100644 src/RynthCore.Engine/Compatibility/DbCacheTeardownHooks.cs create mode 100644 src/RynthCore.Engine/Compatibility/DecalDetection.cs create mode 100644 src/RynthCore.Engine/Compatibility/EngineStatusMetrics.cs create mode 100644 src/RynthCore.Engine/Compatibility/GameTickHooks.cs create mode 100644 src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs create mode 100644 src/RynthCore.Engine/Compatibility/HookResolver.cs create mode 100644 src/RynthCore.Engine/Compatibility/LogoffOriginProbe.cs create mode 100644 src/RynthCore.Engine/Compatibility/MainThreadGuard.cs create mode 100644 src/RynthCore.Engine/Compatibility/OnLoginCommandRunner.cs create mode 100644 src/RynthCore.Engine/Compatibility/ProcessExitHooks.cs create mode 100644 src/RynthCore.Engine/Compatibility/RecursionGuard.cs create mode 100644 src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs create mode 100644 src/RynthCore.Engine/Compatibility/SehTrampoline.cs create mode 100644 src/RynthCore.Engine/Compatibility/StringAnchorDiagnostic.cs create mode 100644 src/RynthCore.Engine/Compatibility/StringRefScanner.cs create mode 100644 src/RynthCore.Engine/Compatibility/TextParserGuardHooks.cs create mode 100644 src/RynthCore.Engine/Compatibility/ThreadStackSampler.cs create mode 100644 src/RynthCore.Engine/Compatibility/VendorTrade.cs create mode 100644 src/RynthCore.Engine/CrashDump.cs create mode 100644 src/RynthCore.Engine/D3D9/BitmapFont.cs create mode 100644 src/RynthCore.Engine/D3D9/VitalHud.cs create mode 100644 src/RynthCore.Engine/EngineLifecycle.cs create mode 100644 src/RynthCore.Engine/ImGui/EngineFrameController.cs create mode 100644 src/RynthCore.Engine/LogPaths.cs create mode 100644 src/RynthCore.Engine/MainThreadHangWatchdog.cs create mode 100644 src/RynthCore.Engine/UI/Dcomp/AcWindowTracker.cs create mode 100644 src/RynthCore.Engine/UI/Dcomp/DcompFloatingPanel.cs create mode 100644 src/RynthCore.Engine/UI/Dcomp/DcompOverlayApp.cs create mode 100644 src/RynthCore.Engine/UI/Dcomp/DcompOverlayBootstrap.cs create mode 100644 src/RynthCore.Engine/UI/Dcomp/DcompOverlayWindow.cs create mode 100644 src/RynthCore.Engine/UI/Dcomp/README.md create mode 100644 src/RynthCore.Engine/UI/LayeredWindow.cs create mode 100644 src/RynthCore.Engine/UI/PanelStateStore.cs create mode 100644 src/RynthCore.Engine/UI/Panels/ItemsPanel.cs create mode 100644 src/RynthCore.Engine/UI/Panels/MetaPanel.cs create mode 100644 src/RynthCore.Engine/UI/Panels/MetaSourceEditor.cs create mode 100644 src/RynthCore.Engine/UI/Panels/MonsterDamagePanel.cs create mode 100644 src/RynthCore.Engine/UI/Panels/MonstersPanel.cs create mode 100644 src/RynthCore.Engine/UI/Panels/NavPanel.cs create mode 100644 src/RynthCore.Engine/UI/Panels/RadarPanel.cs create mode 100644 src/RynthCore.Engine/UI/Panels/RynthChatFiltersPanel.cs create mode 100644 src/RynthCore.Engine/UI/Panels/RynthChatPanel.cs create mode 100644 src/RynthCore.Engine/UI/Panels/RynthNavPanel.cs create mode 100644 src/RynthCore.Engine/UI/Panels/RynthTrackerPanel.cs create mode 100644 src/RynthCore.Engine/UI/Panels/RynthVisionPanel.cs create mode 100644 src/RynthCore.Engine/UI/Panels/SettingsPanel.cs create mode 100644 src/RynthCore.HookManifest/RynthCore.HookManifest.csproj create mode 100644 src/RynthCore.HookManifest/Scanning/AcClientImageView.cs create mode 100644 src/RynthCore.HookManifest/Scanning/PatternScanner.cs create mode 100644 src/RynthCore.HookManifest/Scanning/RttiVtableScanner.cs create mode 100644 src/RynthCore.HookManifest/Scanning/StringRefScanner.cs create mode 100644 src/RynthCore.HookManifest/Schema/FunctionSnapshot.cs create mode 100644 src/RynthCore.HookManifest/Schema/HookManifest.cs create mode 100644 src/RynthCore.HookManifest/Schema/HookManifestEntry.cs create mode 100644 src/RynthCore.HookManifest/Schema/HookManifestJsonContext.cs create mode 100644 src/RynthCore.HookManifest/Schema/ResolvedAddress.cs create mode 100644 src/RynthCore.HookManifest/Schema/ValidationRecord.cs create mode 100644 src/RynthCore.Injector/LaunchCommand.cs create mode 100644 src/RynthCore.Loader/EntryPoint.cs create mode 100644 src/RynthCore.Loader/RynthCore.Loader.csproj create mode 100644 src/RynthCore.PluginSdk/VendorTypes.cs create mode 100644 src/RynthCore.StatusAgent/AgentConfig.cs create mode 100644 src/RynthCore.StatusAgent/AgentLog.cs create mode 100644 src/RynthCore.StatusAgent/BackendPublisher.cs create mode 100644 src/RynthCore.StatusAgent/Dat/DatDatabase.cs create mode 100644 src/RynthCore.StatusAgent/Dat/DxtUtil.cs create mode 100644 src/RynthCore.StatusAgent/Dat/IconDecoder.cs create mode 100644 src/RynthCore.StatusAgent/IconService.cs create mode 100644 src/RynthCore.StatusAgent/LocalStatusServer.cs create mode 100644 src/RynthCore.StatusAgent/MapService.cs create mode 100644 src/RynthCore.StatusAgent/Models.cs create mode 100644 src/RynthCore.StatusAgent/Program.cs create mode 100644 src/RynthCore.StatusAgent/README.md create mode 100644 src/RynthCore.StatusAgent/RunArchive.cs create mode 100644 src/RynthCore.StatusAgent/RynthCore.StatusAgent.csproj create mode 100644 src/RynthCore.StatusAgent/ScreenCapture.cs create mode 100644 src/RynthCore.StatusAgent/StatusReader.cs create mode 100644 src/RynthCore.StatusAgent/VideoCapture.cs create mode 100644 src/RynthCore.StatusAgent/VideoSocketService.cs create mode 100644 src/RynthCore.StatusAgent/WebRtcVideoService.cs create mode 100644 tools/HookResolver.Core/Diff/EngineLogParser.cs create mode 100644 tools/HookResolver.Core/Disassembly/IcedDisassembler.cs create mode 100644 tools/HookResolver.Core/Discovery/StringDiscoveryService.cs create mode 100644 tools/HookResolver.Core/Discovery/VtableDiscoveryService.cs create mode 100644 tools/HookResolver.Core/Offline/AcClientImage.cs create mode 100644 tools/HookResolver.Core/Offline/AcClientImageLoader.cs create mode 100644 tools/HookResolver.Core/Resolution/HookResolveOrchestrator.cs create mode 100644 tools/HookResolver.Core/Resolution/ManifestBuilder.cs create mode 100644 tools/HookResolver.Core/RynthCore.HookResolver.Core.csproj create mode 100644 tools/HookResolver.Core/Symbols/AllSymbols.cs create mode 100644 tools/HookResolver.Core/Symbols/HookSymbol.cs create mode 100644 tools/HookResolver.Core/Validation/IValidationRule.cs create mode 100644 tools/HookResolver.Core/Validation/Rules/CallTargetsRule.cs create mode 100644 tools/HookResolver.Core/Validation/Rules/PrologueBytesRule.cs create mode 100644 tools/HookResolver.SmokeTest/HookResolver.SmokeTest.csproj create mode 100644 tools/HookResolver.SmokeTest/Program.cs create mode 100644 tools/HookResolver.UI/App.axaml create mode 100644 tools/HookResolver.UI/App.axaml.cs create mode 100644 tools/HookResolver.UI/DiscoveryCandidateRow.cs create mode 100644 tools/HookResolver.UI/HookRow.cs create mode 100644 tools/HookResolver.UI/MainViewModel.cs create mode 100644 tools/HookResolver.UI/MainWindow.axaml create mode 100644 tools/HookResolver.UI/MainWindow.axaml.cs create mode 100644 tools/HookResolver.UI/Program.cs create mode 100644 tools/HookResolver.UI/RynthCore.HookResolver.UI.csproj create mode 100644 tools/HookResolver.UI/VtableMethodRow.cs create mode 100644 tools/HookResolver.UI/app.manifest create mode 100644 tools/check-patterns.ps1 create mode 100644 tools/check_offthread_mutators.py create mode 100644 tools/pe_pattern.py create mode 100644 tools/soak_scorecard.py create mode 100644 tools/symbolicate.ps1 create mode 100644 tools/symbolicate.py diff --git a/.github/workflows/ci-statusagent.yml b/.github/workflows/ci-statusagent.yml new file mode 100644 index 0000000..b719374 --- /dev/null +++ b/.github/workflows/ci-statusagent.yml @@ -0,0 +1,59 @@ +name: CI — StatusAgent build + +# Builds on a Windows runner so the (otherwise Windows/NativeAOT-only) code is +# actually compiled in CI, and publishes a standalone RynthCore.StatusAgent.exe +# as a downloadable artifact. Runs on PRs that touch source + on manual dispatch. +on: + pull_request: + paths: + - 'src/**' + - '.github/workflows/ci-statusagent.yml' + workflow_dispatch: + +jobs: + build: + runs-on: windows-latest + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup .NET 10 + uses: actions/setup-dotnet@v4 + with: + dotnet-version: '10.0.x' + + # ── Compile-check the engine-side changes (managed build; no ILC/AOT link, + # no RynthSuite needed — this just verifies the C# compiles). ────────── + - name: Compile-check RynthCore.Engine + shell: pwsh + run: | + dotnet build src/RynthCore.Engine/RynthCore.Engine.csproj -c Release + if ($LASTEXITCODE -ne 0) { throw "RynthCore.Engine failed to compile" } + + # ── Build + publish the StatusAgent as a standalone single-file exe so it + # runs on the gaming PC with no .NET install. ────────────────────────── + - name: Publish RynthCore.StatusAgent (self-contained win-x64) + shell: pwsh + run: | + dotnet publish src/RynthCore.StatusAgent/RynthCore.StatusAgent.csproj ` + -c Release -r win-x64 --self-contained true ` + -p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true ` + -o publish/StatusAgent + if ($LASTEXITCODE -ne 0) { throw "RynthCore.StatusAgent failed to publish" } + Get-ChildItem publish/StatusAgent | Format-Table Name,Length + + - name: Smoke test (--once --dry-run) + shell: pwsh + run: | + # No status files / no AC running on the runner, so this just proves the + # exe starts, reads cleanly, and exits 0 in local print-only mode. + ./publish/StatusAgent/RynthCore.StatusAgent.exe --once --dry-run --verbose + if ($LASTEXITCODE -ne 0) { throw "StatusAgent smoke test exited $LASTEXITCODE" } + + - name: Upload StatusAgent artifact + uses: actions/upload-artifact@v4 + with: + name: RynthCore.StatusAgent-win-x64 + path: publish/StatusAgent/** + if-no-files-found: error diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 84e8d4b..7421c81 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -10,6 +10,10 @@ on: description: 'Version number (e.g. 0.3) — creates tag v' required: true default: '0.3' + rynthsuite_ref: + description: 'RynthSuite ref to build against (tag/branch/SHA). Blank = matching version tag, else default branch.' + required: false + default: '' push: tags: - 'v*' @@ -31,12 +35,21 @@ jobs: - name: Checkout RynthCore uses: actions/checkout@v4 - - name: Checkout RynthSuite (sibling of RynthCore) + # Pin the sibling to the matching version tag so a tagged release is + # REPRODUCIBLE (otherwise it builds against whatever RynthSuite main is at + # build time — PluginContractVersion skew is one push away). Falls back to + # the default branch (with a CI warning) if the matching tag doesn't exist + # yet, e.g. a manual dispatch before RynthSuite is tagged. + - name: Checkout RynthSuite (sibling, pinned) shell: pwsh run: | $parent = Split-Path "$env:GITHUB_WORKSPACE" -Parent $dest = "$parent\RynthSuite" - Write-Host "Cloning RynthSuite to: $dest" + if ("${{ github.event_name }}" -eq "push") { $want = "${{ github.ref_name }}" } + else { $want = "v${{ github.event.inputs.version }}" } + $override = "${{ github.event.inputs.rynthsuite_ref }}" + if ($override) { $want = $override } + Write-Host "Cloning RynthSuite to: $dest (pin target: $want)" # Sibling fork on the same GitHub owner (BlankenshipG in this environment). # Canonical public source is https://aelrynth.com/git/RynthSuite.git — CI uses # the GitHub sibling so the release build matches this fork pair. @@ -44,17 +57,53 @@ jobs: # git clone https://x-access-token:${{ secrets.GH_PAT }}@github.com/${{ github.repository_owner }}/RynthSuite.git $dest git clone "https://github.com/${{ github.repository_owner }}/RynthSuite.git" $dest if ($LASTEXITCODE -ne 0) { throw "git clone RynthSuite failed" } + git -C $dest fetch --tags --quiet + if ($want -and (git -C $dest rev-parse --verify --quiet "$want^{commit}")) { + git -C $dest checkout --quiet $want + if ($LASTEXITCODE -ne 0) { throw "checkout RynthSuite $want failed" } + Write-Host "RynthSuite pinned to: $want" + } else { + Write-Host "::warning::RynthSuite ref '$want' not found; building against default branch HEAD (NOT reproducible)" + } + Write-Host "RynthSuite at commit: $(git -C $dest rev-parse HEAD)" # ── Toolchain ───────────────────────────────────────────────────────────── - - name: Setup .NET 9 + - name: Setup .NET 10 uses: actions/setup-dotnet@v4 with: - dotnet-version: '9.0.x' + dotnet-version: '10.0.x' - name: Install Inno Setup 6 run: choco install innosetup --yes --no-progress shell: pwsh + - name: Setup Python (for validation gates) + uses: actions/setup-python@v5 + with: + python-version: '3.12' + + # ── Validation gates (fail the release before building if any trips) ─────── + # Gate 1: off-thread AC-mutator check — guards the off-thread-mutation AV + # class (the root of the 2026-06 crash week). Pure source scan, no binary. + # Gate 2: LootSdk golden tests — 60+ assertions on the loot-profile parser + # that ships in the bundled plugin (run against the pinned RynthSuite). + # Gate 3 (pe_pattern CHECK) is LOCAL-ONLY: it needs the 1.4 GB acclient.exe + # that CI doesn't have, so it runs as a pre-deploy gate in Deploy-RynthCore.ps1. + - name: Validation gates + shell: pwsh + run: | + $parent = Split-Path "$env:GITHUB_WORKSPACE" -Parent + Write-Host "== Gate 1: off-thread AC-mutator check ==" + python "$env:GITHUB_WORKSPACE\tools\check_offthread_mutators.py" + if ($LASTEXITCODE -ne 0) { throw "off-thread mutator gate FAILED — an AC mutator is reachable off the main thread" } + + Write-Host "== Gate 2: LootSdk golden tests ==" + dotnet run --project "$parent\RynthSuite\Tools\RynthCore.LootSdkTests\RynthCore.LootSdkTests.csproj" -c Release + if ($LASTEXITCODE -ne 0) { throw "LootSdk golden tests FAILED" } + + Write-Host "== Gate 3: pe_pattern CHECK — LOCAL ONLY ==" + Write-Host " (skipped in CI: needs the 1.4 GB acclient.exe; runs pre-deploy via Deploy-RynthCore.ps1)" + # ── Determine version ────────────────────────────────────────────────────── - name: Resolve version id: ver @@ -102,17 +151,42 @@ jobs: ## Installation 1. Download **RynthCore-Setup.exe** below and run it - 2. Start Asheron's Call and log in to your character - 3. Open **RynthCore** from the Start Menu or Desktop shortcut - 4. Click **Inject Running AC** in the launcher - 5. The RynthAi panel will appear inside the AC window + 2. Open **RynthCore** from the Start Menu or Desktop shortcut --- - **First-time setup** — in the RynthCore launcher: - - Set your `acclient.exe` path under **Runtime Paths** if prompted - - The plugin auto-loads from `C:\Games\RynthCore\Runtime\Plugins\` + ## ⚠ Important first-time setup - Loot, nav, and meta profiles go in `C:\Games\RynthSuite\RynthAi\` + ### 1. Second AC client install (required for multi-client coexistence) - Log file: `%USERPROFILE%\Desktop\RynthCore.log` + If you also play Asheron's Call through ThwargLauncher or another launcher, you **must** keep a separate copy of the AC client for RynthCore launches. Otherwise the two stacks fight over the same DAT files and one of them will fail with "cannot access the data files." + + Run this once in PowerShell: + + ```powershell + robocopy "C:\Turbine\Asheron's Call" "C:\Games\RynthCore\AcClient" /E /MT:8 /NFL /NDL /NJH /NJS /NP /XF "acclient_*.log" "acclient.log" + ``` + + Then in the RynthCore launcher, set **AC Client Path** to: + ``` + C:\Games\RynthCore\AcClient\acclient.exe + ``` + + (~1.4 GB extra disk. The two installs share `Documents\Asheron's Call\UserPreferences.ini` so multi-port stays in sync.) + + ### 2. Add the RynthAi plugin (opt-in) + + The installer drops the plugin DLL at `C:\Games\RynthSuite\RynthAi\RynthCore.Plugin.RynthAi.dll`. The engine does **not** auto-scan a Plugins folder. To enable RynthAi: + + - Open the launcher → **Plugins** tab → **Add Plugin DLL** + - Browse to `C:\Games\RynthSuite\RynthAi\RynthCore.Plugin.RynthAi.dll` + - Launch AC. The RynthAi panel appears inside the AC window. + + Loot, nav, and meta profiles also live under `C:\Games\RynthSuite\RynthAi\`. + + --- + + ## Logs + + - Unified RynthCore log: `C:\Games\RynthCore\Logs\RynthCore.log` + - Crash dumps and engine init traces show up there with `[loader]`, `[engine]`, `[plugin]`, and `[compat]` tags. diff --git a/.gitignore b/.gitignore index 7b4ebe5..6c1088b 100644 --- a/.gitignore +++ b/.gitignore @@ -3,6 +3,8 @@ **/obj/ artifacts/ TestResults/ +**/__pycache__/ +*.pyc # IDE and local tooling .vs/ @@ -42,3 +44,8 @@ scratch/ # Installer build artifacts installer/staging/ installer/Output/ +installer/Releases/ + +# Process Monitor / debug log dumps (session junk) +*.PML +Logfile*.XML diff --git a/BUILD.md b/BUILD.md index 8621a80..0f5b1f0 100644 --- a/BUILD.md +++ b/BUILD.md @@ -4,59 +4,78 @@ RynthCore is the injection framework. RynthSuite (separate repo) contains the pl ## Prerequisites -- Windows 10/11 -- .NET 9 SDK (x86) -- Visual Studio 2022 Build Tools with the .NET desktop and C++ desktop workloads (required by the NativeAOT ILC linker) +- Windows 10 or 11 +- **.NET 10 SDK (x86)** +- Visual Studio 2022 Build Tools with the **.NET desktop** and **C++ desktop** workloads (required by the NativeAOT ILC linker) - Asheron's Call client installed ## Projects | Project | Type | Output | |---------|------|--------| -| `src/RynthCore.Engine` | NativeAOT x86 DLL | Injected into acclient.exe — hooks D3D9 EndScene, hosts ImGui overlay | -| `src/RynthCore.Injector` | Console app | Injects the engine DLL via LoadLibrary + CreateRemoteThread | -| `src/RynthCore.App.Avalonia` | Avalonia desktop app | Desktop launcher — server/account profiles, plugin management, launches + injects | -| `src/RynthCore.PluginSdk` | Class library | Public host API surface for plugins | -| `src/RynthCore.PluginCore` | Class library | Runtime helpers for plugin bootstrap/lifecycle | -| `src/RynthCore.App` | Shared source | Model and service files linked by both the Avalonia app and the Engine (not a standalone project) | +| `src/RynthCore.Loader` | NativeAOT x86 DLL | Injected into acclient.exe — owns `RynthCoreInit` export and hot-loads the Engine. | +| `src/RynthCore.Engine` | NativeAOT x86 DLL | The runtime engine — pattern-scans `acclient.exe` hooks, hosts D3D9/ImGui overlay, runs plugins. | +| `src/RynthCore.Injector` | x86 console | Standalone CLI injector via `LoadLibrary` + `CreateRemoteThread`. The launcher embeds the same `EngineInjectionService` directly. | +| `src/RynthCore.App.Avalonia` | Avalonia desktop app | The launcher — server/account profiles, plugin management, suspended-launch + early-inject. | +| `src/RynthCore.PluginSdk` | Class library | Public host API surface for plugins. | +| `src/RynthCore.PluginCore` | Class library | `RynthPluginBase` + lifecycle dispatch helpers. | +| `src/RynthCore.App` | Shared source | Service classes linked into both Engine and Avalonia launcher (not a standalone build target). | + +All projects target **`net10.0-windows`**. NativeAOT projects (Loader, Engine, plugins) are `x86` only with `RuntimeIdentifier=win-x86` and `PublishAot=true`. ## Publish Commands -### Launcher (Avalonia) +### Whole solution -```bash -cd C:\Projects\RynthCore\src\RynthCore.App.Avalonia -dotnet build -c Release +```powershell +dotnet build .\RynthCore.sln -c Release ``` -Output: `bin\Release\net9.0-windows7.0\RynthCore.App.Avalonia.dll` +This compiles every project including the Loader (which is now in the .sln). Note: `dotnet build` is enough for the launcher and SDK projects, but **NativeAOT projects require `dotnet publish`** to actually produce the native DLL with exports — see below. -### Engine (NativeAOT — slow first build, ~2 min) +### Loader (NativeAOT x86 — small, fast) + +```powershell +dotnet publish .\src\RynthCore.Loader\RynthCore.Loader.csproj -c Release +``` + +Output: `src\RynthCore.Loader\bin\Release\net10.0-windows\win-x86\publish\RynthCore.Loader.dll` + +### Engine (NativeAOT x86 — slow first build, ~2 min) Requires `vswhere.exe` on PATH. If the build fails with `'vswhere.exe' is not recognized`, add the VS Installer directory: -```bash -set PATH=%PATH%;C:\Program Files (x86)\Microsoft Visual Studio\Installer +```powershell +$env:PATH += ";C:\Program Files (x86)\Microsoft Visual Studio\Installer" ``` -```bash -cd C:\Projects\RynthCore\src\RynthCore.Engine -dotnet publish -c Release +```powershell +dotnet publish .\src\RynthCore.Engine\RynthCore.Engine.csproj -c Release ``` -Output: `bin\Release\net9.0-windows\win-x86\publish\RynthCore.Engine.dll` (~26 MB) +Output: `src\RynthCore.Engine\bin\Release\net10.0-windows\win-x86\publish\RynthCore.Engine.dll` (~26 MB) + +### Launcher (Avalonia) + +```powershell +dotnet build .\src\RynthCore.App.Avalonia\RynthCore.App.Avalonia.csproj -c Release +``` + +Output: `src\RynthCore.App.Avalonia\bin\Release\net10.0-windows\RynthCore.App.Avalonia.dll` ### RynthAi Plugin (NativeAOT — separate repo) -Always clean first — incremental builds can silently skip NativeAOT and produce a stale DLL. +Always clean first — incremental NativeAOT builds can silently skip recompilation and produce a stale DLL. -```bash +```powershell cd C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthAi -rmdir /s /q obj\Release bin\Release 2>nul +Remove-Item -Recurse -Force obj\Release, bin\Release -ErrorAction SilentlyContinue dotnet publish -c Release ``` -Output: `bin\Release\net9.0-windows\win-x86\publish\RynthCore.Plugin.RynthAi.dll` (~7 MB) +Output: `bin\Release\net10.0-windows\win-x86\publish\RynthCore.Plugin.RynthAi.dll` (~7 MB) + +The plugin's MSBuild target also copies the published DLL into the engine's `bin\...\Plugins\` folder so a freshly built engine picks it up automatically. ## Deploy @@ -64,80 +83,97 @@ Output: `bin\Release\net9.0-windows\win-x86\publish\RynthCore.Plugin.RynthAi.dll ``` C:\Games\RynthCore\ -├── RynthCore.exe ← Launcher (renamed from RynthCore.App.Avalonia.exe) -├── RynthCore.App.Avalonia.dll ← Launcher assembly +├── RynthCore.exe ← Launcher (renamed from RynthCore.App.Avalonia.exe) +├── RynthCore.App.Avalonia.dll ← Launcher assembly ├── RynthCore.App.Avalonia.deps.json ├── RynthCore.App.Avalonia.runtimeconfig.json -├── Avalonia.*.dll ← Avalonia framework DLLs +├── Avalonia.*.dll ← Avalonia framework DLLs └── Runtime\ - ├── RynthCore.Engine.dll ← Engine (NativeAOT x86) - ├── minhook.x86.dll ← MinHook (x86), preloaded by EntryPoint - ├── cimgui.dll ← ImGui C bindings (x86, docking branch) + ├── RynthCore.Loader.dll ← Loader (NativeAOT x86) — injection target + ├── RynthCore.Engine.dll ← Engine (NativeAOT x86) + ├── minhook.x86.dll ← MinHook (x86), preloaded by EntryPoint + ├── cimgui.dll ← ImGui C bindings (x86, docking branch) └── Plugins\ - └── *.dll ← Plugin DLLs (built-in directory) + └── *.dll ← Built-in plugin directory C:\Games\RynthSuite\RynthAi\ -├── RynthCore.Plugin.RynthAi.dll ← RynthAi plugin (recommended deploy location) -├── NavProfiles\ ← Navigation profiles -├── LootProfiles\ ← Loot profiles -└── Metas\ ← Meta files +├── RynthCore.Plugin.RynthAi.dll ← RynthAi plugin (recommended deploy location) +├── NavProfiles\ ← Navigation profiles +├── LootProfiles\ ← Loot profiles +└── Metas\ ← Meta files ``` +The injector's saved-path resolver prefers `Runtime\RynthCore.Loader.dll`. It falls back to `Runtime\RynthCore.Engine.dll` for legacy direct-load setups, and walks parent directories and sibling layouts (`Runtime\Engine\`, `Runtime\Native\`, etc.) so manual layouts continue to work. + ### Deploy Launcher The launcher can stay open while you replace its DLL. -```bash -copy src\RynthCore.App.Avalonia\bin\Release\net9.0-windows7.0\RynthCore.App.Avalonia.dll C:\Games\RynthCore\ -copy src\RynthCore.App.Avalonia\bin\Release\net9.0-windows7.0\RynthCore.App.Avalonia.deps.json C:\Games\RynthCore\ +```powershell +copy src\RynthCore.App.Avalonia\bin\Release\net10.0-windows\RynthCore.App.Avalonia.dll C:\Games\RynthCore\ +copy src\RynthCore.App.Avalonia\bin\Release\net10.0-windows\RynthCore.App.Avalonia.deps.json C:\Games\RynthCore\ ``` Restart the launcher after deploying. -### Deploy Engine +### Deploy Loader + Engine -**AC must be closed** — the running client holds a file lock on the engine DLL. +**AC must be closed** — the running client holds a file lock on the Loader and Engine DLLs. -```bash -copy src\RynthCore.Engine\bin\Release\net9.0-windows\win-x86\publish\RynthCore.Engine.dll C:\Games\RynthCore\Runtime\ +```powershell +copy src\RynthCore.Loader\bin\Release\net10.0-windows\win-x86\publish\RynthCore.Loader.dll C:\Games\RynthCore\Runtime\ +copy src\RynthCore.Engine\bin\Release\net10.0-windows\win-x86\publish\RynthCore.Engine.dll C:\Games\RynthCore\Runtime\ ``` +If you only changed Engine source, you can deploy just `RynthCore.Engine.dll` and rely on the Loader's hot-reload to swap it in (click **RL** on the overlay bar with AC running). + ### Deploy RynthAi Plugin **AC can stay open** — plugins are shadow-copied at load time, so the file is not locked. -The recommended deploy location is `C:\Games\RynthSuite\RynthAi\` — alongside the plugin's data files. Add this path in the launcher's **Plugins** tab. Paths are persisted to `%AppData%\RynthCore\engine.json`. +**Plugin discovery is opt-in:** the engine no longer auto-scans `Runtime\Plugins\` for DLLs. Plugins load only from paths the user has added via the launcher's **Plugins** tab → "Add Plugin DLL". Those paths are persisted to `%AppData%\RynthCore\engine.json` as `PluginPaths` and read by the engine on each (re)init. -```bash -copy C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthAi\bin\Release\net9.0-windows\win-x86\publish\RynthCore.Plugin.RynthAi.dll C:\Games\RynthSuite\RynthAi\ +Deploy the plugin DLL to its canonical home and add the full path in the launcher: + +``` +C:\Games\RynthSuite\RynthAi\ +├── RynthCore.Plugin.RynthAi.dll ← add this path in launcher's Plugins tab +├── NavProfiles\ +├── LootProfiles\ +└── Metas\ ``` -Alternatively, deploy to the engine's built-in plugin directory: - -```bash -copy ... C:\Games\RynthCore\Runtime\Plugins\ +```powershell +copy C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthAi\bin\Release\net10.0-windows\win-x86\publish\RynthCore.Plugin.RynthAi.dll C:\Games\RynthSuite\RynthAi\ ``` -After deploying a plugin with AC running, click **RL** on the RynthCore overlay bar to hot-reload. +After deploying the DLL: + +1. Open the RynthCore launcher +2. **Plugins** tab → **Add Plugin DLL** → select `C:\Games\RynthSuite\RynthAi\RynthCore.Plugin.RynthAi.dll` +3. Launch AC (cold start) — the engine picks up the new path on init. + +If AC is already running, click **RL** on the RynthCore overlay bar to hot-reload the engine; it re-reads `engine.json` and loads the newly-added plugin path. ## Verify | File | Expected Size | If Wrong | |------|--------------|----------| -| `Runtime\RynthCore.Engine.dll` | ~26 MB | NativeAOT didn't run — check for `Generating native code` in build output | -| `RynthSuite\RynthAi\RynthCore.Plugin.RynthAi.dll` | ~7 MB | If ~1 MB, you built the stale stub at `C:\Projects\RynthCore\Plugins\` instead of `C:\Projects\RynthSuite\Plugins\` | +| `Runtime\RynthCore.Loader.dll` | small (~1–2 MB) | NativeAOT didn't run — check for `Generating native code` in build output | +| `Runtime\RynthCore.Engine.dll` | ~26 MB | NativeAOT didn't run — same diagnosis | +| `RynthSuite\RynthAi\RynthCore.Plugin.RynthAi.dll` | ~7 MB | Built `dotnet build` instead of `dotnet publish` | | `Runtime\cimgui.dll` | ~1.5 MB | Must match ImGui.NET 1.91.6.1 | -To confirm NativeAOT actually ran, check that `.lib` and `.exp` files exist alongside the DLL in the `native\` directory. +To confirm NativeAOT actually ran, check that `.lib` and `.exp` files exist alongside the DLL in the publish output's `native\` directory. ## Installer -The `installer/` directory contains an Inno Setup script and a PowerShell build script that publishes all three projects, stages the output, and produces a single `RynthCore-Setup.exe`. +The `installer/` directory contains an Inno Setup script and a PowerShell build script that publishes all required projects, stages the output, and produces a single `RynthCore-Setup.exe`. ### Prerequisites - [Inno Setup 6](https://jrsoftware.org/isdl.php) installed to the default location (`C:\Program Files (x86)\Inno Setup 6\`) -- All build prerequisites listed above (.NET 9 SDK, VS Build Tools) +- All build prerequisites listed above (.NET 10 SDK, VS Build Tools) ### Build the installer @@ -146,7 +182,7 @@ cd C:\Projects\RynthCore\installer .\Build-Installer.ps1 ``` -This runs three `dotnet publish` steps (Launcher, Engine, Plugin), stages everything under `installer\staging\app\`, then invokes `ISCC.exe` to produce the installer. +This runs `dotnet publish` for the Launcher, Loader, Engine, and RynthAi plugin (from RynthSuite), stages everything under `installer\staging\app\`, then invokes `ISCC.exe` to produce the installer. Output: `installer\Output\RynthCore-Setup.exe` @@ -160,18 +196,45 @@ Output: `installer\Output\RynthCore-Setup.exe` ### What the installer does -- Installs the launcher, engine, and native dependencies to `C:\Games\RynthCore` (user-selectable) +- Installs the launcher, loader, engine, and native dependencies to `C:\Games\RynthCore` (user-selectable) - Creates data directories under `C:\Games\RynthSuite\RynthAi\` (NavProfiles, LootProfiles, MetaFiles, etc.) — these are preserved on uninstall - Adds Start Menu and optional Desktop shortcuts -- Warns if `acclient.exe` is running (the engine DLL would be locked) +- Warns if `acclient.exe` is running (the engine + loader DLLs would be locked) - Shows getting-started instructions on the finish page +## Multi-Client Coexistence (with ThwargLauncher etc.) + +If you also run AC through ThwargLauncher, aclauncher, or any other launcher that may not patch AC's `OpenDataFile` for shared access, the two stacks will fight over the same DAT files. Once one launcher's clients have the DATs locked exclusively, the other can't open them — symptom is **"cannot access the data files"** when launching from the second launcher. + +**Required setup**: a second AC client install for RynthCore launches. + +``` +C:\Turbine\Asheron's Call\ ← left untouched, used by ThwargLauncher etc. +C:\Games\RynthCore\AcClient\ ← full copy of the AC client (~1.4 GB), used by RynthCore +``` + +Setup: + +```powershell +robocopy "C:\Turbine\Asheron's Call" "C:\Games\RynthCore\AcClient" /E /MT:8 /NFL /NDL /NJH /NJS /NP ` + /XF "acclient_*.log" "acclient.log" +``` + +Then in the RynthCore launcher: + +1. Set **AC Client Path** to `C:\Games\RynthCore\AcClient\acclient.exe` +2. Click somewhere else / save so the change persists + +The two installs share `Documents\Asheron's Call\UserPreferences.ini` (it's user-scoped), so `ComputeUniquePort=True` applies to all instances regardless of which install they came from. + +If your AC client ever gets a real-world patch, apply it to both copies (or `robocopy /MIR` to re-sync from the canonical install). + ## Gotchas -- **`dotnet publish`, not `dotnet build` for Engine and Plugins.** NativeAOT only runs during `dotnet publish`. A `dotnet build` produces a valid managed DLL that compiles fine but has no unmanaged exports and will be silently ignored by the engine. The Avalonia launcher is the exception — `dotnet build` is fine since it's a normal .NET app. -- **Clean before plugin publish.** Incremental NativeAOT builds can silently reuse stale output. Delete `obj\Release` and `bin\Release` before every publish to guarantee a fresh compile. -- **Engine deploy path is `Runtime\`**, not `C:\Games\RynthCore\`. The injector resolves `Runtime\RynthCore.Engine.dll` by default. -- **Two RynthAi projects exist.** The real plugin is at `C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthAi\`. There is a stale stub at `C:\Projects\RynthCore\Plugins\RynthCore.Plugin.RynthAi\` — do not build or deploy from there. -- **Engine publish copies a stale plugin** into the engine's publish output. Always deploy the plugin from the RynthSuite path last. -- **cimgui.dll version must match ImGui.NET NuGet.** Post-1.90 struct layouts changed. A mismatched cimgui.dll causes `DisplaySize = <1, 1>` or font crashes. -- **vswhere.exe must be on PATH** for NativeAOT link step. Add `C:\Program Files (x86)\Microsoft Visual Studio\Installer` to PATH if missing. +- **`dotnet publish`, not `dotnet build` for Loader, Engine, and plugins.** NativeAOT only runs during `dotnet publish`. A `dotnet build` produces a valid managed DLL that compiles fine but has no unmanaged exports and will be silently ignored. The Avalonia launcher is the exception — `dotnet build` is fine since it's a normal .NET app. +- **Clean before plugin publish.** Incremental NativeAOT builds can silently reuse stale output. Delete `obj\Release` and `bin\Release` before every plugin publish to guarantee a fresh compile. +- **Engine deploy path is `Runtime\`**, not `C:\Games\RynthCore\` directly. The injector resolves `Runtime\RynthCore.Loader.dll` (preferred) and `Runtime\RynthCore.Engine.dll` (legacy) by default. +- **Close AC before redeploying Loader or Engine.** Both are loaded into `acclient.exe` and locked while the game is running. Plugins are shadow-copied so they can be hot-swapped without closing AC. +- **cimgui.dll version must match ImGui.NET NuGet.** Post-1.90 struct layouts changed. A mismatched cimgui.dll causes `DisplaySize = <1, 1>` or font crashes on frame 2. +- **vswhere.exe must be on PATH** for the NativeAOT link step. Add `C:\Program Files (x86)\Microsoft Visual Studio\Installer` to PATH if missing. +- **Decal coexistence mode.** If `decal.dll`, `UBLoader.dll`, `Decal.Adapter.dll`, or `phatacd.dll` is loaded into acclient.exe, the engine skips the entire D3D9/ImGui path and runs plugins on a 30 Hz worker tick with Avalonia floating panels via `LayeredWindow` (GDI). This is intentional — two D3D9 hookers can't symmetrically save/restore render state. Check `RynthCore.log` for `D3D9: Decal coexistence` to confirm. diff --git a/Changelog/2026-10-04-aelrynth-sync.md b/Changelog/2026-10-04-aelrynth-sync.md new file mode 100644 index 0000000..eea0256 --- /dev/null +++ b/Changelog/2026-10-04-aelrynth-sync.md @@ -0,0 +1,12 @@ +# Changelog — 2026-10-04 (upstream snapshot) + +## feat: port aelrynth git snapshot onto GitHub history + +Applied `upstream/main` (`9b5e276`, RynthCore as of 2026-09-27, release 2026.9.27.2) as a new commit on top of BlankenshipG `main`. Histories are unrelated, so this is a tree overlay — not a fast-forward or force-replace. + +- Added aelrynth-only product code: Loader, StatusAgent, HookManifest/HookResolver, DComp overlay, SEH trampoline, signed updater, vendor/trade API (PluginContract +16 functions) +- Overlapping engine/launcher files taken from aelrynth (newer than origin 2026-04-25) +- Kept unique origin-only trees: `Plugins/RynthAi/` (Decal-era), `Plugins/RynthCore.Plugin.RynthAi/` stub, `AGENTS.md`/`CLAUDE.md`, `ImGuiController.cs`, `OverlayFrameBuffer.cs` +- Re-applied dead-link fixes: installer + CI clone URLs point at aelrynth.com / `${{ github.repository_owner }}` siblings + +No PluginSdk version bump (still 0.2.0 on both trees). Packaged aelrynth installer (2026.10.4.3) is newer than this git tip. diff --git a/README.md b/README.md index 214655a..b126ccc 100644 --- a/README.md +++ b/README.md @@ -1,60 +1,70 @@ # RynthCore -RynthCore is a modern .NET 9 modding host for Asheron's Call. It combines an x86 NativeAOT in-process engine, an injector, a desktop launcher, and a plugin surface. +RynthCore is a modern .NET 10 modding host for Asheron's Call. It combines an x86 NativeAOT in-process engine, a hot-reload-capable loader, an injector, an Avalonia desktop launcher, and a plugin surface that replaces the legacy Decal + UBService + VTank stack with a self-contained RynthCore-native API. -The project is currently focused on three things: +The plugin code (RynthAi etc.) lives in a sibling repository: [RynthSuite](https://aelrynth.com/rynth.html) (`git clone https://aelrynth.com/git/RynthSuite.git`). -- launching and injecting the RynthCore engine into `acclient.exe` -- hosting in-game UI through an embedded overlay stack -- building a RynthCore-native plugin API with hooks for chat, combat, targeting, movement, object, and UI events +## What it does + +- Launches `acclient.exe` (suspended if needed) and injects the RynthCore loader +- Hosts in-game UI through an embedded ImGui overlay, with a parallel Avalonia overlay stack for floating panels (and for Decal coexistence mode where ImGui is disabled) +- Exposes a growing plugin host API with hooks for chat, combat, targeting, movement, object lifecycle, vendor/trade, vitals, enchantments, and UI events +- Hot-reloads plugin DLLs without restarting AC; hot-reloads the engine itself via the loader DLL +- Detects Decal/UBService/VTank coexistence and degrades gracefully (skips D3D9 path, drives plugin tick from a worker thread) ## Solution layout -The repository currently ships these main projects: - -- `src/RynthCore.Engine` - x86 NativeAOT runtime injected into the game client -- `src/RynthCore.Injector` - process launch and DLL injection service -- `src/RynthCore.App` - Windows desktop launcher -- `src/RynthCore.App.Avalonia` - Avalonia launcher preview and profile manager -- `src/RynthCore.PluginSdk` - public host API surface for plugins -- `src/RynthCore.PluginCore` - runtime helpers for plugin bootstrap/lifecycle -- `Plugins/RynthCore.Plugin.HelloBox` - sample plugin used for end-to-end testing - -## Current capabilities - -- injects `RynthCore.Engine.dll` into the x86 Asheron's Call client -- hosts overlay panels inside the game process -- includes launcher/profile flows for servers, accounts, and saved launch targets -- exposes a growing plugin host API for chat, target, combat, movement, object, and UI-related hooks -- includes legal guardrails and hook planning docs +``` +RynthCore.sln +├── src/RynthCore.Loader x86 NativeAOT DLL — injection target. +│ Owns RynthCoreInit; loads + reloads +│ the Engine. +├── src/RynthCore.Engine x86 NativeAOT DLL — the runtime +│ injected into acclient.exe. Pattern- +│ scanned hooks, D3D9 + ImGui + Avalonia +│ overlays, plugin manager, crash logger. +├── src/RynthCore.Injector x86 console — Win32 LoadLibrary + +│ CreateRemoteThread injector with a +│ suspended-launch / early-inject path. +├── src/RynthCore.App.Avalonia Desktop launcher (Avalonia 11.2.3, +│ Fluent theme). Profile management, +│ server status, launches and injects. +├── src/RynthCore.App Shared service classes linked into +│ both Engine and Avalonia launcher +│ via — not built +│ standalone. +├── src/RynthCore.PluginSdk Public host API surface for plugins. +└── src/RynthCore.PluginCore RynthPluginBase + lifecycle helpers. +``` ## Prerequisites -- Windows -- .NET 9 SDK -- Visual Studio 2022 with the .NET desktop and C++ desktop workloads +- Windows 10 or 11 +- **.NET 10 SDK (x86)** +- Visual Studio 2022 Build Tools with the **.NET desktop** and **C++ desktop** workloads (the C++ tools are required by the NativeAOT ILC linker) +- Asheron's Call client installed (default: `C:\Turbine\Asheron's Call\`) -The engine project targets `win-x86` and uses NativeAOT. A bundled `cimgui.dll` is included under `src/RynthCore.Engine/Native/`. +The Engine, Loader, and plugin projects target `net10.0-windows` with `RuntimeIdentifier=win-x86` and `PublishAot=true`. A bundled `cimgui.dll` ships under `src/RynthCore.Engine/Native/`. ## Build From the repository root: ```powershell -$env:DOTNET_CLI_HOME = "$PWD\\.dotnet-home" +$env:DOTNET_CLI_HOME = "$PWD\.dotnet-home" $env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE = "1" dotnet build .\RynthCore.sln -c Release ``` -To publish the main runtime pieces individually: +To publish the runtime pieces individually (use **`publish`**, not `build`, for any NativeAOT project): ```powershell +dotnet publish .\src\RynthCore.Loader\RynthCore.Loader.csproj -c Release dotnet publish .\src\RynthCore.Engine\RynthCore.Engine.csproj -c Release -dotnet publish .\src\RynthCore.App\RynthCore.App.csproj -c Release -r win-x86 dotnet publish .\src\RynthCore.App.Avalonia\RynthCore.App.Avalonia.csproj -c Release ``` -For a clean local deployment, keep the launcher at the top level of `C:\Games\RynthCore` and place the injectable engine payload under `C:\Games\RynthCore\Runtime\`. The injector now resolves `Runtime\RynthCore.Engine.dll` by default, which keeps the game folder tidier while still allowing manual overrides. +For a clean local deployment, keep the launcher at the top level of `C:\Games\RynthCore\` and place the injectable engine and loader payloads under `C:\Games\RynthCore\Runtime\`. The injector's saved-path resolver prefers `Runtime\RynthCore.Loader.dll`, falls back to `Runtime\RynthCore.Engine.dll` for legacy direct-load setups, and walks up sibling directories so manual layouts still work. You can produce that layout with: @@ -62,18 +72,21 @@ You can produce that layout with: .\scripts\Deploy-RynthCore.ps1 ``` +For full deploy details, the Inno Setup installer, and gotchas, see [`BUILD.md`](BUILD.md). + +## Documentation + +- `BUILD.md` — full build, deploy, and installer instructions +- `CLAUDE.md` — project memory file (architecture orientation, technical facts, common pitfalls) +- `docs/ACCLIENT_HOOK_INVENTORY.md` — hook target inventory against the user's live `acclient.exe` +- `docs/PLUGIN_HOOK_MATRIX.md` — clean-room hook surface matrix +- `docs/LEGAL_COMPATIBILITY.md` — project policy on Decal/VTank compatibility +- `docs/archive/` — archived plans and one-off utilities + ## Repository notes -- local settings and machine-specific files are ignored through `.gitignore` -- generated `bin/`, `obj/`, `.vs/`, and `.dotnet-home/` content should not be committed -- launcher data such as profiles and runtime state is expected to live outside the repository -- compatibility planning and legal guardrails live in `docs/` - -See: - -- `docs/ACCLIENT_HOOK_INVENTORY.md` -- `docs/PLUGIN_HOOK_MATRIX.md` -- `docs/LEGAL_COMPATIBILITY.md` +- Local settings, machine-specific files, generated `bin/`, `obj/`, `.vs/`, `.dotnet-home/` content, and launcher data (profiles, runtime state) are kept out of source control via `.gitignore` +- Plugin code lives in the [RynthSuite](https://aelrynth.com/rynth.html) repo as a sibling clone (`git clone https://aelrynth.com/git/RynthSuite.git`) ## Security and secrets diff --git a/RynthCore.sln b/RynthCore.sln index 662fa62..ab1ba16 100644 --- a/RynthCore.sln +++ b/RynthCore.sln @@ -1,4 +1,4 @@ - + Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.0.31903.59 @@ -7,7 +7,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.Engine", "src\Ryn EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.Injector", "src\RynthCore.Injector\RynthCore.Injector.csproj", "{A1B2C3D4-0002-0002-0002-000000000002}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.Plugin.RynthAi", "Plugins\RynthCore.Plugin.RynthAi\RynthCore.Plugin.RynthAi.csproj", "{A1B2C3D4-0005-0005-0005-000000000005}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.Loader", "src\RynthCore.Loader\RynthCore.Loader.csproj", "{A1B2C3D4-0006-0006-0006-000000000006}" EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}" EndProject @@ -17,6 +17,16 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.PluginSdk", "src\ EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.PluginCore", "src\RynthCore.PluginCore\RynthCore.PluginCore.csproj", "{A72E31D3-5D91-4C39-A30C-A96A492BBE82}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.HookManifest", "src\RynthCore.HookManifest\RynthCore.HookManifest.csproj", "{C1A2B3D4-0007-0007-0007-000000000007}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.StatusAgent", "src\RynthCore.StatusAgent\RynthCore.StatusAgent.csproj", "{A1B2C3D4-000A-000A-000A-00000000000A}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tools", "tools", "{52D7C9F1-3A4E-4B11-9C2D-7E1A8C3F4D89}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.HookResolver.Core", "tools\HookResolver.Core\RynthCore.HookResolver.Core.csproj", "{C1A2B3D4-0008-0008-0008-000000000008}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RynthCore.HookResolver.UI", "tools\HookResolver.UI\RynthCore.HookResolver.UI.csproj", "{C1A2B3D4-0009-0009-0009-000000000009}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x86 = Debug|x86 @@ -51,18 +61,18 @@ Global {A1B2C3D4-0002-0002-0002-000000000002}.Release|Any CPU.Build.0 = Release|Any CPU {A1B2C3D4-0002-0002-0002-000000000002}.Release|x64.ActiveCfg = Release|Any CPU {A1B2C3D4-0002-0002-0002-000000000002}.Release|x64.Build.0 = Release|Any CPU -{A1B2C3D4-0005-0005-0005-000000000005}.Debug|x86.ActiveCfg = Debug|x86 - {A1B2C3D4-0005-0005-0005-000000000005}.Debug|x86.Build.0 = Debug|x86 - {A1B2C3D4-0005-0005-0005-000000000005}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A1B2C3D4-0005-0005-0005-000000000005}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A1B2C3D4-0005-0005-0005-000000000005}.Debug|x64.ActiveCfg = Debug|Any CPU - {A1B2C3D4-0005-0005-0005-000000000005}.Debug|x64.Build.0 = Debug|Any CPU - {A1B2C3D4-0005-0005-0005-000000000005}.Release|x86.ActiveCfg = Release|x86 - {A1B2C3D4-0005-0005-0005-000000000005}.Release|x86.Build.0 = Release|x86 - {A1B2C3D4-0005-0005-0005-000000000005}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A1B2C3D4-0005-0005-0005-000000000005}.Release|Any CPU.Build.0 = Release|Any CPU - {A1B2C3D4-0005-0005-0005-000000000005}.Release|x64.ActiveCfg = Release|Any CPU - {A1B2C3D4-0005-0005-0005-000000000005}.Release|x64.Build.0 = Release|Any CPU + {A1B2C3D4-0006-0006-0006-000000000006}.Debug|x86.ActiveCfg = Debug|x86 + {A1B2C3D4-0006-0006-0006-000000000006}.Debug|x86.Build.0 = Debug|x86 + {A1B2C3D4-0006-0006-0006-000000000006}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A1B2C3D4-0006-0006-0006-000000000006}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A1B2C3D4-0006-0006-0006-000000000006}.Debug|x64.ActiveCfg = Debug|Any CPU + {A1B2C3D4-0006-0006-0006-000000000006}.Debug|x64.Build.0 = Debug|Any CPU + {A1B2C3D4-0006-0006-0006-000000000006}.Release|x86.ActiveCfg = Release|x86 + {A1B2C3D4-0006-0006-0006-000000000006}.Release|x86.Build.0 = Release|x86 + {A1B2C3D4-0006-0006-0006-000000000006}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A1B2C3D4-0006-0006-0006-000000000006}.Release|Any CPU.Build.0 = Release|Any CPU + {A1B2C3D4-0006-0006-0006-000000000006}.Release|x64.ActiveCfg = Release|Any CPU + {A1B2C3D4-0006-0006-0006-000000000006}.Release|x64.Build.0 = Release|Any CPU {2B283E05-12BB-45F9-B8E5-8F53C1FAB737}.Debug|x86.ActiveCfg = Debug|Any CPU {2B283E05-12BB-45F9-B8E5-8F53C1FAB737}.Debug|x86.Build.0 = Debug|Any CPU {2B283E05-12BB-45F9-B8E5-8F53C1FAB737}.Debug|Any CPU.ActiveCfg = Debug|Any CPU @@ -99,6 +109,54 @@ Global {A72E31D3-5D91-4C39-A30C-A96A492BBE82}.Release|Any CPU.Build.0 = Release|Any CPU {A72E31D3-5D91-4C39-A30C-A96A492BBE82}.Release|x64.ActiveCfg = Release|Any CPU {A72E31D3-5D91-4C39-A30C-A96A492BBE82}.Release|x64.Build.0 = Release|Any CPU + {C1A2B3D4-0007-0007-0007-000000000007}.Debug|x86.ActiveCfg = Debug|Any CPU + {C1A2B3D4-0007-0007-0007-000000000007}.Debug|x86.Build.0 = Debug|Any CPU + {C1A2B3D4-0007-0007-0007-000000000007}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C1A2B3D4-0007-0007-0007-000000000007}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C1A2B3D4-0007-0007-0007-000000000007}.Debug|x64.ActiveCfg = Debug|Any CPU + {C1A2B3D4-0007-0007-0007-000000000007}.Debug|x64.Build.0 = Debug|Any CPU + {C1A2B3D4-0007-0007-0007-000000000007}.Release|x86.ActiveCfg = Release|Any CPU + {C1A2B3D4-0007-0007-0007-000000000007}.Release|x86.Build.0 = Release|Any CPU + {C1A2B3D4-0007-0007-0007-000000000007}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C1A2B3D4-0007-0007-0007-000000000007}.Release|Any CPU.Build.0 = Release|Any CPU + {C1A2B3D4-0007-0007-0007-000000000007}.Release|x64.ActiveCfg = Release|Any CPU + {C1A2B3D4-0007-0007-0007-000000000007}.Release|x64.Build.0 = Release|Any CPU + {C1A2B3D4-0008-0008-0008-000000000008}.Debug|x86.ActiveCfg = Debug|Any CPU + {C1A2B3D4-0008-0008-0008-000000000008}.Debug|x86.Build.0 = Debug|Any CPU + {C1A2B3D4-0008-0008-0008-000000000008}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C1A2B3D4-0008-0008-0008-000000000008}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C1A2B3D4-0008-0008-0008-000000000008}.Debug|x64.ActiveCfg = Debug|Any CPU + {C1A2B3D4-0008-0008-0008-000000000008}.Debug|x64.Build.0 = Debug|Any CPU + {C1A2B3D4-0008-0008-0008-000000000008}.Release|x86.ActiveCfg = Release|Any CPU + {C1A2B3D4-0008-0008-0008-000000000008}.Release|x86.Build.0 = Release|Any CPU + {C1A2B3D4-0008-0008-0008-000000000008}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C1A2B3D4-0008-0008-0008-000000000008}.Release|Any CPU.Build.0 = Release|Any CPU + {C1A2B3D4-0008-0008-0008-000000000008}.Release|x64.ActiveCfg = Release|Any CPU + {C1A2B3D4-0008-0008-0008-000000000008}.Release|x64.Build.0 = Release|Any CPU + {C1A2B3D4-0009-0009-0009-000000000009}.Debug|x86.ActiveCfg = Debug|Any CPU + {C1A2B3D4-0009-0009-0009-000000000009}.Debug|x86.Build.0 = Debug|Any CPU + {C1A2B3D4-0009-0009-0009-000000000009}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C1A2B3D4-0009-0009-0009-000000000009}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C1A2B3D4-0009-0009-0009-000000000009}.Debug|x64.ActiveCfg = Debug|Any CPU + {C1A2B3D4-0009-0009-0009-000000000009}.Debug|x64.Build.0 = Debug|Any CPU + {C1A2B3D4-0009-0009-0009-000000000009}.Release|x86.ActiveCfg = Release|Any CPU + {C1A2B3D4-0009-0009-0009-000000000009}.Release|x86.Build.0 = Release|Any CPU + {C1A2B3D4-0009-0009-0009-000000000009}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C1A2B3D4-0009-0009-0009-000000000009}.Release|Any CPU.Build.0 = Release|Any CPU + {C1A2B3D4-0009-0009-0009-000000000009}.Release|x64.ActiveCfg = Release|Any CPU + {C1A2B3D4-0009-0009-0009-000000000009}.Release|x64.Build.0 = Release|Any CPU + {A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x86.ActiveCfg = Debug|Any CPU + {A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x86.Build.0 = Debug|Any CPU + {A1B2C3D4-000A-000A-000A-00000000000A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A1B2C3D4-000A-000A-000A-00000000000A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x64.ActiveCfg = Debug|Any CPU + {A1B2C3D4-000A-000A-000A-00000000000A}.Debug|x64.Build.0 = Debug|Any CPU + {A1B2C3D4-000A-000A-000A-00000000000A}.Release|x86.ActiveCfg = Release|Any CPU + {A1B2C3D4-000A-000A-000A-00000000000A}.Release|x86.Build.0 = Release|Any CPU + {A1B2C3D4-000A-000A-000A-00000000000A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A1B2C3D4-000A-000A-000A-00000000000A}.Release|Any CPU.Build.0 = Release|Any CPU + {A1B2C3D4-000A-000A-000A-00000000000A}.Release|x64.ActiveCfg = Release|Any CPU + {A1B2C3D4-000A-000A-000A-00000000000A}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -107,5 +165,8 @@ Global {2B283E05-12BB-45F9-B8E5-8F53C1FAB737} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {BB0C5CB5-6C75-4C17-9348-5CA0C481B65C} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} {A72E31D3-5D91-4C39-A30C-A96A492BBE82} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} + {C1A2B3D4-0007-0007-0007-000000000007} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} + {C1A2B3D4-0008-0008-0008-000000000008} = {52D7C9F1-3A4E-4B11-9C2D-7E1A8C3F4D89} + {C1A2B3D4-0009-0009-0009-000000000009} = {52D7C9F1-3A4E-4B11-9C2D-7E1A8C3F4D89} EndGlobalSection EndGlobal diff --git a/docs/STATUS_AGENT.md b/docs/STATUS_AGENT.md new file mode 100644 index 0000000..8e6adfe --- /dev/null +++ b/docs/STATUS_AGENT.md @@ -0,0 +1,225 @@ +# RynthCore Status Agent + +Surface live RynthCore client status (running / in-world / actively botting, +plus fps, plugin-pump rate, memory, vitals) to an external app — e.g. a phone +dashboard — so you can confirm a multi-box session is healthy without remoting +into the PC. + +It is built in two deliberately separated halves: + +1. **Engine status export** — opt-in, **default OFF**. When enabled, the engine + writes a small **local** JSON file per client. It never opens a network + connection. +2. **`RynthCore.StatusAgent.exe`** — a separate, optional program that runs **on + your own PC**, reads those local files, and forwards a rolled-up payload to + **an endpoint you configure**. It is not injected into the game, not in the + installer, and sends nothing until you give it a URL. + +--- + +## Privacy / "this isn't spyware" + +This feature is designed so that distributing RynthCore to other people changes +nothing for them unless they explicitly turn it on, and even then nothing leaves +their machine: + +- **Default off.** With `EnableStatusExport` absent or `false`, the engine writes + no status file and behaves exactly as before. +- **No telemetry from the game.** `acclient.exe` / the engine never opens a + socket for this feature. The most it ever does is write a local file under + `C:\Games\RynthCore\Logs\status\`, right next to the logs it already writes. +- **The network half runs on the operator's PC, by the operator.** Only + `RynthCore.StatusAgent.exe` makes outbound requests, only to the URL **you** + put in **your** config, and only while you choose to run it. With no URL set it + runs in local print-only mode and sends nothing. +- **Nothing is bundled.** The installer does not ship or auto-start the agent. + +If you hand RynthCore to someone else, they get the default-off engine and no +agent — there is no path by which your build reaches into their PC. + +--- + +## Turning it on (operator setup) + +### 1. Enable the engine status export + +Add to **your** `%APPDATA%\RynthCore\engine.json`: + +```json +{ + "EnableStatusExport": true +} +``` + +(Or set the env var `RYNTHCORE_STATUS_EXPORT=1` before launching AC for a +one-session test without editing the file.) Picked up on next client launch. + +The engine then writes, once per second, per running client: + +``` +C:\Games\RynthCore\Logs\status\RynthCore..status.json +``` + +### 2. Build and run the agent + +```powershell +dotnet publish .\src\RynthCore.StatusAgent\RynthCore.StatusAgent.csproj -c Release +.\src\RynthCore.StatusAgent\bin\Release\net10.0-windows\RynthCore.StatusAgent.exe +``` + +On first run it writes a config template to +`%APPDATA%\RynthCore\statusagent.json` and runs in **local print-only mode** +(reads + prints status, sends nothing) until you set an endpoint. + +Useful flags: `--once` (one cycle then exit), `--dry-run` (read + print, never +POST), `--verbose` (print the full payload), `--interval N`, `--config PATH`, +`--help`. + +To keep it running unattended, launch it at login (Task Scheduler "At log on", +or a Startup-folder shortcut). + +### 3. Point it at your backend + +Edit `%APPDATA%\RynthCore\statusagent.json`: + +```json +{ + "Endpoint": "https://your-backend.example.com/api/rynthcore/status", + "AuthHeaderName": "Authorization", + "AuthHeaderValue": "Bearer YOUR_TOKEN", + "IntervalSeconds": 5, + "TimeoutSeconds": 15, + "StatusDirectory": "C:\\Games\\RynthCore\\Logs\\status", + "LogDirectory": "C:\\Games\\RynthCore\\Logs", + "UseHeartbeatLogFallback": true, + "StaleAfterSeconds": 12, + "DropDeadAfterSeconds": 300, + "Host": "", + "ServeHttp": false, + "ServePrefix": "http://127.0.0.1:8740/", + "ServeToken": "", + "WriteAggregateFile": true +} +``` + +- **Endpoint** — required to **push**. Empty = no POST. +- **AuthHeaderName/Value** — optional; sent as a request header if both set. +- **UseHeartbeatLogFallback** — when a running client has no status file (e.g. + `EnableStatusExport` is off), derive basic status from its heartbeat log line. + You get run/idle/loading/hung detection but no macro/profile/vitals. +- **Host** — label for this machine; empty uses the machine name. +- **ServeHttp / ServePrefix / ServeToken** — opt-in **pull** endpoint (see below). +- **WriteAggregateFile** — also drop the latest rollup to + `Logs\status\aggregate.json` (for file-sync delivery or debugging). + +## Three ways to get it to the app — pick one (or several) + +The agent produces one payload per cycle and can deliver it three ways at once; +they're all opt-in, so use whichever fits the app you end up building: + +1. **Push (POST).** Set `Endpoint` (+ optional auth). The agent POSTs the JSON to + your server, which the app reads. Best when you already run a backend. +2. **Pull (serve).** Set `ServeHttp: true`. The agent serves the latest JSON at + `GET status` — **no backend needed**, the app just fetches a URL: + - `http://127.0.0.1:8740/` (default) — this PC only. + - `http://+:8740/` — reachable on the LAN, and from anywhere if the PC is on + a private mesh like **Tailscale** (phone hits `http://:8740/status`). + A `+` bind needs a one-time `netsh http add urlacl url=http://+:8740/ user=Everyone` + (or run the agent elevated). + - `ServeToken` is required: with it empty the server stays off, on any bind. + Every route but `/healthz` then needs `Authorization: Bearer ` (or `?token=`). + Use the same token as your DrakBot remote and one DrakRemote entry shows both. + - `GET /healthz` returns `ok` for uptime checks. +3. **File sync.** Leave `WriteAggregateFile: true` and point iCloud/Dropbox/etc. + at `Logs\status\aggregate.json`; the app reads the synced copy. + +For a phone dashboard with no server, **pull + Tailscale** is the lowest-friction +path: turn on `ServeHttp`, bind to `http://+:8740/`, and fetch +`http://:8740/status` from the app. + +--- + +## Backend payload contract + +The agent sends an HTTP **POST** to `Endpoint` with +`Content-Type: application/json` and (if configured) your auth header. Body: + +```jsonc +{ + "schema": "rynthcore.status-agent/1", + "host": "DESKTOP-XYZ", + "agentVersion": "1.0.0", + "generatedAtUtc": "2026-06-20T12:34:56.789+00:00", + "clientCount": 2, + "clients": [ + { + "pid": 1234, + "host": "DESKTOP-XYZ", + "account": "myacct", + "character": "Gandalf", + "server": "Coldeve", + "state": "botting", // see state table below + "healthy": true, // false for wedged/hung/dead + "ageSec": 0.4, // seconds since this snapshot refreshed + "source": "status-file", // or "heartbeat-log" (basic fallback) + "uptimeSec": 3600, + "fps": 60, // 0 while in-world = render thread dead + "pluginTicksPerSec": 30, // 0 while macro on = bot pump wedged + "workingSetMB": 540, + "inWorld": true, + "macroRunning": true, + "currentState": "Killing", + "botAction": "Cast War", + "profile": "Default", + "navProfile": "DiforsaPatrol", + "lootProfile": "Salvage", + "metaProfile": "", + "target": "Drudge Skulker", + "player": { "hp": 100, "maxHp": 120, "st": 80, "maxSt": 110, "mn": 60, "maxMn": 90 }, + "queueDropped": 0, + "reconciles": 12, + "forceClears": 0 + } + ] +} +``` + +`bot`-derived fields (`macroRunning`, `profile`, `target`, `player`, …) are only +populated for `source: "status-file"` clients. For `heartbeat-log` clients they +are empty/false. + +### Client `state` values + +| state | meaning | healthy | +|-----------|------------------------------------------------------|---------| +| `botting` | in-world, macro running, plugin pump alive | ✅ | +| `idle` | in-world, macro stopped | ✅ | +| `running` | in-world, rendering (macro state unknown — log path) | ✅ | +| `loading` | process up, at login / char-select (not in-world) | ✅ | +| `wedged` | macro on but plugin pump at 0/s — bot stalled | ❌ | +| `hung` | in-world but fps 0, or snapshot frozen — client stuck| ❌ | +| `dead` | process gone (crash/exit) | ❌ | + +A simple phone view: green if every client is `healthy`, red if any is +`wedged`/`hung`/`dead`, and show each character's `state` + `character` name. + +--- + +## Removing the feature entirely + +Everything is tagged `[status-export]` in the engine — `grep -r "[status-export]" +src` finds every touch point. + +1. Delete `src/RynthCore.StatusAgent/` and remove its `Project(...)` line and the + `{A1B2C3D4-000A-...}` config block from `RynthCore.sln`. +2. Delete `src/RynthCore.Engine/Compatibility/StatusSnapshotWriter.cs`. +3. Remove the `StatusSnapshotWriter.Write(...)` call in + `Compatibility/HeartbeatLogger.cs`. +4. Remove the `[status-export]` region in `LogPaths.cs` (status dir helpers + the + status-prune block in `PruneOldLogs`). +5. Remove `EnableStatusExport` from `Plugins/EngineSettings.cs` (field, property, + load, save). +6. Remove the `LastAccountName/LastCharacterName/LastServerName` members and their + assignment in `Compatibility/SessionStateRegistry.cs`. + +The engine builds and behaves exactly as before. diff --git a/installer/Build-Installer.ps1 b/installer/Build-Installer.ps1 index 27399cf..12fe70a 100644 --- a/installer/Build-Installer.ps1 +++ b/installer/Build-Installer.ps1 @@ -6,9 +6,12 @@ .DESCRIPTION 1. Publishes the Avalonia launcher (self-contained, x86) 2. Publishes RynthCore.Engine (NativeAOT, x86 -- ~2 min) - 3. Publishes RynthCore.Plugin.RynthAi (NativeAOT, x86) - 4. Stages all output under installer\staging\app\ - 5. Invokes ISCC.exe to produce installer\Output\RynthCore-Setup.exe + 3. Publishes RynthCore.Loader (NativeAOT, x86) -- the DLL the launcher injects + 4. Publishes RynthCore.Plugin.RynthAi (NativeAOT, x86) + 5. Publishes the Loot Editor + 6. Stages all output under installer\staging\app\, plus the hand-built + RynthCore.SehTrampoline.dll, and checks every required runtime file is there + 7. Invokes ISCC.exe to produce installer\Output\RynthCore-Setup.exe .PARAMETER Configuration Build configuration. Default: Release @@ -22,7 +25,7 @@ #> param( [string]$Configuration = "Release", - [string]$IsccPath = "C:\Program Files (x86)\Inno Setup 6\ISCC.exe", + [string]$IsccPath = "", # Explicit path to the RynthSuite repo root. When omitted, defaults to the # sibling directory of RynthCore (i.e. ..\RynthSuite relative to this repo). [string]$RynthSuiteRoot = "", @@ -35,6 +38,24 @@ param( $ErrorActionPreference = "Stop" Set-StrictMode -Off +# Release number for release.txt, which the launcher's updater reads +# (RynthUpdater.InstalledCoreRelease). -Version yyyy.m.d.n → yyyymmddnn; a dev build +# without -Version records 0 ("unknown", so any published release reads as newer). +# Checked here, before the builds, so a typo fails in a second rather than at the end. +$release = 0 +if ($Version) { + $p = $Version.Split('.') + if ($p.Count -ne 4 -or ($p | Where-Object { $_ -notmatch '^\d+$' }) -or [int]$p[1] -gt 12 -or [int]$p[2] -gt 31 -or [int]$p[3] -gt 99) { + throw "-Version must be yyyy.m.d.n (e.g. 2026.9.26.3), got '$Version'" + } + $release = [int]$p[0] * 1000000 + [int]$p[1] * 10000 + [int]$p[2] * 100 + [int]$p[3] +} + +# Stamp every build with the release, so the launcher, the engine log and the in-game +# Status panel show it (RynthCore.App.BuildVersion); the SDK appends the git commit. +$VersionArgs = @() +if ($Version) { $VersionArgs = @("-p:Version=$Version") } + $ScriptDir = $PSScriptRoot $RepoRoot = Split-Path $ScriptDir -Parent # e.g. C:\Projects\RynthCore $ProjectsRoot = Split-Path $RepoRoot -Parent # e.g. C:\Projects @@ -44,18 +65,22 @@ if (-not $RynthSuiteRoot) { $RynthSuiteRoot = "$ProjectsRoot\RynthSuite" } -$LauncherProject = "$RepoRoot\src\RynthCore.App.Avalonia\RynthCore.App.Avalonia.csproj" -$EngineProject = "$RepoRoot\src\RynthCore.Engine\RynthCore.Engine.csproj" -$PluginProject = "$RynthSuiteRoot\Plugins\RynthCore.Plugin.RynthAi\RynthCore.Plugin.RynthAi.csproj" +$LauncherProject = "$RepoRoot\src\RynthCore.App.Avalonia\RynthCore.App.Avalonia.csproj" +$EngineProject = "$RepoRoot\src\RynthCore.Engine\RynthCore.Engine.csproj" +$LoaderProject = "$RepoRoot\src\RynthCore.Loader\RynthCore.Loader.csproj" +$PluginProject = "$RynthSuiteRoot\Plugins\RynthCore.Plugin.RynthAi\RynthCore.Plugin.RynthAi.csproj" +$LootEditorProject = "$RynthSuiteRoot\Tools\RynthCore.LootEditor\RynthCore.LootEditor.csproj" -$LauncherPublish = "$RepoRoot\src\RynthCore.App.Avalonia\bin\$Configuration\net10.0-windows7.0\win-x86\publish" -$EnginePublish = "$RepoRoot\src\RynthCore.Engine\bin\$Configuration\net10.0-windows\win-x86\publish" -$PluginPublish = "$RynthSuiteRoot\Plugins\RynthCore.Plugin.RynthAi\bin\$Configuration\net10.0-windows\win-x86\publish" +$LauncherPublish = "$RepoRoot\src\RynthCore.App.Avalonia\bin\$Configuration\net10.0-windows7.0\win-x86\publish" +$EnginePublish = "$RepoRoot\src\RynthCore.Engine\bin\$Configuration\net10.0-windows\win-x86\publish" +$LoaderPublish = "$RepoRoot\src\RynthCore.Loader\bin\$Configuration\net10.0-windows\win-x86\publish" +$PluginPublish = "$RynthSuiteRoot\Plugins\RynthCore.Plugin.RynthAi\bin\$Configuration\net10.0-windows\win-x86\publish" +$LootEditorPublish = "$RynthSuiteRoot\Tools\RynthCore.LootEditor\bin\$Configuration\net10.0\win-x86\publish" $StagingDir = "$ScriptDir\staging\app" # ── Validate projects ─────────────────────────────────────────────────────── -foreach ($p in @($LauncherProject, $EngineProject, $PluginProject)) { +foreach ($p in @($LauncherProject, $EngineProject, $LoaderProject, $PluginProject, $LootEditorProject)) { if (-not (Test-Path $p)) { throw "Project not found: $p`nUpdate paths in Build-Installer.ps1 if your repo layout differs." } @@ -64,21 +89,33 @@ foreach ($p in @($LauncherProject, $EngineProject, $PluginProject)) { if (-not $SkipBuild) { # ── 1. Launcher (self-contained Avalonia WinExe) ───────────────────────── Write-Host "" - Write-Host "[1/3] Publishing Launcher (self-contained, x86)..." -ForegroundColor Cyan - dotnet publish $LauncherProject -c $Configuration -r win-x86 --self-contained true + Write-Host "[1/5] Publishing Launcher (self-contained, x86)..." -ForegroundColor Cyan + dotnet publish $LauncherProject -c $Configuration -r win-x86 --self-contained true @VersionArgs if ($LASTEXITCODE -ne 0) { throw "Launcher publish failed (exit $LASTEXITCODE)" } # ── 2. Engine (NativeAOT — the slow one) ────────────────────────────────── Write-Host "" - Write-Host "[2/3] Publishing Engine (NativeAOT, ~2 min)..." -ForegroundColor Cyan - dotnet publish $EngineProject -c $Configuration + Write-Host "[2/5] Publishing Engine (NativeAOT, ~2 min)..." -ForegroundColor Cyan + dotnet publish $EngineProject -c $Configuration @VersionArgs if ($LASTEXITCODE -ne 0) { throw "Engine publish failed (exit $LASTEXITCODE)" } - # ── 3. Plugin (NativeAOT) ───────────────────────────────────────────────── + # ── 3. Loader (NativeAOT, small) ────────────────────────────────────────── Write-Host "" - Write-Host "[3/3] Publishing Plugin (NativeAOT)..." -ForegroundColor Cyan - dotnet publish $PluginProject -c $Configuration + Write-Host "[3/5] Publishing Loader (NativeAOT)..." -ForegroundColor Cyan + dotnet publish $LoaderProject -c $Configuration @VersionArgs + if ($LASTEXITCODE -ne 0) { throw "Loader publish failed (exit $LASTEXITCODE)" } + + # ── 4. Plugin (NativeAOT) ───────────────────────────────────────────────── + Write-Host "" + Write-Host "[4/5] Publishing Plugin (NativeAOT)..." -ForegroundColor Cyan + dotnet publish $PluginProject -c $Configuration @VersionArgs if ($LASTEXITCODE -ne 0) { throw "Plugin publish failed (exit $LASTEXITCODE)" } + + # ── 5. Loot Editor (self-contained Avalonia tool) ───────────────────────── + Write-Host "" + Write-Host "[5/5] Publishing Loot Editor (self-contained, x86)..." -ForegroundColor Cyan + dotnet publish $LootEditorProject -c $Configuration -r win-x86 --self-contained true @VersionArgs + if ($LASTEXITCODE -ne 0) { throw "Loot Editor publish failed (exit $LASTEXITCODE)" } } # ── Stage ──────────────────────────────────────────────────────────────────── @@ -89,7 +126,15 @@ if (Test-Path "$ScriptDir\staging") { Remove-Item "$ScriptDir\staging" -Recurse -Force } New-Item -ItemType Directory -Path "$StagingDir\Runtime\Native" -Force | Out-Null -New-Item -ItemType Directory -Path "$StagingDir\Runtime\Plugins" -Force | Out-Null +New-Item -ItemType Directory -Path "$StagingDir\Tools\LootEditor" -Force | Out-Null +# Plugin DLLs are staged into a separate top-level folder (not under +# Runtime\) because the engine no longer auto-scans Runtime\Plugins\. +# The .iss file installs this folder to C:\Games\RynthSuite\\ +# (an absolute destination outside {app}) so the plugin lives next to its +# data dirs and the user adds the path via the launcher's Plugins tab. +$pluginStagingDir = "$ScriptDir\staging\plugins" +if (Test-Path $pluginStagingDir) { Remove-Item $pluginStagingDir -Recurse -Force } +New-Item -ItemType Directory -Path "$pluginStagingDir\RynthAi" -Force | Out-Null # Launcher root files (rename .exe → RynthCore.exe; drop .pdb) foreach ($file in (Get-ChildItem "$LauncherPublish" -File)) { @@ -104,6 +149,26 @@ foreach ($file in (Get-ChildItem "$EnginePublish" -File)) { Copy-Item $file.FullName "$StagingDir\Runtime\$($file.Name)" -Force } +# Loader — the DLL the launcher injects (EngineInjectionService.EngineDllName); it +# maps RynthCore.Engine.dll and provides hot-reload. Without it a fresh install's +# launcher can't auto-find an engine to inject. +$loaderDll = "$LoaderPublish\RynthCore.Loader.dll" +if (-not (Test-Path $loaderDll)) { throw "Loader DLL not found at: $loaderDll" } +Copy-Item $loaderDll "$StagingDir\Runtime\" -Force + +# SEH trampoline — hand-built native DLL (native\SehTrampoline\Build-SehTrampoline.ps1), +# NOT part of the engine publish output. Without it SehTrampoline.IsAvailable stays +# false and CombatActionHooks.CastSpell fails closed on every targeted cast, which +# includes self-buffs (the plugin passes the player id): the bot says "Casting: X" +# and nothing happens. Same missing/stale checks as scripts\Deploy-RynthCore.ps1. +$sehDll = "$RepoRoot\native\SehTrampoline\bin\RynthCore.SehTrampoline.dll" +$sehSrc = "$RepoRoot\native\SehTrampoline\SehTrampoline.c" +if (-not (Test-Path $sehDll)) { throw "SEH trampoline not found at: $sehDll`nBuild it with native\SehTrampoline\Build-SehTrampoline.ps1" } +if ((Test-Path $sehSrc) -and (Get-Item $sehSrc).LastWriteTime -gt (Get-Item $sehDll).LastWriteTime) { + throw "RynthCore.SehTrampoline.dll is STALE (SehTrampoline.c is newer). Rebuild with native\SehTrampoline\Build-SehTrampoline.ps1" +} +Copy-Item $sehDll "$StagingDir\Runtime\" -Force + # Engine Native subfolder if (Test-Path "$EnginePublish\Native") { foreach ($file in (Get-ChildItem "$EnginePublish\Native" -File)) { @@ -112,10 +177,41 @@ if (Test-Path "$EnginePublish\Native") { } } -# Plugin DLL only (cimgui.dll excluded — already in Runtime from Engine) +# Plugin DLL only — staged separately so the .iss file can install it to an +# absolute path outside {app}. The engine no longer auto-scans Runtime\Plugins\; +# the user explicitly adds the plugin path via the launcher's Plugins tab. $pluginDll = "$PluginPublish\RynthCore.Plugin.RynthAi.dll" if (-not (Test-Path $pluginDll)) { throw "Plugin DLL not found at: $pluginDll" } -Copy-Item $pluginDll "$StagingDir\Runtime\Plugins\" -Force +Copy-Item $pluginDll "$pluginStagingDir\RynthAi\" -Force + +# Loot Editor (self-contained — copy everything from publish, drop pdbs) +if (-not (Test-Path $LootEditorPublish)) { throw "Loot Editor publish not found at: $LootEditorPublish" } +foreach ($file in (Get-ChildItem "$LootEditorPublish" -File)) { + if ($file.Extension -eq '.pdb') { continue } + Copy-Item $file.FullName "$StagingDir\Tools\LootEditor\$($file.Name)" -Force +} +foreach ($dir in (Get-ChildItem "$LootEditorPublish" -Directory)) { + Copy-Item $dir.FullName "$StagingDir\Tools\LootEditor\" -Recurse -Force + # Drop pdbs from copied subdirs + Get-ChildItem "$StagingDir\Tools\LootEditor\$($dir.Name)" -Recurse -File -Filter '*.pdb' | Remove-Item -Force +} + +# release.txt — which core release this install is ($release, from -Version at the top). +Set-Content -Path "$StagingDir\release.txt" -Value @($release, $Version) -Encoding ASCII + +# Everything a working install needs. The 2026-09-25 public installer went out +# without the Loader and the SEH trampoline because nothing checked. +$required = @( + "$StagingDir\RynthCore.exe", + "$StagingDir\Runtime\RynthCore.Loader.dll", + "$StagingDir\Runtime\RynthCore.Engine.dll", + "$StagingDir\Runtime\RynthCore.SehTrampoline.dll", + "$StagingDir\Runtime\minhook.x86.dll", + "$StagingDir\Runtime\cimgui.dll", + "$pluginStagingDir\RynthAi\RynthCore.Plugin.RynthAi.dll" +) +$missing = @($required | Where-Object { -not (Test-Path $_) }) +if ($missing.Count -gt 0) { throw "Staging is missing required files:`n $($missing -join "`n ")" } # Report staged sizes $engineDll = "$StagingDir\Runtime\RynthCore.Engine.dll" @@ -129,13 +225,18 @@ Write-Host " Total staged: ${totalMb} MB" Write-Host "Staging complete: $StagingDir" -ForegroundColor Green # ── Inno Setup ─────────────────────────────────────────────────────────────── -if (-not (Test-Path $IsccPath)) { +# Auto-detect ISCC if not specified: try standard install location then user-local. +if (-not $IsccPath) { + $candidates = @( + "C:\Program Files (x86)\Inno Setup 6\ISCC.exe", + "$env:LOCALAPPDATA\Programs\Inno Setup 6\ISCC.exe" + ) + foreach ($c in $candidates) { if (Test-Path $c) { $IsccPath = $c; break } } +} +if (-not $IsccPath -or -not (Test-Path $IsccPath)) { Write-Host "" - Write-Warning "Inno Setup compiler not found at:" - Write-Warning " $IsccPath" - Write-Warning "Install Inno Setup 6 from: https://jrsoftware.org/isdl.php" - Write-Warning "Then re-run this script, or invoke ISCC manually:" - Write-Warning " `"$IsccPath`" `"$ScriptDir\RynthCore.iss`"" + Write-Warning "Inno Setup compiler not found. Install Inno Setup 6 from: https://jrsoftware.org/isdl.php" + Write-Warning "Or pass -IsccPath to this script explicitly." exit 0 } diff --git a/installer/New-UpdateSigningKey.ps1 b/installer/New-UpdateSigningKey.ps1 new file mode 100644 index 0000000..830125b --- /dev/null +++ b/installer/New-UpdateSigningKey.ps1 @@ -0,0 +1,103 @@ +#Requires -Version 7 +<# +.SYNOPSIS + Creates the RynthCore update-signing keys. Run it once, yourself. + +.DESCRIPTION + Launchers install an update only if its feed is signed by a key they trust. This makes + two ECDSA P-256 keys: + + primary Signs every release. Saved to \primary.key, encrypted with Windows + DPAPI for your user account: Publish-Update.ps1 signs without a prompt, and the + file is useless on any other account or PC. + backup Replaces the primary if it is ever lost (new PC, reinstall). Saved to + \backup.key.p8, encrypted with a password you choose here. Move it + OFFLINE (a USB stick in a drawer) and delete the copy on this PC. + + Both public halves are written into src\RynthCore.App.Avalonia\UpdateTrust.cs, so + launchers built afterwards trust either key. Commit that file, then build and release. + + The private keys never leave this PC. Never copy them to the server: the point of signing + is that a compromised server still can't push code to players. + +.PARAMETER Force + Replace existing keys. Launchers that only trust the old keys will refuse every release + signed with the new ones, so this strands them until they reinstall by hand. +#> +param( + [string]$KeyDir = (Join-Path $env:USERPROFILE ".rynthcore-update-signing"), + [string]$TrustFile = (Join-Path $PSScriptRoot "..\src\RynthCore.App.Avalonia\UpdateTrust.cs"), + # For scripted tests only; normally you are prompted. + [SecureString]$BackupPassword, + [switch]$Force +) + +$ErrorActionPreference = "Stop" +Add-Type -AssemblyName System.Security +$crypto = [System.Security.Cryptography.ProtectedData].Assembly # DPAPI present (fails loudly if not) + +$primaryPath = Join-Path $KeyDir "primary.key" +$backupPath = Join-Path $KeyDir "backup.key.p8" +if ((Test-Path $primaryPath) -and -not $Force) { + throw "Keys already exist in $KeyDir. Replacing them strands launchers that trust only the old ones; pass -Force only if you mean it." +} +if (-not (Test-Path $TrustFile)) { throw "UpdateTrust.cs not found at $TrustFile" } + +if (-not $BackupPassword) { + $BackupPassword = Read-Host "Password for the BACKUP key (needed only if the primary is ever lost)" -AsSecureString + $again = Read-Host "Repeat it" -AsSecureString + if ((ConvertFrom-SecureString $BackupPassword -AsPlainText) -ne (ConvertFrom-SecureString $again -AsPlainText)) { + throw "The passwords don't match." + } +} +$plain = ConvertFrom-SecureString $BackupPassword -AsPlainText +if ($plain.Length -lt 12) { throw "Use at least 12 characters for the backup key password." } + +New-Item -ItemType Directory -Force $KeyDir | Out-Null +$curve = [System.Security.Cryptography.ECCurve+NamedCurves]::nistP256 +$primary = [System.Security.Cryptography.ECDsa]::Create($curve) +$backup = [System.Security.Cryptography.ECDsa]::Create($curve) + +# Primary: DPAPI (CurrentUser), with fixed entropy so a stray DPAPI blob can't pose as it. +$entropy = [Text.Encoding]::UTF8.GetBytes("RynthCore update signing v1") +$pkcs8 = $primary.ExportPkcs8PrivateKey() +try { + $blob = [System.Security.Cryptography.ProtectedData]::Protect($pkcs8, $entropy, 'CurrentUser') + [IO.File]::WriteAllBytes($primaryPath, $blob) +} finally { [Array]::Clear($pkcs8) } + +# Backup: password-encrypted PKCS#8 (AES-256, 600k PBKDF2 rounds). +$pbe = [System.Security.Cryptography.PbeParameters]::new( + [System.Security.Cryptography.PbeEncryptionAlgorithm]::Aes256Cbc, + [System.Security.Cryptography.HashAlgorithmName]::SHA256, 600000) +[IO.File]::WriteAllBytes($backupPath, $backup.ExportEncryptedPkcs8PrivateKey($plain, $pbe)) +$plain = $null + +function KeyId([byte[]]$spki) { + $h = [System.Security.Cryptography.SHA256]::HashData($spki) + return ([Convert]::ToHexString($h, 0, 8)).ToLowerInvariant() +} +$keys = foreach ($k in @(@{ Name = "primary"; Key = $primary }, @{ Name = "backup"; Key = $backup })) { + $spki = $k.Key.ExportSubjectPublicKeyInfo() + [pscustomobject]@{ Name = $k.Name; Id = KeyId $spki; Base64 = [Convert]::ToBase64String($spki) } +} + +# Write the public keys between the markers in UpdateTrust.cs. +$src = Get-Content $TrustFile -Raw +$begin = "// BEGIN KEYS (New-UpdateSigningKey.ps1)" +$end = "// END KEYS" +$i = $src.IndexOf($begin); $j = $src.IndexOf($end) +if ($i -lt 0 -or $j -lt $i) { throw "Key markers not found in $TrustFile" } +$indent = " " +$lines = $keys | ForEach-Object { "$indent`"$($_.Base64)`", // $($_.Name) $($_.Id)" } +$new = $src.Substring(0, $i + $begin.Length) + "`r`n" + ($lines -join "`r`n") + "`r`n$indent" + $src.Substring($j) +Set-Content -Path $TrustFile -Value $new -NoNewline -Encoding utf8 + +Write-Host "" +Write-Host "Keys created in $KeyDir" -ForegroundColor Green +$keys | ForEach-Object { Write-Host (" {0,-8} {1}" -f $_.Name, $_.Id) } +Write-Host "" +Write-Host "Public keys written to $TrustFile" -ForegroundColor Green +Write-Host "Next:" +Write-Host " 1. Move $backupPath OFFLINE (USB stick), then delete it here. Keep its password somewhere safe." +Write-Host " 2. Commit UpdateTrust.cs, then publish with installer\Publish-Update.ps1 -Version ." diff --git a/installer/Publish-Update.ps1 b/installer/Publish-Update.ps1 new file mode 100644 index 0000000..d2cb1db --- /dev/null +++ b/installer/Publish-Update.ps1 @@ -0,0 +1,256 @@ +#Requires -Version 7 +<# +.SYNOPSIS + Builds, signs and publishes a RynthCore + RynthSuite release to the launchers' update feed. + +.DESCRIPTION + One command per release: + 1. Refuses if the signing key isn't set up or isn't trusted by the launcher being shipped, + if either repo has uncommitted changes, or if -Version isn't newer than the live feed. + 2. Builds the installer (Build-Installer.ps1 -Version) and the RynthSuite plugins into + installer\Releases\\ — never into the live C:\Games folders. + 3. Writes the manifest (sizes + SHA-256 of every file), signs it with the DPAPI key + (Sign-Update.ps1, no prompt) and checks the signature the way the launcher will. + 4. Uploads the release files, checks their hashes on the server, replaces the website's + RynthCore-Setup.exe and RynthSuite-Plugins.zip (old ones kept in ~/backups/rynth), + and swaps in update.json last, atomically. + 5. Fetches the live feed back and compares it byte for byte. + + Launchers pick it up at their next check (start-up, every 6 hours, or the button). Plugins + swap in place without touching running bots; the core installer waits until every + RynthCore client is closed. + +.EXAMPLE + .\Publish-Update.ps1 -Version 2026.9.28.1 -Changes "Arrow crafting covers every head type.", "The Tell button works on players too." +#> +param( + [Parameter(Mandatory)][string]$Version, + # Release notes for players, one line per change: they become this release's entry in + # downloads/rynth/releases.json, which the "What's new" list on aelrynth.com/rynth.html shows. + [string[]]$Changes = @(), + # Short text the launcher shows next to an available update; defaults to the changes. + [string]$Notes = "", + [switch]$DryRun, # build + sign + verify, upload nothing + [switch]$AllowDirty, # publish with uncommitted changes (don't) + [string]$SshHost = "aelrynth-vps", + [string]$RemoteDir = "/var/www/site/downloads/rynth", + [string]$BaseUrl = "https://aelrynth.com/downloads/rynth", + [string]$KeyDir = (Join-Path $env:USERPROFILE ".rynthcore-update-signing"), + [string]$RynthSuiteRoot = "", + [string]$TrustFile = "" # defaults to the launcher's UpdateTrust.cs; override for tests +) + +$ErrorActionPreference = "Stop" +$ScriptDir = $PSScriptRoot +$RepoRoot = Split-Path $ScriptDir -Parent +if (-not $RynthSuiteRoot) { $RynthSuiteRoot = Join-Path (Split-Path $RepoRoot -Parent) "RynthSuite" } +if (-not $TrustFile) { $TrustFile = Join-Path $RepoRoot "src\RynthCore.App.Avalonia\UpdateTrust.cs" } + +function Step($m) { Write-Host ""; Write-Host "== $m" -ForegroundColor Cyan } +function Sha256([string]$path) { (Get-FileHash $path -Algorithm SHA256).Hash.ToLowerInvariant() } + +# Same check as RynthUpdater.VerifyEnvelope: any trusted key's signature over the payload bytes. +function Test-Envelope([string]$path, [string[]]$keys) { + $envelope = Get-Content $path -Raw | ConvertFrom-Json + $payload = [Convert]::FromBase64String($envelope.payload) + foreach ($k in $keys) { + $spki = [Convert]::FromBase64String($k) + $id = ([Convert]::ToHexString([System.Security.Cryptography.SHA256]::HashData($spki), 0, 8)).ToLowerInvariant() + $ec = [System.Security.Cryptography.ECDsa]::Create() + $read = 0; $ec.ImportSubjectPublicKeyInfo($spki, [ref]$read) + foreach ($s in $envelope.signatures) { + if ($s.key -ne $id) { continue } + if ($ec.VerifyData($payload, [Convert]::FromBase64String($s.sig), + [System.Security.Cryptography.HashAlgorithmName]::SHA256, + [System.Security.Cryptography.DSASignatureFormat]::IeeeP1363FixedFieldConcatenation)) { return $true } + } + } + return $false +} + +# ── 1. Preconditions ───────────────────────────────────────────────────────── +Step "Checking preconditions" +$p = $Version.Split('.') +if ($p.Count -ne 4 -or ($p | Where-Object { $_ -notmatch '^\d+$' })) { throw "-Version must be yyyy.m.d.n, got '$Version'" } +$release = [int]$p[0] * 1000000 + [int]$p[1] * 10000 + [int]$p[2] * 100 + [int]$p[3] +if ($Changes.Count -eq 0 -and $Notes) { $Changes = @($Notes -split ';\s*' | Where-Object { $_ }) } +if ($Changes.Count -eq 0) { throw "Give -Changes: the release notes players see on aelrynth.com/rynth.html (one string per change)." } +if (-not $Notes) { $Notes = $Changes -join " " } + +$trusted = [regex]::Matches((Get-Content $TrustFile -Raw), '"([A-Za-z0-9+/=]{80,})"') | ForEach-Object { $_.Groups[1].Value } +if ($trusted.Count -lt 2) { + throw "UpdateTrust.cs has $($trusted.Count) key(s); it needs the primary and the backup. Run New-UpdateSigningKey.ps1 and commit UpdateTrust.cs." +} +$probe = New-TemporaryFile +try { + Set-Content $probe "probe $release" -NoNewline + & (Join-Path $ScriptDir "Sign-Update.ps1") -PayloadPath $probe -OutPath "$probe.sig" -KeyDir $KeyDir | Out-Null + if (-not (Test-Envelope "$probe.sig" $trusted)) { + throw "The signing key in $KeyDir is not one UpdateTrust.cs trusts: launchers would refuse this release." + } +} finally { Remove-Item $probe, "$probe.sig" -ErrorAction SilentlyContinue } +Write-Host " signing key is trusted by the launcher ($($trusted.Count) keys)" + +if (-not $AllowDirty) { + foreach ($repo in $RepoRoot, $RynthSuiteRoot) { + $dirty = git -C $repo status --porcelain --untracked-files=no + if ($dirty) { throw "$repo has uncommitted changes — release from committed code (or pass -AllowDirty):`n$dirty" } + } + Write-Host " RynthCore $(git -C $RepoRoot rev-parse --short HEAD), RynthSuite $(git -C $RynthSuiteRoot rev-parse --short HEAD)" +} + +try { + $live = Invoke-RestMethod "$BaseUrl/update.json" -TimeoutSec 20 + $liveRelease = ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($live.payload)) | ConvertFrom-Json).release + if ($release -le $liveRelease) { throw "Release $release is not newer than the live feed's $liveRelease — bump -Version." } + Write-Host " live feed is at $liveRelease; publishing $release" +} catch [Microsoft.PowerShell.Commands.HttpResponseException] { + Write-Host " no live feed yet — this is the first release" +} + +# ── 2. Build ───────────────────────────────────────────────────────────────── +$rel = Join-Path $ScriptDir "Releases\$release" +if (Test-Path $rel) { Remove-Item $rel -Recurse -Force } +New-Item -ItemType Directory -Force "$rel\plugins", "$rel\build" | Out-Null + +Step "Building the installer ($Version)" +& (Join-Path $ScriptDir "Build-Installer.ps1") -Version $Version -RynthSuiteRoot $RynthSuiteRoot +if (-not $?) { throw "Build-Installer.ps1 failed" } +Copy-Item (Join-Path $ScriptDir "Output\RynthCore-Setup.exe") "$rel\RynthCore-Setup.exe" +Copy-Item (Join-Path $ScriptDir "staging\plugins\RynthAi\RynthCore.Plugin.RynthAi.dll") "$rel\plugins\" + +$suitePlugins = "RynthChat", "RynthTracker", "RynthNav", "RynthVision" +foreach ($name in $suitePlugins) { + Step "Building $name" + $proj = Join-Path $RynthSuiteRoot "Plugins\RynthCore.Plugin.$name\RynthCore.Plugin.$name.csproj" + # PublishDir overrides the projects' own (RynthNav/RynthVision publish into the live C:\Games folders). + dotnet publish $proj -c Release "-p:Version=$Version" "-p:PublishDir=$rel\build\$name\" -v q -nologo + if ($LASTEXITCODE -ne 0) { throw "dotnet publish failed for $name" } + Copy-Item "$rel\build\$name\RynthCore.Plugin.$name.dll" "$rel\plugins\" +} + +Step "Packing RynthSuite-Plugins.zip" +$zipRoot = "$rel\build\zip" +foreach ($name in $suitePlugins) { + New-Item -ItemType Directory -Force "$zipRoot\RynthSuite\$name" | Out-Null + Copy-Item "$rel\plugins\RynthCore.Plugin.$name.dll" "$zipRoot\RynthSuite\$name\" +} +$navSrc = "C:\Games\RynthCore\NavData" +New-Item -ItemType Directory -Force "$zipRoot\RynthCore\NavData" | Out-Null +Get-ChildItem $navSrc -File | Where-Object { $_.Extension -eq ".tile" -or $_.Name -eq "portals.tsv" } | + Copy-Item -Destination "$zipRoot\RynthCore\NavData\" +@" +RynthSuite plugins for RynthCore (Asheron's Call, retail client) - $Version + +Extract this zip into C:\Games - it creates: + C:\Games\RynthSuite\RynthChat\ RynthChat plugin + C:\Games\RynthSuite\RynthNav\ RynthNav plugin + C:\Games\RynthSuite\RynthTracker\ RynthTracker plugin + C:\Games\RynthSuite\RynthVision\ RynthVision plugin + C:\Games\RynthCore\NavData\ RynthNav's baked navmesh tiles + +Then, in the RynthCore launcher's Plugins tab, add the full path of each +plugin DLL you want. Install RynthCore first (RynthCore-Setup.exe), which +also installs RynthAi and the Loot Editor. After that the launcher keeps +the plugins up to date by itself. + +MIT licensed. https://aelrynth.com/projects.html +"@ -replace "`n", "`r`n" | Set-Content "$zipRoot\README.txt" -NoNewline +Compress-Archive -Path "$zipRoot\*" -DestinationPath "$rel\RynthSuite-Plugins.zip" -CompressionLevel Optimal + +# ── 3. Manifest + signature ────────────────────────────────────────────────── +Step "Writing and signing the manifest" +$setup = Get-Item "$rel\RynthCore-Setup.exe" +$plugins = foreach ($dll in Get-ChildItem "$rel\plugins\*.dll" | Sort-Object Name) { + [ordered]@{ + name = $dll.BaseName -replace '^RynthCore\.Plugin\.', '' + file = $dll.Name + url = "$BaseUrl/releases/$release/plugins/$($dll.Name)" + size = $dll.Length + sha256 = Sha256 $dll.FullName + } +} +$manifest = [ordered]@{ + schema = 1 + release = $release + version = $Version + published = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ") + notes = $Notes + core = [ordered]@{ + release = $release + version = $Version + url = "$BaseUrl/releases/$release/RynthCore-Setup.exe" + size = $setup.Length + sha256 = Sha256 $setup.FullName + } + plugins = @($plugins) +} +Set-Content "$rel\update.payload.json" ($manifest | ConvertTo-Json -Depth 5) -Encoding utf8NoBOM +& (Join-Path $ScriptDir "Sign-Update.ps1") -PayloadPath "$rel\update.payload.json" -OutPath "$rel\update.json" -KeyDir $KeyDir +if (-not (Test-Envelope "$rel\update.json" $trusted)) { throw "Signed feed does not verify against UpdateTrust.cs" } +Write-Host " verified against the launcher's trusted keys" + +# Release notes: this release on top of the live list (a re-run replaces its own entry). +$history = @() +try { $history = @((Invoke-RestMethod "$BaseUrl/releases.json" -TimeoutSec 20).releases) } +catch [Microsoft.PowerShell.Commands.HttpResponseException] { Write-Host " no releases.json yet — starting one" } +$entry = [ordered]@{ version = $Version; date = (Get-Date -Format "yyyy-MM-dd"); changes = @($Changes) } +$releaseNotes = [ordered]@{ releases = @($entry) + @($history | Where-Object { $_ -and $_.version -ne $Version }) } +Set-Content "$rel\releases.json" ($releaseNotes | ConvertTo-Json -Depth 5) -Encoding utf8NoBOM +Write-Host " releases.json: $($releaseNotes.releases.Count) release(s), $($Changes.Count) change(s) in this one" + +if ($DryRun) { + Write-Host ""; Write-Host "Dry run: release built and signed in $rel; nothing uploaded." -ForegroundColor Yellow + return +} + +# ── 4. Upload ──────────────────────────────────────────────────────────────── +Step "Uploading release $release" +$remoteRel = "$RemoteDir/releases/$release" +ssh $SshHost "mkdir -p '$remoteRel/plugins'" +if ($LASTEXITCODE -ne 0) { throw "ssh mkdir failed" } +scp -q "$rel\RynthCore-Setup.exe" "${SshHost}:$remoteRel/RynthCore-Setup.exe" +if ($LASTEXITCODE -ne 0) { throw "scp of the installer failed" } +scp -q (Get-ChildItem "$rel\plugins\*.dll").FullName "${SshHost}:$remoteRel/plugins/" +if ($LASTEXITCODE -ne 0) { throw "scp of the plugins failed" } + +$remoteSums = ssh $SshHost "cd '$remoteRel' && sha256sum RynthCore-Setup.exe plugins/*.dll" +$expect = @{ "RynthCore-Setup.exe" = $manifest.core.sha256 } +foreach ($pl in $plugins) { $expect["plugins/$($pl.file)"] = $pl.sha256 } +foreach ($line in $remoteSums) { + $sum, $name = $line -split '\s+', 2 + if ($expect[$name.TrimStart('*')] -ne $sum) { throw "Hash mismatch on the server for $name — feed NOT published" } +} +Write-Host " $($expect.Count) files uploaded and hash-checked" + +Step "Replacing the website downloads" +scp -q "$rel\RynthCore-Setup.exe" "${SshHost}:$RemoteDir/.RynthCore-Setup.exe.new" +if ($LASTEXITCODE -ne 0) { throw "scp of the website installer failed" } +scp -q "$rel\RynthSuite-Plugins.zip" "${SshHost}:$RemoteDir/.RynthSuite-Plugins.zip.new" +if ($LASTEXITCODE -ne 0) { throw "scp of the plugins zip failed" } +ssh $SshHost "set -e; mkdir -p ~/backups/rynth; cd '$RemoteDir'; for f in RynthCore-Setup.exe RynthSuite-Plugins.zip; do [ -f `$f ] && cp -p `$f ~/backups/rynth/`$f.before-$release || true; mv -f .`$f.new `$f; done" +if ($LASTEXITCODE -ne 0) { throw "Replacing the website downloads failed" } + +Step "Publishing the feed" +scp -q "$rel\update.json" "${SshHost}:$RemoteDir/.update.json.new" +if ($LASTEXITCODE -ne 0) { throw "scp of update.json failed" } +ssh $SshHost "mv -f '$RemoteDir/.update.json.new' '$RemoteDir/update.json'" +if ($LASTEXITCODE -ne 0) { throw "Publishing update.json failed" } +# The release notes follow the feed, so the page never lists a release launchers can't get yet. +scp -q "$rel\releases.json" "${SshHost}:$RemoteDir/.releases.json.new" +if ($LASTEXITCODE -ne 0) { throw "scp of releases.json failed" } +ssh $SshHost "mv -f '$RemoteDir/.releases.json.new' '$RemoteDir/releases.json'" +if ($LASTEXITCODE -ne 0) { throw "Publishing releases.json failed" } + +# ── 5. Verify ──────────────────────────────────────────────────────────────── +Step "Verifying the live feed" +$tmp = New-TemporaryFile +try { + Invoke-WebRequest "$BaseUrl/update.json" -OutFile $tmp -UseBasicParsing -Headers @{ "Cache-Control" = "no-cache" } + if ((Sha256 $tmp) -ne (Sha256 "$rel\update.json")) { throw "The live update.json differs from the one just signed!" } + if (-not (Test-Envelope $tmp $trusted)) { throw "The live update.json does not verify!" } +} finally { Remove-Item $tmp -ErrorAction SilentlyContinue } + +Write-Host "" +Write-Host "Published RynthCore $Version (release $release)." -ForegroundColor Green +Write-Host "Launchers pick it up at their next check, and aelrynth.com/rynth.html lists it. Still by hand: the public source snapshots." diff --git a/installer/RynthCore.iss b/installer/RynthCore.iss index 8269aef..b37744a 100644 --- a/installer/RynthCore.iss +++ b/installer/RynthCore.iss @@ -13,7 +13,6 @@ AppId={{A8B4C2D1-E3F5-4678-9ABC-DEF012345678} AppName=RynthCore AppVersion=0.0.0 AppPublisher=RynthCore -; Canonical product/docs page (aelrynth.com); tombohar GitHub upstream is gone. AppPublisherURL=https://aelrynth.com/rynth.html DefaultDirName=C:\Games\RynthCore DisableDirPage=no @@ -41,9 +40,14 @@ Name: desktopicon; Description: "Create a &desktop shortcut"; GroupDescription: ; Program files [Files] -; Installs the entire staging layout (launcher, Runtime\, Runtime\Plugins\, etc.) +; Launcher + engine runtime + Loot Editor go to {app} (default C:\Games\RynthCore\) Source: "staging\app\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs +; Plugin DLL goes to its canonical home next to plugin data dirs. +; Engine does NOT auto-scan this folder — user adds the full DLL path in the +; launcher's Plugins tab to enable the plugin. See BUILD.md "Deploy RynthAi Plugin". +Source: "staging\plugins\RynthAi\RynthCore.Plugin.RynthAi.dll"; DestDir: "C:\Games\RynthSuite\RynthAi"; Flags: ignoreversion + ; Data directories (created once; never removed on uninstall) [Dirs] Name: "C:\Games\RynthSuite\RynthAi"; Flags: uninsneveruninstall @@ -62,7 +66,29 @@ Name: "C:\Games\RynthSuite\RynthAi\ItemGiver"; Flags: uninsnev [Icons] ; Start Menu Name: "{group}\RynthCore"; Filename: "{app}\RynthCore.exe"; WorkingDir: "{app}"; Comment: "Launch RynthCore and inject into Asheron's Call" +Name: "{group}\Loot Editor"; Filename: "{app}\Tools\LootEditor\RynthCore.LootEditor.exe"; WorkingDir: "{app}\Tools\LootEditor"; Comment: "Edit VTank-style loot profiles" Name: "{group}\Uninstall RynthCore"; Filename: "{uninstallexe}" ; Optional Desktop shortcut (created only when the desktopicon task is checked) Name: "{autodesktop}\RynthCore"; Filename: "{app}\RynthCore.exe"; WorkingDir: "{app}"; Tasks: desktopicon + +[Run] +; Interactive install: offer to start the launcher on the last page. +Filename: "{app}\RynthCore.exe"; WorkingDir: "{app}"; Description: "Launch RynthCore"; Flags: nowait postinstall skipifsilent +; The launcher's updater runs this installer with /SILENT /RELAUNCH after closing itself; +; bring it back when the upgrade is done. +Filename: "{app}\RynthCore.exe"; WorkingDir: "{app}"; Flags: nowait runasoriginaluser; Check: CmdLineParamExists('/RELAUNCH') + +[Code] +function CmdLineParamExists(const Value: string): Boolean; +var + I: Integer; +begin + Result := False; + for I := 1 to ParamCount do + if CompareText(ParamStr(I), Value) = 0 then + begin + Result := True; + Exit; + end; +end; diff --git a/installer/Sign-Update.ps1 b/installer/Sign-Update.ps1 new file mode 100644 index 0000000..fef6764 --- /dev/null +++ b/installer/Sign-Update.ps1 @@ -0,0 +1,58 @@ +#Requires -Version 7 +<# +.SYNOPSIS + Signs an update manifest into the envelope the launcher verifies (RynthUpdater.VerifyEnvelope). + +.DESCRIPTION + Output: {"payload": base64(manifest bytes), "signatures": [{"key": , "sig": base64}]}, + ECDSA P-256 / SHA-256 over the exact payload bytes, IEEE P1363 format. Signs with the DPAPI + primary key from New-UpdateSigningKey.ps1 — no prompt — or, with -UseBackupKey, the offline + backup key (asks for its password). +#> +param( + [Parameter(Mandatory)][string]$PayloadPath, + [Parameter(Mandatory)][string]$OutPath, + [string]$KeyDir = (Join-Path $env:USERPROFILE ".rynthcore-update-signing"), + [switch]$UseBackupKey, + [string]$BackupKeyPath, + # For scripted tests only; normally you are prompted. + [SecureString]$BackupPassword +) + +$ErrorActionPreference = "Stop" +Add-Type -AssemblyName System.Security + +$ec = [System.Security.Cryptography.ECDsa]::Create() +if ($UseBackupKey) { + if (-not $BackupKeyPath) { $BackupKeyPath = Join-Path $KeyDir "backup.key.p8" } + if (-not (Test-Path $BackupKeyPath)) { throw "Backup key not found at $BackupKeyPath" } + if (-not $BackupPassword) { $BackupPassword = Read-Host "Backup key password" -AsSecureString } + $pw = ConvertFrom-SecureString $BackupPassword -AsPlainText + $read = 0 + $ec.ImportEncryptedPkcs8PrivateKey($pw, [IO.File]::ReadAllBytes($BackupKeyPath), [ref]$read) + $pw = $null +} else { + $primaryPath = Join-Path $KeyDir "primary.key" + if (-not (Test-Path $primaryPath)) { + throw "No signing key at $primaryPath. Run installer\New-UpdateSigningKey.ps1 first." + } + $entropy = [Text.Encoding]::UTF8.GetBytes("RynthCore update signing v1") + $pkcs8 = [System.Security.Cryptography.ProtectedData]::Unprotect([IO.File]::ReadAllBytes($primaryPath), $entropy, 'CurrentUser') + try { + $read = 0 + $ec.ImportPkcs8PrivateKey($pkcs8, [ref]$read) + } finally { [Array]::Clear($pkcs8) } +} + +$payload = [IO.File]::ReadAllBytes($PayloadPath) +$sig = $ec.SignData($payload, [System.Security.Cryptography.HashAlgorithmName]::SHA256, + [System.Security.Cryptography.DSASignatureFormat]::IeeeP1363FixedFieldConcatenation) +$spki = $ec.ExportSubjectPublicKeyInfo() +$id = ([Convert]::ToHexString([System.Security.Cryptography.SHA256]::HashData($spki), 0, 8)).ToLowerInvariant() + +$envelope = [ordered]@{ + payload = [Convert]::ToBase64String($payload) + signatures = @([ordered]@{ key = $id; sig = [Convert]::ToBase64String($sig) }) +} +Set-Content -Path $OutPath -Value ($envelope | ConvertTo-Json -Depth 4) -Encoding utf8NoBOM +Write-Host "Signed $PayloadPath with key $id -> $OutPath" diff --git a/native/SehTrampoline/Build-SehTrampoline.ps1 b/native/SehTrampoline/Build-SehTrampoline.ps1 new file mode 100644 index 0000000..99449bc --- /dev/null +++ b/native/SehTrampoline/Build-SehTrampoline.ps1 @@ -0,0 +1,38 @@ +# Build-SehTrampoline.ps1 +# Compiles RynthCore.SehTrampoline.dll (x86 MSVC) and copies to the runtime. +# Run from anywhere; finds VS automatically via vswhere. + +$ErrorActionPreference = "Stop" + +$vsPath = & "C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe" ` + -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 ` + -property installationPath 2>$null + +if (-not $vsPath) { Write-Error "Visual Studio with C++ tools not found."; exit 1 } + +$vcVer = (Get-ChildItem "$vsPath\VC\Tools\MSVC" | Sort-Object Name -Descending | Select-Object -First 1).Name +$vcBase = "$vsPath\VC\Tools\MSVC\$vcVer" +$cl = "$vcBase\bin\Hostx86\x86\cl.exe" +$sdkVer = (Get-ChildItem "C:\Program Files (x86)\Windows Kits\10\Include" | Sort-Object Name -Descending | Select-Object -First 1).Name +$sdkInc = "C:\Program Files (x86)\Windows Kits\10\Include\$sdkVer" +$sdkLib = "C:\Program Files (x86)\Windows Kits\10\Lib\$sdkVer" + +$env:INCLUDE = "$vcBase\include;$sdkInc\ucrt;$sdkInc\um;$sdkInc\shared" +$env:LIB = "$vcBase\lib\x86;$sdkLib\ucrt\x86;$sdkLib\um\x86" + +$src = $PSScriptRoot +$out = Join-Path $src "bin" +New-Item -ItemType Directory -Path $out -Force | Out-Null + +Write-Host "Compiling SehTrampoline.c (MSVC $vcVer, x86)..." +Set-Location $out +& $cl /nologo /O2 /MT /GS- /LD /W3 "$src\SehTrampoline.c" ` + /link /MACHINE:X86 /OUT:"$out\RynthCore.SehTrampoline.dll" +if ($LASTEXITCODE -ne 0) { Write-Error "Compilation failed."; exit $LASTEXITCODE } + +$size = (Get-Item "$out\RynthCore.SehTrampoline.dll").Length +Write-Host "Built: RynthCore.SehTrampoline.dll ($size bytes)" + +$runtimeDst = "C:\Games\RynthCore\Runtime\RynthCore.SehTrampoline.dll" +Copy-Item "$out\RynthCore.SehTrampoline.dll" $runtimeDst -Force +Write-Host "Deployed to $runtimeDst" diff --git a/native/SehTrampoline/SehTrampoline.c b/native/SehTrampoline/SehTrampoline.c new file mode 100644 index 0000000..a458eeb --- /dev/null +++ b/native/SehTrampoline/SehTrampoline.c @@ -0,0 +1,439 @@ +/* + * RynthCore.SehTrampoline.dll — x86 native SEH wrapper for dangerous AC API calls. + * + * NativeAOT managed try/catch cannot intercept access violations (hardware + * exceptions / corrupted-state exceptions). When the bot calls AC APIs on + * objects that are being torn down by the client's object lifecycle, the AV + * propagates up and kills acclient.exe. + * + * This DLL provides __try/__except wrappers that live entirely in native code. + * Each export calls a supplied function pointer inside a structured exception + * handler scoped only to that one call — it does not install any process-wide + * handler (VEH/SUEF), so it cannot interfere with AC's or Avalonia's own + * internal exception handling. + * + * Conventions: + * - All exports are __cdecl so the caller controls stack cleanup. + * - Return value: 1 = call completed normally; 0 = AV was caught. + * - out_* parameters are always written (safe default on AV). + * - __thiscall helpers are separate non-__try functions; MSVC does not allow + * inline __asm and __try in the same function on x86. + * + * Build: cl /nologo /O2 /MD /LD SehTrampoline.c /link /MACHINE:X86 + * /OUT:RynthCore.SehTrampoline.dll /DEF:SehTrampoline.def + */ + +#define WIN32_LEAN_AND_MEAN +#include + +BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason, LPVOID lpReserved) +{ + (void)hModule; (void)ul_reason; (void)lpReserved; + return TRUE; +} + +/* ── Cdecl helpers ─────────────────────────────────────────────────────── */ + +/* void* __cdecl fn(unsigned int id) — e.g. GetWeenieObject */ +typedef void* (__cdecl *Fn_CdeclPtrUint)(unsigned int); +__declspec(dllexport) int __cdecl +SEH_CdeclPtrUint(Fn_CdeclPtrUint fn, unsigned int arg, void** out_result) +{ + *out_result = NULL; + __try { + *out_result = fn(arg); + } + __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION + ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + *out_result = NULL; + return 0; + } + return 1; +} + +/* void* __cdecl fn() — e.g. GetCombatSystem */ +typedef void* (__cdecl *Fn_CdeclPtrVoid)(void); +__declspec(dllexport) int __cdecl +SEH_CdeclPtrVoid(Fn_CdeclPtrVoid fn, void** out_result) +{ + *out_result = NULL; + __try { + *out_result = fn(); + } + __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION + ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + *out_result = NULL; + return 0; + } + return 1; +} + +/* void __cdecl fn(unsigned int, unsigned char) — e.g. CastSpell(spellId, targetIsSelected) */ +typedef void (__cdecl *Fn_CdeclVoidUintByte)(unsigned int, unsigned char); +__declspec(dllexport) int __cdecl +SEH_CdeclVoidUintByte(Fn_CdeclVoidUintByte fn, unsigned int arg1, unsigned char arg2) +{ + __try { + fn(arg1, arg2); + } + __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION + ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + return 0; + } + return 1; +} + +/* void __thiscall fn(this, unsigned int spellId, unsigned int targetId) + * e.g. ClientMagicSystem::FreeHandsAndCastSpell(this, spellId, targetId) @ 0x00567C90. + * Modeled as __fastcall (this in ECX, a dummy EDX slot, spellId+targetId on the stack; + * callee cleans the 8 stack bytes) — the exact, proven binding RynthSuite2 uses. The + * target is an EXPLICIT argument, so this never reads AC's global selection and never + * touches UI state (unlike CastSpell(spellId, targetIsSelected=1) @ 0x00568DE0, which + * reads [magicSysSingleton+0xF4]). __fastcall is a real declarable convention, so this + * needs no inline __asm and can host its own __try. */ +typedef void (__fastcall *Fn_FreeHandsCast)(void* ecx, void* edx, unsigned int spellId, unsigned int targetId); +__declspec(dllexport) int __cdecl +SEH_FreeHandsCast(void* fn, void* this_ptr, unsigned int spellId, unsigned int targetId) +{ + __try { + ((Fn_FreeHandsCast)fn)(this_ptr, 0, spellId, targetId); + } + __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION + ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + return 0; + } + return 1; +} + +/* ── Thiscall helpers — inline __asm lives here, NOT in __try functions ── */ + +/* + * MSVC x86: __thiscall puts 'this' in ECX. C has no __thiscall call-site + * syntax, so we use inline __asm. These helpers must NOT contain __try; + * the outer SEH wrappers call them so the SEH frame is established by the + * caller's stack frame, not by the helper. + */ + +/* unsigned char __thiscall fn(unsigned int objectId) */ +static unsigned char __cdecl +_helper_thiscall_byte_uint(void* fn_ptr, void* this_ptr, unsigned int arg) +{ + unsigned char result = 0; + __asm { + mov ecx, this_ptr + push arg + call fn_ptr + mov result, al + } + return result; +} + +/* unsigned int __thiscall fn() — no stack args, this in ECX */ +static unsigned int __cdecl +_helper_thiscall_uint_noarg(void* fn_ptr, void* this_ptr) +{ + unsigned int result = 0; + __asm { + mov ecx, this_ptr + call fn_ptr + mov result, eax + } + return result; +} + +/* ── Thiscall SEH wrappers ─────────────────────────────────────────────── */ + +/* + * unsigned char __thiscall fn(unsigned int objectId) + * e.g. ClientCombatSystem::ObjectIsAttackable(objectId) + */ +__declspec(dllexport) int __cdecl +SEH_ThiscallByteUint(void* fn, void* this_ptr, unsigned int arg, + unsigned char* out_result) +{ + *out_result = 0; + __try { + *out_result = _helper_thiscall_byte_uint(fn, this_ptr, arg); + } + __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION + ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + *out_result = 0; + return 0; + } + return 1; +} + +/* + * unsigned int __thiscall fn() + * e.g. ACCWeenieObject::InqType() + */ +__declspec(dllexport) int __cdecl +SEH_ThiscallUintNoArg(void* fn, void* this_ptr, unsigned int* out_result) +{ + *out_result = 0; + __try { + *out_result = _helper_thiscall_uint_noarg(fn, this_ptr); + } + __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION + ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + *out_result = 0; + return 0; + } + return 1; +} + +/* int __thiscall fn(unsigned int stype, void* outStruct) + * e.g. CACQualities/CWeenieObject::InqAttribute2nd(stype, &SecondaryAttribute). + * this in ECX; stype + outStruct on the stack (callee cleans, thiscall). Reads a + * 2nd-level attribute (health/stam/mana) into the caller's struct. Used to pull a + * MONSTER's real MaxHealth out of its (possibly partially-populated) qualities + * table without crashing if a sub-table is null — the AV that forced the + * AllowNonPlayerQualities gate. */ +static int __cdecl +_helper_thiscall_int_uint_ptr(void* fn_ptr, void* this_ptr, + unsigned int arg1, void* arg2) +{ + int result = 0; + __asm { + mov ecx, this_ptr + push arg2 /* outStruct (rightmost) */ + push arg1 /* stype */ + call fn_ptr /* thiscall callee cleans the 8 stack bytes */ + mov result, eax + } + return result; +} + +__declspec(dllexport) int __cdecl +SEH_ThiscallIntUintPtr(void* fn, void* this_ptr, unsigned int arg1, void* arg2, + int* out_result) +{ + *out_result = 0; + __try { + *out_result = _helper_thiscall_int_uint_ptr(fn, this_ptr, arg1, arg2); + } + __except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION + ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + *out_result = 0; + return 0; + } + return 1; +} + +/* ── Process-wide native crash logger (VEH) ─────────────────────────────── + * Logs the faulting 32-bit context + a module-resolved stack sweep to a + * dedicated file BEFORE the process dies, for the fatal exceptions that bypass + * NativeAOT's managed handlers: 0xC0000005 (AV / corrupted-state) and + * 0xC0000602 (STATUS_FAIL_FAST from RaiseFailFastException — e.g. an unhandled + * managed exception or a stack-walk fail-fast in the plugin/engine). + * + * This is PURE NATIVE: no managed callback / reverse-P/Invoke transition, so + * unlike the removed managed CrashLogger VEH it cannot itself re-trigger a + * NativeAOT fail-fast on an AC-owned thread. It only OBSERVES — returns + * EXCEPTION_CONTINUE_SEARCH so AC's own SEH / the runtime still proceed exactly + * as before. Uses only kernel32 APIs + hand-rolled formatting (no CRT stdio / + * user32) so the build link line stays unchanged. Hardened: stack sweep in + * __try/__except, capped log count, dedicated file (no contention with the + * managed log). x86 (32-bit) context fields only — matches the WOW64 target. + */ +static wchar_t g_crashLogPath[MAX_PATH]; +static volatile LONG g_crashCount = 0; +static PVOID g_vehHandle = NULL; + +static char* cl_str(char* p, const char* s) { while (*s) { *p++ = *s++; } return p; } + +static char* cl_hex(char* p, unsigned int v) +{ + const char* H = "0123456789ABCDEF"; + int i; + *p++ = '0'; *p++ = 'x'; + for (i = 28; i >= 0; i -= 4) { *p++ = H[(v >> i) & 0xF]; } + return p; +} + +static char* cl_u(char* p, unsigned int v) +{ + char tmp[12]; int n = 0; + if (v == 0) { *p++ = '0'; return p; } + while (v) { tmp[n++] = (char)('0' + (v % 10)); v /= 10; } + while (n) { *p++ = tmp[--n]; } + return p; +} + +/* Append "module.dll+0xRVA", or "0xADDR" if the address is in no module. */ +static char* cl_sym(char* p, unsigned int addr) +{ + HMODULE hm = NULL; + /* GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS(0x4) | UNCHANGED_REFCOUNT(0x2) */ + if (GetModuleHandleExW(0x4 | 0x2, (LPCWSTR)(UINT_PTR)addr, &hm) && hm) { + wchar_t wpath[MAX_PATH]; + DWORD n = GetModuleFileNameW(hm, wpath, MAX_PATH); + DWORD i, leaf = 0; + for (i = 0; i < n; i++) { if (wpath[i] == L'\\' || wpath[i] == L'/') leaf = i + 1; } + for (i = leaf; i < n; i++) { *p++ = (char)wpath[i]; } + p = cl_str(p, "+"); + p = cl_hex(p, addr - (unsigned int)(UINT_PTR)hm); + } else { + p = cl_hex(p, addr); + } + return p; +} + +static LONG CALLBACK CrashVeh(PEXCEPTION_POINTERS ep) +{ + DWORD code = ep->ExceptionRecord->ExceptionCode; + if (code != 0xC0000005 && code != 0xC0000602 && code != 0xC0000409) { + return EXCEPTION_CONTINUE_SEARCH; + } + if (InterlockedIncrement(&g_crashCount) > 24) { + return EXCEPTION_CONTINUE_SEARCH; + } + + { + HANDLE h = CreateFileW(g_crashLogPath, FILE_APPEND_DATA, + FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_ALWAYS, + FILE_ATTRIBUTE_NORMAL, NULL); + if (h == INVALID_HANDLE_VALUE) { return EXCEPTION_CONTINUE_SEARCH; } + SetFilePointer(h, 0, NULL, FILE_END); + + { + char buf[4096]; + char* p = buf; + CONTEXT* c = ep->ContextRecord; + unsigned int exAddr = (unsigned int)(UINT_PTR)ep->ExceptionRecord->ExceptionAddress; + DWORD wr; + + p = cl_str(p, "\r\n==== NATIVE CRASH LOGGER (SEH VEH) ====\r\n code="); + p = cl_hex(p, code); + p = cl_str(p, " exAddr="); + p = cl_sym(p, exAddr); + p = cl_str(p, " tid="); + p = cl_u(p, GetCurrentThreadId()); + { + SYSTEMTIME st; GetLocalTime(&st); + p = cl_str(p, " time="); + p = cl_u(p, st.wHour); p = cl_str(p, ":"); + if (st.wMinute < 10) { p = cl_str(p, "0"); } p = cl_u(p, st.wMinute); p = cl_str(p, ":"); + if (st.wSecond < 10) { p = cl_str(p, "0"); } p = cl_u(p, st.wSecond); + } + if ((code == 0xC0000005 || code == 0xC0000409) && ep->ExceptionRecord->NumberParameters >= 2) { + unsigned int acc = (unsigned int)ep->ExceptionRecord->ExceptionInformation[0]; + unsigned int dataAddr = (unsigned int)ep->ExceptionRecord->ExceptionInformation[1]; + p = cl_str(p, " access="); + p = cl_str(p, acc == 1 ? "WRITE" : (acc == 8 ? "EXEC" : "READ")); + p = cl_str(p, " dataAddr="); + p = cl_hex(p, dataAddr); /* the [null+X] value, e.g. 0xC for the parser race */ + } + p = cl_str(p, "\r\n eip="); p = cl_sym(p, c->Eip); + p = cl_str(p, " esp="); p = cl_hex(p, c->Esp); + p = cl_str(p, " ebp="); p = cl_hex(p, c->Ebp); + p = cl_str(p, "\r\n eax="); p = cl_hex(p, c->Eax); + p = cl_str(p, " ebx="); p = cl_hex(p, c->Ebx); + p = cl_str(p, " ecx="); p = cl_hex(p, c->Ecx); + p = cl_str(p, " edx="); p = cl_hex(p, c->Edx); + p = cl_str(p, " esi="); p = cl_hex(p, c->Esi); + p = cl_str(p, " edi="); p = cl_hex(p, c->Edi); + p = cl_str(p, "\r\n stack code pointers (esp -> up):\r\n"); + WriteFile(h, buf, (DWORD)(p - buf), &wr, NULL); + + __try { + unsigned int* sp = (unsigned int*)c->Esp; + int i, emitted = 0; + for (i = 0; i < 4096 && emitted < 96; i++) { + unsigned int v = sp[i]; + if (v > 0x00401000u && v < 0x7FFF0000u) { + HMODULE hm = NULL; + if (GetModuleHandleExW(0x4 | 0x2, (LPCWSTR)(UINT_PTR)v, &hm) && hm) { + char* q = buf; + q = cl_str(q, " +"); + q = cl_hex(q, (unsigned int)(i * 4)); + q = cl_str(q, " "); + q = cl_sym(q, v); + q = cl_str(q, "\r\n"); + WriteFile(h, buf, (DWORD)(q - buf), &wr, NULL); + emitted++; + } + } + } + } + __except (EXCEPTION_EXECUTE_HANDLER) { + const char* m = " \r\n"; + WriteFile(h, m, (DWORD)lstrlenA(m), &wr, NULL); + } + + { + const char* e = "==== END NATIVE CRASH ====\r\n"; + WriteFile(h, e, (DWORD)lstrlenA(e), &wr, NULL); + } + } + CloseHandle(h); + } + return EXCEPTION_CONTINUE_SEARCH; +} + +/* Install the VEH once. logPath = wide path to the dedicated crash log. */ +__declspec(dllexport) void __cdecl +RC_InstallCrashLogger(const wchar_t* logPath) +{ + if (g_vehHandle) { return; } + if (logPath) { + int i = 0; + for (; logPath[i] && i < MAX_PATH - 1; i++) { g_crashLogPath[i] = logPath[i]; } + g_crashLogPath[i] = 0; + } + g_vehHandle = AddVectoredExceptionHandler(1, CrashVeh); +} + +/* ── Tagged-text parser guard (native MinHook detour body) ──────────────── + * Null-guards AC's tag-parser consumer FUN_0067D3C0 (live VA 0x0067D3C0) + * against a null parser-context singleton. DAT_008F881C (AC's "current tag + * parser context") is unsynchronized; when our off-thread pump triggers a + * text-generation path while AC's main thread is mid-parse, it races to null + * and the consumer does `MOV EDI,[EAX+0xC]` with EAX=0 at 0x0067D3DA -> AV + * READ [null+0xC]. That is the recurring text-parser-race crash (captured + * 2026-06-03 native-crash.log: code=0xC0000005 exAddr=acclient.exe+0x27D3DA). + * + * MUST be native: the consumer is called by AC's main thread for EVERY parsed + * tag. A MANAGED MinHook detour here (reverse-P/Invoke per tag) reintroduced a + * NativeAOT fail-fast and crashed in ~7s (2026-05-25, pid 20852). This detour + * has NO managed transition. The engine installs the hook via MinHook and + * hands us the trampoline (original) through RC_SetTagParserOriginal BEFORE it + * enables the hook. If the parser context is null we drop ONE parse run + * (return 0) instead of dereferencing it; the caller (FUN_0067E150) discards + * the return value, so dropping it is safe. + * + * The hooked function is __cdecl: void* FUN_0067D3C0(void* parserContext). + */ +typedef void* (__cdecl *Fn_TagParserConsume)(void*); +static Fn_TagParserConsume g_tagParserOriginal = NULL; +static volatile LONG g_tagParserSkips = 0; + +static void* __cdecl RC_TagParserGuard(void* parserContext) +{ + if (parserContext == NULL) { + InterlockedIncrement(&g_tagParserSkips); + return NULL; /* drop this parse run — no null deref */ + } + if (g_tagParserOriginal == NULL) { + return NULL; /* not wired yet (pre-SetOriginal) — fail safe */ + } + return g_tagParserOriginal(parserContext); +} + +/* Returns the address of the native detour for the engine to pass to MinHook. */ +__declspec(dllexport) void* __cdecl RC_GetTagParserGuardAddress(void) +{ + return (void*)(UINT_PTR)&RC_TagParserGuard; +} + +/* Engine calls this with the MinHook trampoline (original) BEFORE enabling. */ +__declspec(dllexport) void __cdecl RC_SetTagParserOriginal(void* original) +{ + g_tagParserOriginal = (Fn_TagParserConsume)original; +} + +/* Diagnostic: how many null-context parse runs we've dropped. */ +__declspec(dllexport) unsigned int __cdecl RC_TagParserSkipCount(void) +{ + return (unsigned int)g_tagParserSkips; +} diff --git a/scripts/Deploy-RynthCore.ps1 b/scripts/Deploy-RynthCore.ps1 index 48a30db..74caba6 100644 --- a/scripts/Deploy-RynthCore.ps1 +++ b/scripts/Deploy-RynthCore.ps1 @@ -1,6 +1,21 @@ param( [string]$Destination = "C:\Games\RynthCore", - [switch]$SkipPublish + [string]$PluginsDestination = "C:\Games\RynthSuite", + [switch]$SkipPublish, + # When set, skip both the launcher publish AND the launcher payload copy + # to $Destination root. Use this for engine-only / plugin-only iteration + # while the launcher (RynthCore.exe) is running — without it, the launcher's + # held Avalonia.Base.dll causes a Copy-Item lock failure that wipes the + # Runtime\ folder. Engine still publishes/deploys to Runtime\ and plugins + # still deploy under $PluginsDestination. + [switch]$SkipLauncher, + # Pre-deploy pattern gate (tools\check-patterns.ps1): verify every acclient.exe + # signature embedded in the engine source still resolves uniquely + correctly + # against the live client BEFORE shipping. -SkipPatternCheck bypasses it; + # -AcClient overrides the binary it checks (default: auto-detect the private + # copy under $Destination\AcClient, else C:\Turbine\Asheron's Call). + [switch]$SkipPatternCheck, + [string]$AcClient = "" ) $ErrorActionPreference = "Stop" @@ -9,24 +24,73 @@ Set-StrictMode -Version Latest $repoRoot = Split-Path -Parent $PSScriptRoot $launcherProject = Join-Path $repoRoot "src\RynthCore.App.Avalonia\RynthCore.App.Avalonia.csproj" $engineProject = Join-Path $repoRoot "src\RynthCore.Engine\RynthCore.Engine.csproj" +$loaderProject = Join-Path $repoRoot "src\RynthCore.Loader\RynthCore.Loader.csproj" + +# Plugins are deployed to per-plugin folders under $PluginsDestination +# (e.g. C:\Games\RynthSuite\RynthAi\). Users register plugin DLLs through +# the launcher's "Add Plugin DLL" UI; the engine no longer relies on a +# default Runtime\Plugins\ scan being populated by deploy. +# +# RynthAi's live source lives in a separate repo at C:\Projects\RynthSuite - +# the rynthcore\Plugins\RynthCore.Plugin.RynthAi tree is a stub (~1 MB +# published) that lacks Combat / Loot / Meta / Raycasting / LegacyUi. +# Always source from the RynthSuite tree so the real ~8 MB plugin ships. +$rynthAiSourceRoot = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthAi" +$rynthChatSourceRoot = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthChat" +$rynthVisionSourceRoot = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthVision" +$rynthJuiceSourceRoot = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthJuice" $pluginProjects = @( @{ - Project = Join-Path $repoRoot "Plugins\RynthCore.Plugin.HelloBox\RynthCore.Plugin.HelloBox.csproj" - Publish = Join-Path $repoRoot "Plugins\RynthCore.Plugin.HelloBox\bin\Release\net9.0-windows\win-x86\publish" - DllName = "RynthCore.Plugin.HelloBox.dll" + Project = Join-Path $rynthAiSourceRoot "RynthCore.Plugin.RynthAi.csproj" + Publish = Join-Path $rynthAiSourceRoot "bin\Release\net10.0-windows\win-x86\publish" + DllName = "RynthCore.Plugin.RynthAi.dll" + DestSubdir = "RynthAi" }, @{ - Project = Join-Path $repoRoot "Plugins\RynthCore.Plugin.RynthAi\RynthCore.Plugin.RynthAi.csproj" - Publish = Join-Path $repoRoot "Plugins\RynthCore.Plugin.RynthAi\bin\Release\net9.0-windows\win-x86\publish" - DllName = "RynthCore.Plugin.RynthAi.dll" + Project = Join-Path $rynthChatSourceRoot "RynthCore.Plugin.RynthChat.csproj" + Publish = Join-Path $rynthChatSourceRoot "bin\Release\net10.0-windows\win-x86\publish" + DllName = "RynthCore.Plugin.RynthChat.dll" + DestSubdir = "RynthChat" + }, + # RynthVision sets to its deploy home, so publish lands + # directly in $PluginsDestination\RynthVision. The copy step below detects + # source == dest and skips the redundant self-copy. + @{ + Project = Join-Path $rynthVisionSourceRoot "RynthCore.Plugin.RynthVision.csproj" + Publish = Join-Path $PluginsDestination "RynthVision" + DllName = "RynthCore.Plugin.RynthVision.dll" + DestSubdir = "RynthVision" + }, + @{ + Project = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthTracker\RynthCore.Plugin.RynthTracker.csproj" + Publish = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthTracker\bin\Release\net10.0-windows\win-x86\publish" + DllName = "RynthCore.Plugin.RynthTracker.dll" + DestSubdir = "RynthTracker" + }, + # RynthJuice sets to its deploy home (like RynthVision), so + # publish lands directly in $PluginsDestination\RynthJuice and the copy step + # below detects source == dest and skips the redundant self-copy. + @{ + Project = Join-Path $rynthJuiceSourceRoot "RynthCore.Plugin.RynthJuice.csproj" + Publish = Join-Path $PluginsDestination "RynthJuice" + DllName = "RynthCore.Plugin.RynthJuice.dll" + DestSubdir = "RynthJuice" + }, + # RynthNav also publishes straight to its deploy home via . + # It was missing from this list entirely, so full deploys never refreshed it. + @{ + Project = "C:\Projects\RynthSuite\Plugins\RynthCore.Plugin.RynthNav\RynthCore.Plugin.RynthNav.csproj" + Publish = Join-Path $PluginsDestination "RynthNav" + DllName = "RynthCore.Plugin.RynthNav.dll" + DestSubdir = "RynthNav" } ) -$launcherPublish = Join-Path $repoRoot "src\RynthCore.App.Avalonia\bin\Release\net9.0-windows7.0\win-x86\publish" -$enginePublish = Join-Path $repoRoot "src\RynthCore.Engine\bin\Release\net9.0-windows\win-x86\publish" +$launcherPublish = Join-Path $repoRoot "src\RynthCore.App.Avalonia\bin\Release\net10.0-windows7.0\win-x86\publish" +$enginePublish = Join-Path $repoRoot "src\RynthCore.Engine\bin\Release\net10.0-windows\win-x86\publish" +$loaderPublish = Join-Path $repoRoot "src\RynthCore.Loader\bin\Release\net10.0-windows\win-x86\publish" $runtimeDir = Join-Path $Destination "Runtime" -$runtimePluginsDir = Join-Path $runtimeDir "Plugins" function Copy-FilteredChildren { param( @@ -41,14 +105,71 @@ function Copy-FilteredChildren { } | Copy-Item -Destination $Target -Recurse -Force } +# --------------------------------------------------------------------------- +# Pre-deploy pattern gate: verify every acclient.exe signature embedded in the +# engine source still resolves uniquely + correctly against the live client +# binary BEFORE we publish/ship. A future AC patch / ACE rebuild that shifts +# code or a data global fails HERE instead of silently shipping a hook that +# falls back to a stale VA at runtime. (tools\pe_pattern.py CHECK, wrapped by +# tools\check-patterns.ps1.) Bypass: -SkipPatternCheck. Target: -AcClient. +# --------------------------------------------------------------------------- +if (-not $SkipPatternCheck) { + $checkScript = Join-Path $repoRoot "tools\check-patterns.ps1" + $acClientPath = $AcClient + if ([string]::IsNullOrWhiteSpace($acClientPath)) { + foreach ($cand in @((Join-Path $Destination "AcClient\acclient.exe"), "C:\Turbine\Asheron's Call\acclient.exe")) { + if (Test-Path -LiteralPath $cand) { $acClientPath = $cand; break } + } + } + + # Fail CLOSED: a gate that silently downgrades to a warning when python / + # the script / the binary is missing is no gate at all — the explicit + # bypass is -SkipPatternCheck. + if (-not (Get-Command python -ErrorAction SilentlyContinue)) { + throw "Pattern gate cannot run: 'python' is not on PATH. Install Python, or pass -SkipPatternCheck to bypass deliberately." + } + elseif (-not (Test-Path -LiteralPath $checkScript)) { + throw "Pattern gate cannot run: $checkScript not found. Pass -SkipPatternCheck to bypass deliberately." + } + elseif ([string]::IsNullOrWhiteSpace($acClientPath) -or -not (Test-Path -LiteralPath $acClientPath)) { + throw "Pattern gate cannot run: no acclient.exe found (tried '$Destination\AcClient' and 'C:\Turbine\Asheron''s Call'). Pass -AcClient , or -SkipPatternCheck to bypass deliberately." + } + else { + Write-Host "Pattern gate: verifying engine signatures against $acClientPath ..." + & $checkScript -AcClient $acClientPath + if ($LASTEXITCODE -ne 0) { + throw "Pattern gate FAILED (exit $LASTEXITCODE) - aborting deploy. A signature drifted or is wrong; re-cut it with tools\pe_pattern.py (GEN / ALL / DATA), fix the source, rebuild, and retry. Override with -SkipPatternCheck only if you understand the risk." + } + Write-Host "Pattern gate PASSED - all engine signatures unique & correct." + } +} + +function Invoke-Publish { + param( + [Parameter(Mandatory = $true)][string]$What, + [Parameter(Mandatory = $true)][string[]]$Arguments + ) + dotnet @Arguments + # PS 5.1's $ErrorActionPreference=Stop does NOT throw on a native exe's + # nonzero exit — without this check a failed publish silently deployed the + # PREVIOUS publish output (the root staleness trap). + if ($LASTEXITCODE -ne 0) { + throw "dotnet publish FAILED for $What (exit $LASTEXITCODE) - aborting deploy so stale output cannot ship." + } +} + if (-not $SkipPublish) { $env:DOTNET_CLI_HOME = Join-Path $repoRoot ".dotnet-home-deploy-clean" $env:DOTNET_SKIP_FIRST_TIME_EXPERIENCE = "1" - dotnet publish $launcherProject -c Release -r win-x86 - dotnet publish $engineProject -c Release + if (-not $SkipLauncher) { + # --self-contained false is required: omitting it with the launcher's IncludeNativeLibrariesForSelfExtract=true produces a broken half-payload (apphost + coreclr.dll, no framework) that reports ".NET is not installed". + Invoke-Publish -What "launcher" -Arguments @('publish', $launcherProject, '-c', 'Release', '-r', 'win-x86', '--self-contained', 'false') + } + Invoke-Publish -What "engine" -Arguments @('publish', $engineProject, '-c', 'Release') + Invoke-Publish -What "loader" -Arguments @('publish', $loaderProject, '-c', 'Release') foreach ($plugin in $pluginProjects) { - dotnet publish $plugin.Project -c Release + Invoke-Publish -What $plugin.DllName -Arguments @('publish', $plugin.Project, '-c', 'Release') } } @@ -77,32 +198,129 @@ $rootCleanup = @( "RynthCore.exe.pre-avalonia-redeploy-20260331.bak" ) -foreach ($name in $rootCleanup) { - $target = Join-Path $Destination $name - if (Test-Path -LiteralPath $target) { - Remove-Item -LiteralPath $target -Recurse -Force +if (-not $SkipLauncher) { + # Same pre-flight for the launcher payload: a running RynthCore.exe holds its + # Avalonia DLLs, and the copy failing on one of them used to abort the deploy + # AFTER Runtime\ below had been wiped (2026-09-26) — no engine until a redeploy. + $launcherLocked = @() + foreach ($f in Get-ChildItem -LiteralPath $launcherPublish -File) { + $target = Join-Path $Destination $f.Name + if ($f.Name -eq "RynthCore.App.Avalonia.exe") { $target = Join-Path $Destination "RynthCore.exe" } + if (-not (Test-Path -LiteralPath $target)) { continue } + try { + $s = [System.IO.File]::Open($target, 'Open', 'ReadWrite', 'None') + $s.Close() + } catch { + $launcherLocked += $target + } + } + if ($launcherLocked.Count -gt 0) { + throw ("Deploy aborted BEFORE touching anything - $($launcherLocked.Count) launcher file(s) are locked (close the RynthCore launcher, or pass -SkipLauncher):`n " + ($launcherLocked -join "`n ")) + } + + foreach ($name in $rootCleanup) { + $target = Join-Path $Destination $name + if (Test-Path -LiteralPath $target) { + Remove-Item -LiteralPath $target -Recurse -Force + } } } if (Test-Path -LiteralPath $runtimeDir) { + # Lock pre-flight BEFORE the destructive wipe. A running client holds + # Runtime\RynthCore.Loader.dll (loaded UNshadowed into acclient.exe) and + # its .engine_loads shadow DLLs; the old behavior wiped Runtime\ first and + # then died on the locked file, leaving a half-destroyed deploy. Probe + # every file for an exclusive open and abort cleanly while the old deploy + # is still intact. + $locked = @() + foreach ($f in Get-ChildItem -LiteralPath $runtimeDir -Recurse -File) { + try { + $s = [System.IO.File]::Open($f.FullName, 'Open', 'ReadWrite', 'None') + $s.Close() + } catch { + $locked += $f.FullName + } + } + if ($locked.Count -gt 0) { + throw ("Deploy aborted BEFORE wiping Runtime\ - $($locked.Count) file(s) are locked by running processes (close all AC clients and the launcher, then retry):`n " + ($locked -join "`n ")) + } Remove-Item -LiteralPath $runtimeDir -Recurse -Force } New-Item -ItemType Directory -Path $Destination -Force | Out-Null New-Item -ItemType Directory -Path $runtimeDir -Force | Out-Null -New-Item -ItemType Directory -Path $runtimePluginsDir -Force | Out-Null -Copy-FilteredChildren -Source $launcherPublish -Target $Destination -ExcludeNames @("RynthCore.App.Avalonia.exe") -ExcludeExtensions @(".pdb") -Copy-FilteredChildren -Source $enginePublish -Target $runtimeDir -ExcludeExtensions @(".pdb") -foreach ($plugin in $pluginProjects) { - Copy-FilteredChildren -Source $plugin.Publish -Target $runtimePluginsDir -ExcludeNames @("cimgui.dll") -ExcludeExtensions @(".pdb") +if (-not $SkipLauncher) { + # Launcher payload to root, except the bootstrapper exe (renamed below). + Copy-FilteredChildren -Source $launcherPublish -Target $Destination -ExcludeNames @("RynthCore.App.Avalonia.exe") -ExcludeExtensions @(".pdb") } -Copy-Item -LiteralPath (Join-Path $launcherPublish "RynthCore.App.Avalonia.exe") -Destination (Join-Path $Destination "RynthCore.exe") -Force -foreach ($plugin in $pluginProjects) { - Copy-Item -LiteralPath (Join-Path $plugin.Publish $plugin.DllName) -Destination (Join-Path $runtimePluginsDir $plugin.DllName) -Force -} -Get-ChildItem -Path $Destination -Recurse -Filter *.pdb -File | Remove-Item -Force +# Engine payload to Runtime\. Skip the bundled Plugins\ subfolder - plugins +# are deployed separately to $PluginsDestination so they have a single home. +Copy-FilteredChildren -Source $enginePublish -Target $runtimeDir -ExcludeNames @("Plugins") -ExcludeExtensions @(".pdb") -Write-Host "Launcher deployed to $Destination" +# Loader DLL - this is what RynthCore.Injector loads into acclient.exe; the +# Loader then maps RynthCore.Engine.dll and provides hot-reload support. +Copy-Item -LiteralPath (Join-Path $loaderPublish "RynthCore.Loader.dll") -Destination (Join-Path $runtimeDir "RynthCore.Loader.dll") -Force + +# SEH trampoline - small native x86 MSVC DLL providing __try/__except wrappers +# around dangerous AC API calls so object-teardown AVs are caught instead of +# crashing acclient.exe. Built by native\SehTrampoline\Build-SehTrampoline.ps1. +$sehTrampolineSrc = Join-Path $repoRoot "native\SehTrampoline\bin\RynthCore.SehTrampoline.dll" +$sehTrampolineC = Join-Path $repoRoot "native\SehTrampoline\SehTrampoline.c" +if (-not (Test-Path -LiteralPath $sehTrampolineSrc)) { + # Fail closed: the trampoline is load-bearing (SEH-guarded AC reads) and a + # missing DLL silently shipped an engine whose guarded calls all throw. + throw "RynthCore.SehTrampoline.dll not found at $sehTrampolineSrc - build it with native\SehTrampoline\Build-SehTrampoline.ps1, then re-run deploy." +} +if (Test-Path -LiteralPath $sehTrampolineC) { + # The trampoline is hand-built (cl.exe), not part of dotnet publish — a + # newer .c than the built DLL means the binary about to ship is stale. + $srcTime = (Get-Item -LiteralPath $sehTrampolineC).LastWriteTime + $dllTime = (Get-Item -LiteralPath $sehTrampolineSrc).LastWriteTime + if ($srcTime -gt $dllTime) { + throw "RynthCore.SehTrampoline.dll is STALE (SehTrampoline.c edited $srcTime > DLL built $dllTime). Rebuild with native\SehTrampoline\Build-SehTrampoline.ps1, then re-run deploy." + } +} +Copy-Item -LiteralPath $sehTrampolineSrc -Destination (Join-Path $runtimeDir "RynthCore.SehTrampoline.dll") -Force +Write-Host "SEH trampoline deployed to $runtimeDir" + +if (-not $SkipLauncher) { + Copy-Item -LiteralPath (Join-Path $launcherPublish "RynthCore.App.Avalonia.exe") -Destination (Join-Path $Destination "RynthCore.exe") -Force +} + +foreach ($plugin in $pluginProjects) { + $pluginSrc = Join-Path $plugin.Publish $plugin.DllName + if (-not (Test-Path -LiteralPath $pluginSrc)) { + Write-Warning "Plugin DLL not found at $pluginSrc - skipping copy." + continue + } + + $pluginTargetDir = Join-Path $PluginsDestination $plugin.DestSubdir + if (-not (Test-Path -LiteralPath $pluginTargetDir)) { + New-Item -ItemType Directory -Path $pluginTargetDir -Force | Out-Null + } + + # Only the DLL - leave any user data (LootProfiles\, imgui.ini, etc.) + # in place by not touching anything else under $pluginTargetDir. + $pluginDest = Join-Path $pluginTargetDir $plugin.DllName + if ([System.IO.Path]::GetFullPath($pluginSrc) -ieq [System.IO.Path]::GetFullPath($pluginDest)) { + # Plugin published straight into its deploy home (see RynthVision) - + # nothing to copy, the publish already put the DLL in place. + Write-Host "Plugin $($plugin.DllName) already in place at $pluginTargetDir; skipping copy." + } else { + Copy-Item -LiteralPath $pluginSrc -Destination $pluginDest -Force + Write-Host "Plugin $($plugin.DllName) deployed to $pluginTargetDir" + } +} + +# Scoped pdb sweep: root + Runtime\ only. A $Destination-wide recurse walked +# the ~1.4 GB private AcClient copy on every deploy for nothing. +Get-ChildItem -Path $Destination -Filter *.pdb -File | Remove-Item -Force +Get-ChildItem -Path $runtimeDir -Recurse -Filter *.pdb -File | Remove-Item -Force + +if (-not $SkipLauncher) { + Write-Host "Launcher deployed to $Destination" +} Write-Host "Engine runtime deployed to $runtimeDir" diff --git a/scripts/Show-AcMemoryTrend.ps1 b/scripts/Show-AcMemoryTrend.ps1 new file mode 100644 index 0000000..aa5df80 --- /dev/null +++ b/scripts/Show-AcMemoryTrend.ps1 @@ -0,0 +1,344 @@ +# ============================================================================ +# Show-AcMemoryTrend.ps1 +# +# Live console-based memory monitor for acclient.exe. Complements the +# persistent CSV logger (Watch-AcMemory.ps1) by giving an in-the-moment +# trend view: current WorkingSet/Private/Virtual + handle/thread counts, +# deltas vs. session start, and computed growth rates (MB/min, MB/hour) +# with stable/growing/shrinking indicators. +# +# Two parallel rate windows are shown: +# * all-time — from the first sample we took to now (good for long +# averaged leak rates) +# * recent — last ~15 samples (~75s at 5s tick), so a process that +# leaked at startup then stabilised reads STABLE in this +# column while the all-time column still shows growth +# +# Zero impact on the running engine — pure OS query, no injection. +# +# This is a live VIEWER only — no file output. Persistence is owned by +# Watch-AcMemory.ps1 (5-min CSV samples to C:\Games\RynthCore\Logs\). +# Both can run in parallel against the same PID. +# +# Usage: +# .\Show-AcMemoryTrend.ps1 # auto-pick first acclient.exe, 5s refresh +# .\Show-AcMemoryTrend.ps1 -TargetPid 35456 # explicit PID +# .\Show-AcMemoryTrend.ps1 -IntervalSeconds 2 # tighter cadence +# .\Show-AcMemoryTrend.ps1 -HistorySize 120 # deeper recent-trend window +# +# acclient.exe is x86 — 2 GB user address space ceiling. The viewer +# surfaces a WARNING line at >1800 MB Virtual and a CRITICAL line at +# >1900 MB Virtual. +# +# Exit: Ctrl-C (clean), or auto-exits with a final summary when the +# watched process terminates. +# +# Accessibility: status indicators use text labels (STABLE / GROWING / +# SHRINKING) and ASCII arrows (->, ^, v). Colour is used as a +# supplement only and is never the sole signal. +# ============================================================================ + +[CmdletBinding()] +param( + [Alias('Pid')] + [int]$TargetPid = 0, + + [int]$IntervalSeconds = 5, + + # How many samples to keep in the rolling buffer. 60 @ 5s = 5 min. + [int]$HistorySize = 60, + + # How many of the most-recent samples define the "recent trend" slope. + [int]$RecentSampleCount = 15, + + # MB/min threshold below which a memory metric reads STABLE. + [double]$StableThresholdMbPerMin = 0.5, + + # Handles/hour threshold below which the handle metric reads STABLE. + [double]$StableThresholdHandlesPerHour = 50.0 +) + +# --------------------------------------------------------------------------- +# Resolve target PID — explicit param wins, else auto-pick the running client. +# --------------------------------------------------------------------------- +if ($TargetPid -eq 0) { + $candidates = @(Get-Process -Name acclient -ErrorAction SilentlyContinue) + if ($candidates.Count -eq 0) { + Write-Error 'No acclient.exe process found. Pass -TargetPid or launch AC first.' + exit 1 + } + if ($candidates.Count -gt 1) { + Write-Warning ("Multiple acclient.exe processes running ({0}). Picking PID {1}; pass -TargetPid to override." -f $candidates.Count, $candidates[0].Id) + Start-Sleep -Seconds 2 + } + $TargetPid = $candidates[0].Id +} + +$proc = Get-Process -Id $TargetPid -ErrorAction SilentlyContinue +if (-not $proc) { + Write-Error "No process found with PID $TargetPid." + exit 1 +} + +# StartTime can throw on protected processes; tolerate it. +$startTime = $null +try { $startTime = $proc.StartTime } catch { $startTime = (Get-Date) } + +# --------------------------------------------------------------------------- +# Sample state. Each sample is a PSCustomObject; we keep at most $HistorySize. +# --------------------------------------------------------------------------- +$history = New-Object System.Collections.Generic.List[object] +$firstSample = $null +$sessionStartWall = Get-Date + +function New-Sample { + param([System.Diagnostics.Process]$p) + + [pscustomobject]@{ + Time = Get-Date + WsMB = [double]($p.WorkingSet64 / 1MB) + PrivMB = [double]($p.PrivateMemorySize64 / 1MB) + VmMB = [double]($p.VirtualMemorySize64 / 1MB) + Handles = [int]$p.HandleCount + Threads = [int]$p.Threads.Count + } +} + +# Compute MB-per-minute slope between two samples. Returns 0 if window is +# too short to be meaningful. +function Get-RatePerMinute { + param($older, $newer, [string]$field) + + if (-not $older -or -not $newer) { return 0.0 } + $deltaMinutes = ($newer.Time - $older.Time).TotalMinutes + if ($deltaMinutes -le 0.01) { return 0.0 } + return ($newer.$field - $older.$field) / $deltaMinutes +} + +# Pick a text status label + an ASCII arrow given a slope and a stability +# threshold. The arrow + label are the load-bearing signals (the user is +# colorblind — colour, where used, is a supplement only). +function Get-Status { + param([double]$ratePerMinute, [double]$threshold) + + $abs = [math]::Abs($ratePerMinute) + if ($abs -lt $threshold) { + return [pscustomobject]@{ Label = 'STABLE '; Arrow = '->'; Color = 'Gray' } + } + if ($ratePerMinute -gt 0) { + return [pscustomobject]@{ Label = 'GROWING '; Arrow = '^^'; Color = 'Yellow' } + } + return [pscustomobject]@{ Label = 'SHRINKING'; Arrow = 'vv'; Color = 'Cyan' } +} + +# Format a delta with explicit sign so STABLE vs GROWING is visually obvious +# even without colour. "+12.3" / "-4.5" / " 0.0". +function Format-Delta { + param([double]$v, [int]$width = 7, [int]$decimals = 1) + + # Build the .NET composite-format string explicitly to dodge PS's + # "variable:scope" lookahead after a colon. e.g. width=7, decimals=1 -> + # "{0,7:+0.0;-0.0; 0.0}". + $dec = ('0' * $decimals) + $pos = if ($decimals -gt 0) { "+0.$dec" } else { '+0' } + $neg = if ($decimals -gt 0) { "-0.$dec" } else { '-0' } + $zero = if ($decimals -gt 0) { " 0.$dec" } else { ' 0' } + $fmt = '{0,' + $width + ':' + $pos + ';' + $neg + ';' + $zero + '}' + return ($fmt -f $v) +} + +# --------------------------------------------------------------------------- +# Console plumbing. We try in-place redraw via SetCursorPosition; if the host +# doesn't support it (ISE, some remote shells) we fall back to Clear-Host. +# Either way, redraws must tolerate a resized terminal — no fixed widths +# beyond the host's BufferWidth. +# --------------------------------------------------------------------------- +$supportsCursor = $true +try { + [void][Console]::CursorTop + [void][Console]::CursorLeft +} catch { + $supportsCursor = $false +} + +function Clear-Frame { + if ($supportsCursor) { + try { + [Console]::SetCursorPosition(0, 0) + # Overwrite the previously-drawn region with blanks. We pad to the + # current BufferWidth so the new frame doesn't leave stale chars + # at the right edge after a resize. + $w = [Console]::BufferWidth + $h = [Math]::Min(40, [Console]::BufferHeight - 1) + $blank = ' ' * ($w - 1) + for ($i = 0; $i -lt $h; $i++) { + [Console]::SetCursorPosition(0, $i) + [Console]::Write($blank) + } + [Console]::SetCursorPosition(0, 0) + } catch { + # Resize or other transient failure — fall back to Clear-Host. + Clear-Host + } + } else { + Clear-Host + } +} + +function Write-Line { + param([string]$text, [ConsoleColor]$Color = [ConsoleColor]::White) + + # Truncate to BufferWidth-1 so we never wrap mid-frame and corrupt + # subsequent SetCursorPosition writes. + try { + $maxLen = [Console]::BufferWidth - 1 + if ($maxLen -gt 0 -and $text.Length -gt $maxLen) { + $text = $text.Substring(0, $maxLen) + } + } catch { } + + $prevFg = $null + try { $prevFg = [Console]::ForegroundColor } catch { } + try { [Console]::ForegroundColor = $Color } catch { } + [Console]::WriteLine($text) + if ($null -ne $prevFg) { + try { [Console]::ForegroundColor = $prevFg } catch { } + } +} + +function Format-Uptime { + param([TimeSpan]$ts) + return ("{0:00}:{1:00}:{2:00}" -f [int]$ts.TotalHours, $ts.Minutes, $ts.Seconds) +} + +# --------------------------------------------------------------------------- +# Main loop. Sample, append to history, render frame, sleep. +# Ctrl-C handling: PowerShell raises a PipelineStoppedException out of +# Start-Sleep; the finally block prints a goodbye and restores cursor. +# --------------------------------------------------------------------------- +try { + Clear-Frame + Write-Line ("Starting Show-AcMemoryTrend for PID {0} (interval {1}s, history {2})..." -f $TargetPid, $IntervalSeconds, $HistorySize) + Start-Sleep -Milliseconds 250 + + while ($true) { + $p = Get-Process -Id $TargetPid -ErrorAction SilentlyContinue + if (-not $p) { + Clear-Frame + Write-Line ("PID {0} (acclient.exe) exited at {1}." -f $TargetPid, (Get-Date).ToString('HH:mm:ss')) Red + if ($firstSample -and $history.Count -gt 0) { + $last = $history[$history.Count - 1] + $sessionMin = ($last.Time - $firstSample.Time).TotalMinutes + if ($sessionMin -gt 0) { + $wsRate = ($last.WsMB - $firstSample.WsMB) / $sessionMin + $privRate = ($last.PrivMB - $firstSample.PrivMB) / $sessionMin + $vmRate = ($last.VmMB - $firstSample.VmMB) / $sessionMin + Write-Line ("Final summary : {0} samples over {1:0.0} min" -f $history.Count, $sessionMin) + Write-Line (" WS : last={0,5:0.0} MB delta={1} rate={2,7:+0.00;-0.00; 0.00} MB/min" -f $last.WsMB, (Format-Delta ($last.WsMB - $firstSample.WsMB)), $wsRate) + Write-Line (" Priv: last={0,5:0.0} MB delta={1} rate={2,7:+0.00;-0.00; 0.00} MB/min" -f $last.PrivMB, (Format-Delta ($last.PrivMB - $firstSample.PrivMB)), $privRate) + Write-Line (" VM : last={0,5:0.0} MB delta={1} rate={2,7:+0.00;-0.00; 0.00} MB/min" -f $last.VmMB, (Format-Delta ($last.VmMB - $firstSample.VmMB)), $vmRate) + } + } + exit 0 + } + + $sample = New-Sample -p $p + if (-not $firstSample) { $firstSample = $sample } + $history.Add($sample) + if ($history.Count -gt $HistorySize) { + $history.RemoveAt(0) + } + + # ---- Compute deltas + rates ---- + $deltaWs = $sample.WsMB - $firstSample.WsMB + $deltaPriv = $sample.PrivMB - $firstSample.PrivMB + $deltaVm = $sample.VmMB - $firstSample.VmMB + $deltaHnd = $sample.Handles - $firstSample.Handles + $deltaThr = $sample.Threads - $firstSample.Threads + + $allTimeWs = Get-RatePerMinute $firstSample $sample 'WsMB' + $allTimePriv = Get-RatePerMinute $firstSample $sample 'PrivMB' + $allTimeVm = Get-RatePerMinute $firstSample $sample 'VmMB' + $allTimeHnd = Get-RatePerMinute $firstSample $sample 'Handles' + + # Recent window: last N samples, oldest of those vs newest. + $recentOlder = $null + if ($history.Count -ge 2) { + $idx = [Math]::Max(0, $history.Count - $RecentSampleCount) + $recentOlder = $history[$idx] + } + $recentWs = Get-RatePerMinute $recentOlder $sample 'WsMB' + $recentPriv = Get-RatePerMinute $recentOlder $sample 'PrivMB' + $recentVm = Get-RatePerMinute $recentOlder $sample 'VmMB' + $recentHnd = Get-RatePerMinute $recentOlder $sample 'Handles' + + $statWs = Get-Status -ratePerMinute $recentWs -threshold $StableThresholdMbPerMin + $statPriv = Get-Status -ratePerMinute $recentPriv -threshold $StableThresholdMbPerMin + $statVm = Get-Status -ratePerMinute $recentVm -threshold $StableThresholdMbPerMin + # Handle threshold is given per-hour; convert to per-minute for the + # comparator so we share the same Get-Status helper. + $statHnd = Get-Status -ratePerMinute $recentHnd -threshold ($StableThresholdHandlesPerHour / 60.0) + + # ---- Render frame ---- + Clear-Frame + + $procUptime = if ($startTime) { (Get-Date) - $startTime } else { [TimeSpan]::Zero } + $sessionUptime = (Get-Date) - $sessionStartWall + + Write-Line "============================================================================" + Write-Line (" Show-AcMemoryTrend PID {0,-6} now {1}" -f $TargetPid, (Get-Date).ToString('HH:mm:ss')) + Write-Line (" proc started {0} proc uptime {1} viewer uptime {2}" -f ` + ($(if ($startTime) { $startTime.ToString('yyyy-MM-dd HH:mm:ss') } else { '?' })), ` + (Format-Uptime $procUptime), (Format-Uptime $sessionUptime)) + Write-Line (" samples {0}/{1} interval {2}s recent window = last {3} samples" -f ` + $history.Count, $HistorySize, $IntervalSeconds, [Math]::Min($RecentSampleCount, $history.Count)) + Write-Line "============================================================================" + Write-Line "" + Write-Line " METRIC CURRENT DELTA ALL-TIME RECENT (~75s)" + Write-Line " --------- ----------- ----------- -------------- ------------------------" + + # WorkingSet + Write-Line ((" {0,-9} {1,7:0.0} MB {2} MB {3,7:+0.00;-0.00; 0.00} MB/min {4,7:+0.00;-0.00; 0.00} MB/min {5} {6}" -f ` + 'WS', $sample.WsMB, (Format-Delta $deltaWs), $allTimeWs, $recentWs, $statWs.Arrow, $statWs.Label)) $statWs.Color + # Private + Write-Line ((" {0,-9} {1,7:0.0} MB {2} MB {3,7:+0.00;-0.00; 0.00} MB/min {4,7:+0.00;-0.00; 0.00} MB/min {5} {6}" -f ` + 'Private', $sample.PrivMB, (Format-Delta $deltaPriv), $allTimePriv, $recentPriv, $statPriv.Arrow, $statPriv.Label)) $statPriv.Color + # Virtual + Write-Line ((" {0,-9} {1,7:0.0} MB {2} MB {3,7:+0.00;-0.00; 0.00} MB/min {4,7:+0.00;-0.00; 0.00} MB/min {5} {6}" -f ` + 'Virtual', $sample.VmMB, (Format-Delta $deltaVm), $allTimeVm, $recentVm, $statVm.Arrow, $statVm.Label)) $statVm.Color + # Handles (count, not MB; rate column header still reads correctly) + Write-Line ((" {0,-9} {1,7} {2} {3,7:+0.00;-0.00; 0.00} /min {4,7:+0.00;-0.00; 0.00} /min {5} {6}" -f ` + 'Handles', $sample.Handles, (Format-Delta $deltaHnd 7 0), $allTimeHnd, $recentHnd, $statHnd.Arrow, $statHnd.Label)) $statHnd.Color + # Threads (informational, no slope label — usually noisy by design) + Write-Line (" {0,-9} {1,7} {2}" -f ` + 'Threads', $sample.Threads, (Format-Delta $deltaThr 7 0)) + + Write-Line "" + Write-Line (" Per-hour extrapolation (all-time): WS {0,7:+0.0;-0.0; 0.0} MB/hr Priv {1,7:+0.0;-0.0; 0.0} MB/hr VM {2,7:+0.0;-0.0; 0.0} MB/hr Handles {3,7:+0;-0; 0} /hr" -f ` + ($allTimeWs * 60), ($allTimePriv * 60), ($allTimeVm * 60), ($allTimeHnd * 60)) + Write-Line (" Per-hour extrapolation (recent) : WS {0,7:+0.0;-0.0; 0.0} MB/hr Priv {1,7:+0.0;-0.0; 0.0} MB/hr VM {2,7:+0.0;-0.0; 0.0} MB/hr Handles {3,7:+0;-0; 0} /hr" -f ` + ($recentWs * 60), ($recentPriv * 60), ($recentVm * 60), ($recentHnd * 60)) + + # ---- x86 2 GB ceiling warnings ---- + Write-Line "" + if ($sample.VmMB -ge 1900) { + Write-Line " !! CRITICAL: Virtual memory >= 1900 MB. acclient.exe x86 ceiling is ~2 GB. Crash imminent. !!" Red + Write-Line " !! CRITICAL: Save state / disconnect now before the address space is exhausted. !!" Red + } elseif ($sample.VmMB -ge 1800) { + Write-Line " ** WARNING: Virtual memory >= 1800 MB. Approaching x86 ~2 GB address space ceiling. **" Yellow + } + + Write-Line "" + Write-Line " Status legend: STABLE -> (within threshold) GROWING ^^ (rising) SHRINKING vv (falling)" + Write-Line (" Thresholds : memory < {0} MB/min = STABLE; handles < {1} /hr = STABLE" -f $StableThresholdMbPerMin, $StableThresholdHandlesPerHour) + Write-Line " Press Ctrl-C to exit. CSV persistence is handled separately by Watch-AcMemory.ps1." + + Start-Sleep -Seconds $IntervalSeconds + } +} finally { + # Make sure the cursor is left on a fresh line so the prompt isn't + # overwritten on whatever row the last frame happened to end on. + try { [Console]::ResetColor() } catch { } + Write-Host "" + Write-Host "Show-AcMemoryTrend exited." +} diff --git a/scripts/Watch-AcFreeze.ps1 b/scripts/Watch-AcFreeze.ps1 new file mode 100644 index 0000000..6289ce9 --- /dev/null +++ b/scripts/Watch-AcFreeze.ps1 @@ -0,0 +1,338 @@ +# ============================================================================ +# Watch-AcFreeze.ps1 +# +# Out-of-process freeze/wedge watchdog for RynthCore-injected acclient.exe. +# Tails the per-PID heartbeat log (C:\Games\RynthCore\Logs\RynthCore..log) +# and applies the SAME wedge heuristics the Avalonia launcher uses +# (MaybeRestartWedgedClients), so it can run with the launcher closed: +# +# * fps=0 with login=1 sustained >= WedgeHoldSeconds (render dead, alive) +# * main-thread queue qd > QueueWedgeDepth with login=1 (queue not draining) +# * combat-mode "stuck Ns" >= StanceStuckSeconds (item-action hard-lock) +# * heartbeat file silent > HbStaleSeconds while alive (engine died in-proc) +# +# On a CONFIRMED wedge it captures a diagnostic bundle, then (by default) kills +# and relaunches the same account so an unattended soak keeps running: +# +# 1. procdump -ma full dump -> Logs\freezes\freeze__.dmp +# 2. cdb "~*k" all-thread stacks -> ..._cdb.txt +# 3. symbolicate.py on the per-PID log -> ..._symbolicated.txt +# +# Zero impact on the running engine - pure OS query + log tail, no injection. +# +# Usage: +# .\Watch-AcFreeze.ps1 # auto-pick the RynthCore client +# .\Watch-AcFreeze.ps1 -TargetPid 12345 +# .\Watch-AcFreeze.ps1 -Account Buffi # account to use on relaunch +# .\Watch-AcFreeze.ps1 -Relaunch:$false # capture only, leave frozen +# .\Watch-AcFreeze.ps1 -Once # single evaluation pass (test) +# ============================================================================ + +[CmdletBinding()] +param( + [Alias('Pid')] + [int]$TargetPid = 0, + + # Account name/id passed to the injector on relaunch. If empty, read from + # the watched PID's launch_context_.json. + [string]$Account = '', + + [int]$IntervalSeconds = 5, + + # Sustained dwell before an fps=0 / queue wedge is acted on. Matches the + # launcher's WedgeRestartSeconds default. + [int]$WedgeHoldSeconds = 90, + + # Heartbeat file untouched this long while the process lives = engine dead. + [int]$HbStaleSeconds = 120, + + # Combat-mode "stuck Ns" threshold for the fps>0 item-action hard-lock. + [int]$StanceStuckSeconds = 300, + + # Main-thread queue depth that means AC stopped draining. + [int]$QueueWedgeDepth = 2000, + + [bool]$Relaunch = $true, + + # Stop relaunching after this many wedges (kill/relaunch loop breaker). + [int]$MaxRelaunch = 5, + + [string]$InjectorPath = 'C:\Projects\RynthCore\src\RynthCore.Injector\bin\Release\net10.0-windows\RynthCore.Injector.exe', + + [string]$LogDir = 'C:\Games\RynthCore\Logs', + + [string]$ToolsDir = 'C:\Games\RynthCore\tools', + + [string]$SymbolicatePs1 = 'C:\Projects\RynthCore\tools\symbolicate.ps1', + + # Do one evaluation pass and exit (for testing the detection logic). + [switch]$Once +) + +$ErrorActionPreference = 'Stop' +$DumpDir = Join-Path $LogDir 'freezes' +$WatchLog = Join-Path $LogDir 'freeze-watch.log' +$ProcDump = Join-Path $ToolsDir 'procdump.exe' +$Cdb = Join-Path $ToolsDir 'dbg_x86\cdb.exe' +New-Item -ItemType Directory -Path $DumpDir -Force | Out-Null + +# Heartbeat parse. Groups: 1=fps, 2=plug pump rate, 3=login(in-world), 4=qd. +# NOTE: fps is captured but NOT used as a wedge signal - see Test-Wedge. +$HbRegex = [regex]'hb #\d+ .*?fps=(\d+) .*?plug=(\d+)/s .*?login=(\d)(?:.*?qd=(\d+))?' +$StanceRegex = [regex]'ChangeCombatMode\([^)]*\) retry #\d+ \(stuck (\d+)s' +# The engine's own MainThreadHangWatchdog confirms a permanent main-thread wedge. +# It beats off the UseTime game tick (live even when EndScene/fps is not), so it +# works in every overlay config - the strongest cross-config signal. +$HangPermRegex = [regex]'still hung after' +$RecoverRegex = [regex]'MAIN THREAD RECOVERED' + +Add-Type -Namespace Native -Name Win -MemberDefinition @' +[System.Runtime.InteropServices.DllImport("user32.dll")] +public static extern bool IsIconic(System.IntPtr hWnd); +'@ + +function Write-WatchLog { + param([string]$Message, [string]$Level = 'INF') + $line = "[{0}] [{1}] {2}" -f (Get-Date -Format 'HH:mm:ss'), $Level, $Message + Write-Host $line + try { Add-Content -Path $WatchLog -Value $line -Encoding UTF8 } catch { } +} + +function Get-RynthCorePids { + # A RynthCore-injected acclient is the one with a recently-written + # per-PID log; Decal/Thwargle clients have no RynthCore..log. + $live = @{} + foreach ($p in @(Get-Process -Name acclient -ErrorAction SilentlyContinue)) { $live[$p.Id] = $true } + $result = @() + foreach ($f in Get-ChildItem (Join-Path $LogDir 'RynthCore.*.log') -ErrorAction SilentlyContinue) { + if ($f.Name -match '^RynthCore\.(\d+)\.log$') { + $candidatePid = [int]$Matches[1] + if ($live.ContainsKey($candidatePid) -and ((Get-Date) - $f.LastWriteTime).TotalSeconds -lt 30) { + $result += $candidatePid + } + } + } + return $result +} + +function Resolve-TargetPid { + if ($TargetPid -ne 0) { return $TargetPid } + $found = @(Get-RynthCorePids) + if ($found.Count -eq 0) { return 0 } + if ($found.Count -gt 1) { + Write-WatchLog ("Multiple RynthCore clients ({0}); picking {1}. Pass -TargetPid to override." -f ($found -join ', '), $found[0]) 'WRN' + } + return $found[0] +} + +function Get-AccountForPid { + param([int]$ProcId) + if ($Account) { return $Account } + $ctx = Join-Path $env:APPDATA "RynthCore\launch_contexts\launch_context_$ProcId.json" + if (Test-Path $ctx) { + try { return (Get-Content $ctx -Raw | ConvertFrom-Json).AccountName } catch { } + } + return '' +} + +# Returns $null if healthy, else a reason string. $state is a hashtable used to +# track sustained-dwell start times across calls (per the launcher's logic). +function Test-Wedge { + param([int]$ProcId, [hashtable]$State) + + $proc = Get-Process -Id $ProcId -ErrorAction SilentlyContinue + if (-not $proc) { return $null } # gone, not wedged + + # Minimized windows can read fps=0 on healthy clients - exempt them. + try { + $h = $proc.MainWindowHandle + if ($h -ne [IntPtr]::Zero -and [Native.Win]::IsIconic($h)) { + $State.Remove('zeroSince'); return $null + } + } catch { } + + $logPath = Join-Path $LogDir "RynthCore.$ProcId.log" + $fi = Get-Item $logPath -ErrorAction SilentlyContinue + if (-not $fi) { $State.Remove('zeroSince'); return $null } + + if (((Get-Date) - $fi.LastWriteTime).TotalSeconds -gt $HbStaleSeconds) { + return ("engine heartbeat silent for >{0}s while process alive" -f $HbStaleSeconds) + } + + # Tail ~16KB (enough for the every-30s combat-stuck line). + $tail = '' + try { + $fs = [System.IO.File]::Open($logPath, 'Open', 'Read', 'ReadWrite, Delete') + try { + $want = [Math]::Min(16384, $fs.Length) + [void]$fs.Seek(-$want, 'End') + $buf = New-Object byte[] $want + $read = $fs.Read($buf, 0, $want) + $tail = [System.Text.Encoding]::UTF8.GetString($buf, 0, $read) + } finally { $fs.Close() } + } catch { return $null } + + # STRONGEST signal: the engine's own watchdog confirmed a permanent + # main-thread wedge. Act only on the "still hung" confirmation, and only if + # no later RECOVERED line (transient stalls self-recover). + $hangIdx = $tail.LastIndexOf('MAIN THREAD HANG DETECTED') + if ($hangIdx -ge 0) { + $after = $tail.Substring($hangIdx) + if ($HangPermRegex.IsMatch($after) -and -not $RecoverRegex.IsMatch($after)) { + return "in-process MainThreadHangWatchdog confirmed a permanent main-thread wedge" + } + } + + # Item-action hard-lock while the engine threads keep ticking. + $stanceStuck = 0 + foreach ($m in $StanceRegex.Matches($tail)) { + $s = [int]$m.Groups[1].Value + if ($s -gt $stanceStuck) { $stanceStuck = $s } + } + if ($stanceStuck -ge $StanceStuckSeconds) { + return ("combat-mode stuck {0}s with login=1 (item-action hard-lock, heartbeat alive)" -f $stanceStuck) + } + + $hb = $HbRegex.Matches($tail) + if ($hb.Count -eq 0) { $State.Remove('zeroSince'); return $null } + $last = $hb[$hb.Count - 1] + $fps = [int]$last.Groups[1].Value + $plug = [int]$last.Groups[2].Value + $inWorld = $last.Groups[3].Value -eq '1' + $qd = if ($last.Groups[4].Success) { [int]$last.Groups[4].Value } else { 0 } + + # Minimized clients were already exempted above (they throttle fps on their + # own), so fps=0 here = a VISIBLE in-world client that stopped rendering + # (a healthy visible client renders tens of fps). plug=0 = plugin pump dead. + if (-not $inWorld) { $State.Remove('zeroSince'); return $null } + + $reason = $null + if ($fps -eq 0) { $reason = "fps=0 with login=1 (render dead)" } + elseif ($plug -eq 0) { $reason = "plugin pump dead (plug=0/s) with login=1" } + elseif ($qd -gt $QueueWedgeDepth) { $reason = ("main-thread queue backing up (qd={0}, login=1)" -f $qd) } + + if (-not $reason) { $State.Remove('zeroSince'); return $null } + + if (-not $State.ContainsKey('zeroSince')) { + $State['zeroSince'] = Get-Date + Write-WatchLog ("Wedge candidate on PID {0} ({1}) - holding {2}s to confirm." -f $ProcId, $reason, $WedgeHoldSeconds) 'WRN' + return $null + } + $held = ((Get-Date) - $State['zeroSince']).TotalSeconds + if ($held -lt $WedgeHoldSeconds) { return $null } + + return ("{0} for >{1}s (heartbeat alive - AC main thread/pump wedged)" -f $reason, $WedgeHoldSeconds) +} + +function Invoke-FreezeCapture { + param([int]$ProcId, [string]$Reason) + $stamp = Get-Date -Format 'yyyyMMdd-HHmmss' + $base = Join-Path $DumpDir ("freeze_{0}_{1}" -f $ProcId, $stamp) + $dmp = "$base.dmp" + $cdbOut = "${base}_cdb.txt" + $symOut = "${base}_symbolicated.txt" + + Write-WatchLog ("FREEZE CONFIRMED pid={0} - {1}" -f $ProcId, $Reason) 'ERR' + Write-WatchLog ("Capturing bundle -> {0}.*" -f $base) + + # 1. Full dump. + if (Test-Path $ProcDump) { + try { + & $ProcDump -accepteula -ma $ProcId $dmp 2>&1 | Out-Null + if (Test-Path $dmp) { Write-WatchLog (" dump: {0} ({1} MB)" -f $dmp, [int]((Get-Item $dmp).Length/1MB)) } + else { Write-WatchLog " dump: procdump produced no file" 'WRN' } + } catch { Write-WatchLog (" dump FAILED: {0}" -f $_.Exception.Message) 'WRN' } + } else { Write-WatchLog (" procdump not found at {0}" -f $ProcDump) 'WRN' } + + # 2. All-thread native stacks from the dump (catches fps>0 locks the + # in-process watchdog never logged a stack for). + if ((Test-Path $Cdb) -and (Test-Path $dmp)) { + try { + & $Cdb -z $dmp -c "~*k; q" 2>&1 | Out-File -FilePath $cdbOut -Encoding UTF8 + Write-WatchLog (" cdb stacks: {0}" -f $cdbOut) + } catch { Write-WatchLog (" cdb FAILED: {0}" -f $_.Exception.Message) 'WRN' } + } + + # 3. Symbolicate the per-PID log (contains the in-process hang stack when + # the EndScene/UseTime watchdog fired). + $logPath = Join-Path $LogDir "RynthCore.$ProcId.log" + if ((Test-Path $SymbolicatePs1) -and (Test-Path $logPath)) { + try { + & powershell -NoProfile -ExecutionPolicy Bypass -File $SymbolicatePs1 $logPath -o $symOut --only-crash 2>&1 | Out-Null + if (Test-Path $symOut) { Write-WatchLog (" symbolicated: {0}" -f $symOut) } + } catch { Write-WatchLog (" symbolicate FAILED: {0}" -f $_.Exception.Message) 'WRN' } + } + + return $base +} + +function Invoke-Relaunch { + param([int]$DeadPid, [string]$Acct) + if (-not (Test-Path $InjectorPath)) { + Write-WatchLog ("Cannot relaunch - injector not found at {0}" -f $InjectorPath) 'ERR' + return 0 + } + if (-not $Acct) { + Write-WatchLog "Cannot relaunch - no account resolved (pass -Account)." 'ERR' + return 0 + } + try { Stop-Process -Id $DeadPid -Force -ErrorAction SilentlyContinue } catch { } + Write-WatchLog ("Relaunching account '{0}' via injector..." -f $Acct) + $out = & $InjectorPath --launch --account $Acct 2>&1 + $out | ForEach-Object { Write-WatchLog (" injector> {0}" -f $_) } + $m = ($out | Select-String -Pattern 'LAUNCHED_PID=(\d+)' | Select-Object -Last 1) + if ($m) { + $newPid = [int]$m.Matches[0].Groups[1].Value + Write-WatchLog ("Relaunched as PID {0}." -f $newPid) 'INF' + return $newPid + } + Write-WatchLog "Relaunch did not report a PID." 'WRN' + return 0 +} + +# -- Main --------------------------------------------------------------------- +$activePid = Resolve-TargetPid +if ($activePid -eq 0) { + Write-WatchLog "No RynthCore-injected acclient found. Launch one first (RynthCore.Injector.exe --launch)." 'ERR' + exit 1 +} +$acct = Get-AccountForPid -ProcId $activePid +Write-WatchLog ("Watching PID {0} (account='{1}', relaunch={2}, hold={3}s, interval={4}s)." -f $activePid, $acct, $Relaunch, $WedgeHoldSeconds, $IntervalSeconds) + +$state = @{} +$relaunchCount = 0 + +while ($true) { + $proc = Get-Process -Id $activePid -ErrorAction SilentlyContinue + if (-not $proc) { + Write-WatchLog ("PID {0} is gone." -f $activePid) 'WRN' + if ($Relaunch -and -not $Once -and $acct -and $relaunchCount -lt $MaxRelaunch) { + $relaunchCount++ + $newPid = Invoke-Relaunch -DeadPid $activePid -Acct $acct + if ($newPid -ne 0) { $activePid = $newPid; $state = @{}; Start-Sleep -Seconds 10; continue } + } + break + } + + $reason = Test-Wedge -ProcId $activePid -State $state + if ($reason) { + [void](Invoke-FreezeCapture -ProcId $activePid -Reason $reason) + $state = @{} + if ($Relaunch -and -not $Once) { + if ($relaunchCount -ge $MaxRelaunch) { + Write-WatchLog ("Hit MaxRelaunch ({0}) - leaving client and stopping." -f $MaxRelaunch) 'ERR' + break + } + $relaunchCount++ + $newPid = Invoke-Relaunch -DeadPid $activePid -Acct $acct + if ($newPid -ne 0) { $activePid = $newPid; Start-Sleep -Seconds 10; continue } + break + } else { + Write-WatchLog ("Relaunch disabled - leaving PID {0} frozen for inspection. Stopping." -f $activePid) 'INF' + break + } + } + + if ($Once) { Write-WatchLog ("Single pass complete - PID {0} healthy." -f $activePid); break } + Start-Sleep -Seconds $IntervalSeconds +} diff --git a/scripts/Watch-AcMemory.ps1 b/scripts/Watch-AcMemory.ps1 new file mode 100644 index 0000000..cc9ff5b --- /dev/null +++ b/scripts/Watch-AcMemory.ps1 @@ -0,0 +1,100 @@ +# ============================================================================ +# Watch-AcMemory.ps1 +# +# Polls acclient.exe's memory + handle metrics on an interval and appends +# them to a CSV under C:\Games\RynthCore\Logs\. Designed for long-running +# 24/7 bot sessions where we want to know: +# +# * is RynthCore (or AC itself) leaking? +# * if yes, how fast (MB/hour)? +# * does growth correlate with subsystem activity (loot on/off, mage cast +# cycles, travel into new cells)? +# +# Zero impact on the running engine — runs in a separate PowerShell host, +# pure OS query, no injection. +# +# Usage: +# .\Watch-AcMemory.ps1 # auto-pick first acclient.exe +# .\Watch-AcMemory.ps1 -Pid 35456 # explicit PID +# .\Watch-AcMemory.ps1 -IntervalSeconds 60 # tighter cadence +# .\Watch-AcMemory.ps1 -OutFile foo.csv # custom output path +# +# Exits when the watched process exits (clean or crash) so it's safe to +# start-and-forget; the CSV stays on disk for post-session analysis. +# ============================================================================ + +[CmdletBinding()] +param( + [Alias('Pid')] + [int]$TargetPid = 0, + + [int]$IntervalSeconds = 300, + + [string]$OutFile = $null +) + +# Resolve target PID — explicit param wins, else auto-pick the running acclient. +if ($TargetPid -eq 0) { + $candidates = @(Get-Process -Name acclient -ErrorAction SilentlyContinue) + if ($candidates.Count -eq 0) { + Write-Error 'No acclient.exe process found. Pass -TargetPid or launch AC first.' + exit 1 + } + if ($candidates.Count -gt 1) { + Write-Warning ("Multiple acclient.exe processes running ({0}). Picking PID {1}; pass -TargetPid to override." -f $candidates.Count, $candidates[0].Id) + } + $TargetPid = $candidates[0].Id +} + +# Verify the PID is alive before we commit to a CSV path. +$proc = Get-Process -Id $TargetPid -ErrorAction SilentlyContinue +if (-not $proc) { + Write-Error "No process found with PID $TargetPid." + exit 1 +} + +# Default output: timestamped per session so successive runs never overwrite. +if (-not $OutFile) { + $logsDir = 'C:\Games\RynthCore\Logs' + if (-not (Test-Path $logsDir)) { New-Item -ItemType Directory -Path $logsDir | Out-Null } + $stamp = (Get-Date -Format 'yyyyMMdd-HHmmss') + $OutFile = Join-Path $logsDir ("acclient-memory-pid{0}-{1}.csv" -f $TargetPid, $stamp) +} + +Write-Host "Watching acclient.exe PID $TargetPid" +Write-Host "Interval : $IntervalSeconds seconds" +Write-Host "Output : $OutFile" +Write-Host "Process start: $($proc.StartTime)" +Write-Host '' + +# Header. Append-only after this so a Ctrl-C resume preserves prior samples. +'Timestamp,PID,UptimeMinutes,WorkingSetMB,PrivateMB,VirtualMB,HandleCount,ThreadCount' | + Out-File -FilePath $OutFile -Encoding UTF8 + +$startTime = $proc.StartTime + +while ($true) { + $p = Get-Process -Id $TargetPid -ErrorAction SilentlyContinue + if (-not $p) { + Write-Host "PID $TargetPid exited. Final sample written. CSV: $OutFile" + break + } + + $now = Get-Date + $uptimeMin = [math]::Round(($now - $startTime).TotalMinutes, 2) + $wsMB = [int]($p.WorkingSet64 / 1MB) + $privMB = [int]($p.PrivateMemorySize64 / 1MB) + $vmMB = [int]($p.VirtualMemorySize64 / 1MB) + $handles = $p.HandleCount + $threads = $p.Threads.Count + + $row = "{0},{1},{2},{3},{4},{5},{6},{7}" -f ` + $now.ToString('s'), $TargetPid, $uptimeMin, $wsMB, $privMB, $vmMB, $handles, $threads + $row | Out-File -FilePath $OutFile -Append -Encoding UTF8 + + # Echo to console too so a watching terminal shows live trend. + Write-Host ("[{0}] up={1,7:0.00}min WS={2,5}MB Priv={3,5}MB Handles={4,5} Threads={5,3}" -f ` + $now.ToString('HH:mm:ss'), $uptimeMin, $wsMB, $privMB, $handles, $threads) + + Start-Sleep -Seconds $IntervalSeconds +} diff --git a/spikes/WglDxInterop/D3D9.cs b/spikes/WglDxInterop/D3D9.cs new file mode 100644 index 0000000..a966861 --- /dev/null +++ b/spikes/WglDxInterop/D3D9.cs @@ -0,0 +1,369 @@ +// Plain D3D9 device + render-target texture. Mimics AC's setup: Direct3DCreate9 +// (NOT Ex), SOFTWARE_VERTEXPROCESSING (matches what AC's actual device uses, per +// the engine's MultiClient hooks). The interop chain we're testing in this spike +// must work against a non-Ex device because that's what AC ships. + +using System; +using System.Runtime.InteropServices; + +namespace WglDxInterop; + +internal sealed unsafe class D3D9Host : IDisposable +{ + public const uint D3D_SDK_VERSION = 32; + public const uint D3DDEVTYPE_HAL = 1; + public const uint D3DCREATE_FPU_PRESERVE = 0x00000002; + public const uint D3DCREATE_MULTITHREADED = 0x00000004; + public const uint D3DCREATE_SOFTWARE_VERTEXPROCESSING = 0x00000020; + public const uint D3DFMT_UNKNOWN = 0; + public const uint D3DFMT_A8R8G8B8 = 21; + public const uint D3DSWAPEFFECT_DISCARD = 1; + public const uint D3DPOOL_DEFAULT = 0; + public const uint D3DUSAGE_RENDERTARGET = 0x00000001; + public const uint D3DFVF_XYZRHW = 0x004; + public const uint D3DFVF_TEX1 = 0x100; + public const uint D3DPT_TRIANGLESTRIP = 5; + + public const uint D3DRS_LIGHTING = 137; + public const uint D3DRS_ZENABLE = 7; + public const uint D3DRS_CULLMODE = 22; + public const uint D3DCULL_NONE = 1; + + public const uint D3DTSS_COLOROP = 1; + public const uint D3DTSS_COLORARG1 = 2; + public const uint D3DTSS_ALPHAOP = 4; + public const uint D3DTSS_ALPHAARG1 = 5; + public const uint D3DTOP_SELECTARG1 = 2; + public const uint D3DTA_TEXTURE = 2; + public const uint D3DSAMP_MINFILTER = 5; + public const uint D3DSAMP_MAGFILTER = 6; + public const uint D3DTEXF_LINEAR = 2; + + [StructLayout(LayoutKind.Sequential)] + public struct D3DPRESENT_PARAMETERS + { + public uint BackBufferWidth; + public uint BackBufferHeight; + public uint BackBufferFormat; + public uint BackBufferCount; + public uint MultiSampleType; + public uint MultiSampleQuality; + public uint SwapEffect; + public IntPtr hDeviceWindow; + public int Windowed; + public int EnableAutoDepthStencil; + public uint AutoDepthStencilFormat; + public uint Flags; + public uint FullScreen_RefreshRateInHz; + public uint PresentationInterval; + } + + [StructLayout(LayoutKind.Sequential)] + public struct D3DVIEWPORT9 { public uint X, Y, Width, Height; public float MinZ, MaxZ; } + + [DllImport("d3d9.dll")] + public static extern IntPtr Direct3DCreate9(uint sdkVersion); + + [DllImport("d3d9.dll")] + public static extern int Direct3DCreate9Ex(uint sdkVersion, out IntPtr pD3D9Ex); + + public const int IDirect3D9Ex_CreateDeviceEx = 20; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate int CreateDeviceExD(IntPtr pD3D9Ex, uint adapter, uint deviceType, IntPtr hFocusWindow, + uint behaviorFlags, IntPtr pPresentationParameters, IntPtr pFullscreenDisplayMode, + out IntPtr ppReturnedDeviceInterface); + + // Vtable indexes for IDirect3D9 / IDirect3DDevice9 / IDirect3DTexture9. + // Cross-checked against the engine's D3D9VTable.cs at investigation time. + public const int IDirect3D9_CreateDevice = 16; + public const int IDirect3D9_Release = 2; + public const int IDirect3DDevice9_TestCooperativeLevel = 3; + public const int IDirect3DDevice9_Reset = 16; + public const int IDirect3DDevice9_Present = 17; + public const int IDirect3DDevice9_BeginScene = 41; + public const int IDirect3DDevice9_EndScene = 42; + public const int IDirect3DDevice9_Clear = 43; + public const int IDirect3DDevice9_SetRenderState = 57; + public const int IDirect3DDevice9_SetTextureStageState = 60; + public const int IDirect3DDevice9_SetSamplerState = 62; + public const int IDirect3DDevice9_SetTexture = 65; + public const int IDirect3DDevice9_SetFVF = 89; + public const int IDirect3DDevice9_DrawPrimitiveUP = 83; + public const int IDirect3DDevice9_CreateTexture = 23; + public const int IDirect3DDevice9_Release = 2; + public const int IDirect3DTexture9_Release = 2; + public const int IDirect3DTexture9_GetSurfaceLevel = 18; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate int CreateDeviceD(IntPtr pD3D9, uint adapter, uint deviceType, IntPtr hFocusWindow, + uint behaviorFlags, IntPtr pPresentationParameters, out IntPtr ppReturnedDeviceInterface); + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate uint ReleaseD(IntPtr pObj); + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate int CreateTextureD(IntPtr dev, uint w, uint h, uint levels, uint usage, + uint fmt, uint pool, out IntPtr ppTex, IntPtr pSharedHandle); + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate int PresentD(IntPtr dev, IntPtr pSourceRect, IntPtr pDestRect, + IntPtr hDestWindowOverride, IntPtr pDirtyRegion); + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate int ClearD(IntPtr dev, uint count, IntPtr pRects, uint flags, uint color, float z, uint stencil); + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate int BeginSceneD(IntPtr dev); + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate int EndSceneD(IntPtr dev); + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate int SetRenderStateD(IntPtr dev, uint state, uint value); + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate int SetTextureStageStateD(IntPtr dev, uint stage, uint type, uint value); + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate int SetSamplerStateD(IntPtr dev, uint stage, uint type, uint value); + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate int SetTextureD(IntPtr dev, uint stage, IntPtr pTex); + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate int SetFVFD(IntPtr dev, uint fvf); + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate int DrawPrimitiveUPD(IntPtr dev, uint primType, uint primCount, IntPtr pVtxData, uint vtxStride); + + public IntPtr Direct3D9 { get; private set; } + public IntPtr Device { get; private set; } + public uint AdapterIndex { get; private set; } + public bool IsEx { get; private set; } + + private CreateTextureD? _createTexture; + private PresentD? _present; + private ClearD? _clear; + private BeginSceneD? _beginScene; + private EndSceneD? _endScene; + private SetRenderStateD? _setRenderState; + private SetTextureStageStateD? _setTexStageState; + private SetSamplerStateD? _setSamplerState; + private SetTextureD? _setTexture; + private SetFVFD? _setFvf; + private DrawPrimitiveUPD? _drawPrimitiveUp; + + public void Initialize(IntPtr hwnd, int width, int height) => InitializeInternal(hwnd, width, height, useEx: false); + + /// D3D9Ex variant — required if WGL_NV_DX_interop needs shared-handle textures. + public void InitializeEx(IntPtr hwnd, int width, int height) => InitializeInternal(hwnd, width, height, useEx: true); + + private void InitializeInternal(IntPtr hwnd, int width, int height, bool useEx) + { + if (useEx) + { + int hrEx = Direct3DCreate9Ex(D3D_SDK_VERSION, out IntPtr pEx); + if (hrEx < 0 || pEx == IntPtr.Zero) + throw new InvalidOperationException($"Direct3DCreate9Ex failed, HRESULT=0x{hrEx:X8}."); + Direct3D9 = pEx; + IsEx = true; + } + else + { + Direct3D9 = Direct3DCreate9(D3D_SDK_VERSION); + if (Direct3D9 == IntPtr.Zero) + throw new InvalidOperationException("Direct3DCreate9 returned null. Ensure d3d9.dll is present."); + IsEx = false; + } + + var pp = new D3DPRESENT_PARAMETERS + { + BackBufferWidth = (uint)width, + BackBufferHeight = (uint)height, + BackBufferFormat = D3DFMT_A8R8G8B8, + BackBufferCount = 1, + SwapEffect = D3DSWAPEFFECT_DISCARD, + hDeviceWindow = hwnd, + Windowed = 1, + EnableAutoDepthStencil = 0, + AutoDepthStencilFormat = D3DFMT_UNKNOWN, + PresentationInterval = 0 + }; + + IntPtr pPP = Marshal.AllocHGlobal(Marshal.SizeOf()); + try + { + Marshal.StructureToPtr(pp, pPP, false); + + IntPtr d3dVtable = Marshal.ReadIntPtr(Direct3D9); + + int hr; + IntPtr device; + if (useEx) + { + var createDeviceEx = Marshal.GetDelegateForFunctionPointer( + Marshal.ReadIntPtr(d3dVtable, IDirect3D9Ex_CreateDeviceEx * IntPtr.Size)); + hr = createDeviceEx( + Direct3D9, 0, D3DDEVTYPE_HAL, hwnd, + 0x00000040u /*D3DCREATE_HARDWARE_VERTEXPROCESSING*/ | D3DCREATE_FPU_PRESERVE, + pPP, IntPtr.Zero, out device); + } + else + { + var createDevice = Marshal.GetDelegateForFunctionPointer( + Marshal.ReadIntPtr(d3dVtable, IDirect3D9_CreateDevice * IntPtr.Size)); + hr = createDevice( + Direct3D9, 0, D3DDEVTYPE_HAL, hwnd, + 0x00000040u /*D3DCREATE_HARDWARE_VERTEXPROCESSING*/ | D3DCREATE_FPU_PRESERVE, + pPP, out device); + } + + if (hr < 0 || device == IntPtr.Zero) + throw new InvalidOperationException($"CreateDevice{(useEx ? "Ex" : "")} failed, HRESULT=0x{hr:X8}"); + + Device = device; + AdapterIndex = 0; + + CacheDeviceMethods(); + } + finally + { + Marshal.FreeHGlobal(pPP); + } + } + + /// + /// D3D9Ex-only: create an RT texture with a non-null pSharedHandle slot so + /// the driver allocates a kernel-mode shared handle for the texture. The + /// returned shared handle can then be passed to wglDXSetResourceShareHandleNV. + /// On a non-Ex device this returns a texture but the share handle stays null. + /// + public IntPtr CreateRenderTargetTextureWithSharedHandle(int width, int height, out IntPtr sharedHandle) + { + if (_createTexture == null) throw new InvalidOperationException("Device not initialized."); + sharedHandle = IntPtr.Zero; + + // CreateTexture's pSharedHandle is in/out: caller passes a pointer to + // a HANDLE; on D3D9Ex devices the driver writes the kernel handle there. + unsafe + { + IntPtr handle = IntPtr.Zero; + int hr = _createTexture(Device, (uint)width, (uint)height, 1, + D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, + out IntPtr tex, new IntPtr(&handle)); + if (hr < 0 || tex == IntPtr.Zero) + throw new InvalidOperationException($"CreateTexture(RT shared {width}x{height}) failed, HRESULT=0x{hr:X8}"); + sharedHandle = handle; + return tex; + } + } + + private void CacheDeviceMethods() + { + IntPtr vtbl = Marshal.ReadIntPtr(Device); + _createTexture = GetMethod(vtbl, IDirect3DDevice9_CreateTexture); + _present = GetMethod(vtbl, IDirect3DDevice9_Present); + _clear = GetMethod(vtbl, IDirect3DDevice9_Clear); + _beginScene = GetMethod(vtbl, IDirect3DDevice9_BeginScene); + _endScene = GetMethod(vtbl, IDirect3DDevice9_EndScene); + _setRenderState = GetMethod(vtbl, IDirect3DDevice9_SetRenderState); + _setTexStageState = GetMethod(vtbl, IDirect3DDevice9_SetTextureStageState); + _setSamplerState = GetMethod(vtbl, IDirect3DDevice9_SetSamplerState); + _setTexture = GetMethod(vtbl, IDirect3DDevice9_SetTexture); + _setFvf = GetMethod(vtbl, IDirect3DDevice9_SetFVF); + _drawPrimitiveUp = GetMethod(vtbl, IDirect3DDevice9_DrawPrimitiveUP); + } + + private static T GetMethod(IntPtr vtable, int index) where T : Delegate + => Marshal.GetDelegateForFunctionPointer(Marshal.ReadIntPtr(vtable, index * IntPtr.Size)); + + /// Creates an A8R8G8B8 texture in D3DPOOL_DEFAULT with RENDERTARGET usage. + public IntPtr CreateRenderTargetTexture(int width, int height) + { + if (_createTexture == null) throw new InvalidOperationException("Device not initialized."); + int hr = _createTexture(Device, (uint)width, (uint)height, 1, + D3DUSAGE_RENDERTARGET, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, + out IntPtr tex, IntPtr.Zero); + if (hr < 0 || tex == IntPtr.Zero) + throw new InvalidOperationException($"CreateTexture(RT {width}x{height}) failed, HRESULT=0x{hr:X8}"); + return tex; + } + + /// Returns IDirect3DSurface9* for level 0 of the texture. Caller releases. + public IntPtr GetTextureSurfaceLevel0(IntPtr texture) + { + if (texture == IntPtr.Zero) return IntPtr.Zero; + IntPtr texVtbl = Marshal.ReadIntPtr(texture); + var getSurfaceLevel = Marshal.GetDelegateForFunctionPointer( + Marshal.ReadIntPtr(texVtbl, IDirect3DTexture9_GetSurfaceLevel * IntPtr.Size)); + int hr = getSurfaceLevel(texture, 0, out IntPtr surface); + if (hr < 0 || surface == IntPtr.Zero) + throw new InvalidOperationException($"GetSurfaceLevel(0) failed, HRESULT=0x{hr:X8}"); + return surface; + } + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + private delegate int GetSurfaceLevelD(IntPtr tex, uint level, out IntPtr ppSurface); + + public void ReleaseObject(IntPtr pObj) + { + if (pObj == IntPtr.Zero) return; + IntPtr vtbl = Marshal.ReadIntPtr(pObj); + var release = Marshal.GetDelegateForFunctionPointer( + Marshal.ReadIntPtr(vtbl, 2 * IntPtr.Size)); + release(pObj); + } + + // ─── Frame helpers ──────────────────────────────────────────────────── + public int Clear(uint argbColor) => _clear!(Device, 0, IntPtr.Zero, 0x00000001 /*D3DCLEAR_TARGET*/, argbColor, 1.0f, 0); + public int BeginScene() => _beginScene!(Device); + public int EndScene() => _endScene!(Device); + public int Present() => _present!(Device, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); + + public void DrawTexturedQuad(IntPtr texture, float W, float H) + { + // Pre-transformed XYZRHW vertices; matches OverlayTextureRenderer.cs in the engine. + // -0.5 offset is the D3D9 half-texel rule. + Span verts = stackalloc QuadVertex[4]; + verts[0] = new QuadVertex { X = -0.5f, Y = -0.5f, Z = 0, RHW = 1, U = 0, V = 0 }; + verts[1] = new QuadVertex { X = W - 0.5f, Y = -0.5f, Z = 0, RHW = 1, U = 1, V = 0 }; + verts[2] = new QuadVertex { X = -0.5f, Y = H - 0.5f, Z = 0, RHW = 1, U = 0, V = 1 }; + verts[3] = new QuadVertex { X = W - 0.5f, Y = H - 0.5f, Z = 0, RHW = 1, U = 1, V = 1 }; + + _setRenderState!(Device, D3DRS_LIGHTING, 0); + _setRenderState!(Device, D3DRS_ZENABLE, 0); + _setRenderState!(Device, D3DRS_CULLMODE, D3DCULL_NONE); + + _setTexStageState!(Device, 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1); + _setTexStageState!(Device, 0, D3DTSS_COLORARG1, D3DTA_TEXTURE); + _setTexStageState!(Device, 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1); + _setTexStageState!(Device, 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE); + _setSamplerState!(Device, 0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); + _setSamplerState!(Device, 0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); + + _setFvf!(Device, D3DFVF_XYZRHW | D3DFVF_TEX1); + _setTexture!(Device, 0, texture); + + fixed (QuadVertex* p = verts) + { + _drawPrimitiveUp!(Device, D3DPT_TRIANGLESTRIP, 2, (IntPtr)p, (uint)sizeof(QuadVertex)); + } + + _setTexture!(Device, 0, IntPtr.Zero); + } + + public void Dispose() + { + if (Device != IntPtr.Zero) + { + ReleaseObject(Device); + Device = IntPtr.Zero; + } + if (Direct3D9 != IntPtr.Zero) + { + ReleaseObject(Direct3D9); + Direct3D9 = IntPtr.Zero; + } + } + + [StructLayout(LayoutKind.Sequential)] + private struct QuadVertex + { + public float X, Y, Z, RHW; + public float U, V; + } +} diff --git a/spikes/WglDxInterop/Gl.cs b/spikes/WglDxInterop/Gl.cs new file mode 100644 index 0000000..99b4783 --- /dev/null +++ b/spikes/WglDxInterop/Gl.cs @@ -0,0 +1,201 @@ +// OpenGL + WGL bootstrap. We need a real GL context (not ANGLE) to access the +// WGL_NV_DX_interop2 extension, which is the whole point of the spike. +// +// Sequence: +// 1. Create a hidden Win32 window and DC. +// 2. ChoosePixelFormat / SetPixelFormat with a basic 32-bit RGBA / no depth format. +// 3. wglCreateContext → fallback GL 1.x context, just to bootstrap. +// 4. wglMakeCurrent the fallback so we can call wglGetProcAddress for ARB extensions. +// 5. (Optional) wglCreateContextAttribsARB to upgrade to 3.3 core. Skia GL needs this. +// 6. Load WGL_NV_DX_interop2 entry points via wglGetProcAddress. +// 7. Confirm the extension string contains "WGL_NV_DX_interop2". +// +// Spike question A7 (multi-adapter): on a laptop with dGPU+iGPU, the default GL +// context may be on the wrong adapter. Confirming this requires hardware to test. +// For now, the spike just uses whatever the default DC ends up on. + +using System; +using System.Runtime.InteropServices; +using System.Text; + +namespace WglDxInterop; + +internal static unsafe class Gl +{ + // ─── opengl32.dll core ──────────────────────────────────────────────── + [DllImport("opengl32.dll")] public static extern IntPtr wglCreateContext(IntPtr hdc); + [DllImport("opengl32.dll")] public static extern bool wglMakeCurrent(IntPtr hdc, IntPtr hglrc); + [DllImport("opengl32.dll")] public static extern bool wglDeleteContext(IntPtr hglrc); + [DllImport("opengl32.dll")] public static extern IntPtr wglGetCurrentContext(); + [DllImport("opengl32.dll")] public static extern IntPtr wglGetCurrentDC(); + [DllImport("opengl32.dll", CharSet = CharSet.Ansi)] public static extern IntPtr wglGetProcAddress(string name); + + // ─── core GL we need (resolved via wglGetProcAddress for >=GL 1.5 / ARB) ── + [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void glClearD(uint mask); + [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void glClearColorD(float r, float g, float b, float a); + [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void glViewportD(int x, int y, int w, int h); + [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void glFinishD(); + [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void glFlushD(); + [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate IntPtr glGetStringD(uint name); + [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void glGenTexturesD(int n, uint* textures); + [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void glDeleteTexturesD(int n, uint* textures); + [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void glBindTextureD(uint target, uint texture); + + // FBO entry points (GL 3.0 / ARB_framebuffer_object) + [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void glGenFramebuffersD(int n, uint* framebuffers); + [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void glDeleteFramebuffersD(int n, uint* framebuffers); + [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void glBindFramebufferD(uint target, uint framebuffer); + [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate void glFramebufferTexture2DD(uint target, uint attachment, uint textarget, uint texture, int level); + [UnmanagedFunctionPointer(CallingConvention.StdCall)] public delegate uint glCheckFramebufferStatusD(uint target); + + // GL constants we need + public const uint GL_VENDOR = 0x1F00; + public const uint GL_RENDERER = 0x1F01; + public const uint GL_VERSION = 0x1F02; + public const uint GL_EXTENSIONS = 0x1F03; + public const uint GL_TEXTURE_2D = 0x0DE1; + public const uint GL_TEXTURE_RECTANGLE = 0x84F5; + public const uint GL_FRAMEBUFFER = 0x8D40; + public const uint GL_COLOR_ATTACHMENT0 = 0x8CE0; + public const uint GL_FRAMEBUFFER_COMPLETE = 0x8CD5; + public const uint GL_COLOR_BUFFER_BIT = 0x00004000; + + // ─── WGL_ARB_extensions_string + WGL_ARB_create_context ──────────────── + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate IntPtr wglGetExtensionsStringARBD(IntPtr hdc); + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate IntPtr wglCreateContextAttribsARBD(IntPtr hdc, IntPtr hShareContext, int* attribList); + + public const int WGL_CONTEXT_MAJOR_VERSION_ARB = 0x2091; + public const int WGL_CONTEXT_MINOR_VERSION_ARB = 0x2092; + public const int WGL_CONTEXT_PROFILE_MASK_ARB = 0x9126; + public const int WGL_CONTEXT_CORE_PROFILE_BIT_ARB = 0x00000001; + + // ─── WGL_NV_DX_interop2 ──────────────────────────────────────────────── + // Function signatures from the registered extension spec at + // https://registry.khronos.org/OpenGL/extensions/NV/WGL_NV_DX_interop.txt + // (DX_interop2 is the same surface; v2 just lifts the D3D11 restriction.) + public const uint WGL_ACCESS_READ_ONLY_NV = 0x00000000; + public const uint WGL_ACCESS_READ_WRITE_NV = 0x00000001; + public const uint WGL_ACCESS_WRITE_DISCARD_NV = 0x00000002; + + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate IntPtr wglDXOpenDeviceNVD(IntPtr dxDevice); + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate bool wglDXCloseDeviceNVD(IntPtr hDevice); + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate IntPtr wglDXRegisterObjectNVD(IntPtr hDevice, IntPtr dxObject, uint name, uint type, uint access); + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate bool wglDXUnregisterObjectNVD(IntPtr hDevice, IntPtr hObject); + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate bool wglDXLockObjectsNVD(IntPtr hDevice, int count, IntPtr* objects); + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate bool wglDXUnlockObjectsNVD(IntPtr hDevice, int count, IntPtr* objects); + [UnmanagedFunctionPointer(CallingConvention.StdCall)] + public delegate bool wglDXSetResourceShareHandleNVD(IntPtr dxObject, IntPtr shareHandle); + + public sealed class Bindings + { + public glClearD glClear = null!; + public glClearColorD glClearColor = null!; + public glViewportD glViewport = null!; + public glFinishD glFinish = null!; + public glFlushD glFlush = null!; + public glGetStringD glGetString = null!; + public glGenTexturesD glGenTextures = null!; + public glDeleteTexturesD glDeleteTextures = null!; + public glBindTextureD glBindTexture = null!; + + public glGenFramebuffersD glGenFramebuffers = null!; + public glDeleteFramebuffersD glDeleteFramebuffers = null!; + public glBindFramebufferD glBindFramebuffer = null!; + public glFramebufferTexture2DD glFramebufferTexture2D = null!; + public glCheckFramebufferStatusD glCheckFramebufferStatus = null!; + + public wglDXOpenDeviceNVD wglDXOpenDeviceNV = null!; + public wglDXCloseDeviceNVD wglDXCloseDeviceNV = null!; + public wglDXRegisterObjectNVD wglDXRegisterObjectNV = null!; + public wglDXUnregisterObjectNVD wglDXUnregisterObjectNV = null!; + public wglDXLockObjectsNVD wglDXLockObjectsNV = null!; + public wglDXUnlockObjectsNVD wglDXUnlockObjectsNV = null!; + public wglDXSetResourceShareHandleNVD? wglDXSetResourceShareHandleNV; // optional; only needed for D3D9 shared HANDLE textures + + public bool Loaded; + } + + public static T Resolve(string name) where T : Delegate + { + IntPtr proc = wglGetProcAddress(name); + if (proc == IntPtr.Zero || proc == new IntPtr(1) || proc == new IntPtr(2) || proc == new IntPtr(3) || proc == new IntPtr(-1)) + { + // wglGetProcAddress returns 1/2/3/-1 on some drivers when the name isn't a real ICD entry; fall through to opengl32 itself. + IntPtr opengl32 = Win32.LoadLibraryA("opengl32.dll"); + proc = Win32.GetProcAddress(opengl32, name); + } + if (proc == IntPtr.Zero) + throw new InvalidOperationException($"GL proc not found: {name}"); + return Marshal.GetDelegateForFunctionPointer(proc); + } + + public static T? TryResolve(string name) where T : Delegate + { + IntPtr proc = wglGetProcAddress(name); + if (proc == IntPtr.Zero || proc == new IntPtr(1) || proc == new IntPtr(2) || proc == new IntPtr(3) || proc == new IntPtr(-1)) + { + IntPtr opengl32 = Win32.LoadLibraryA("opengl32.dll"); + proc = Win32.GetProcAddress(opengl32, name); + } + if (proc == IntPtr.Zero) return null; + return Marshal.GetDelegateForFunctionPointer(proc); + } + + public static Bindings LoadAll() + { + var b = new Bindings + { + glClear = Resolve("glClear"), + glClearColor = Resolve("glClearColor"), + glViewport = Resolve("glViewport"), + glFinish = Resolve("glFinish"), + glFlush = Resolve("glFlush"), + glGetString = Resolve("glGetString"), + glGenTextures = Resolve("glGenTextures"), + glDeleteTextures = Resolve("glDeleteTextures"), + glBindTexture = Resolve("glBindTexture"), + + glGenFramebuffers = Resolve("glGenFramebuffers"), + glDeleteFramebuffers = Resolve("glDeleteFramebuffers"), + glBindFramebuffer = Resolve("glBindFramebuffer"), + glFramebufferTexture2D = Resolve("glFramebufferTexture2D"), + glCheckFramebufferStatus = Resolve("glCheckFramebufferStatus"), + + wglDXOpenDeviceNV = Resolve("wglDXOpenDeviceNV"), + wglDXCloseDeviceNV = Resolve("wglDXCloseDeviceNV"), + wglDXRegisterObjectNV = Resolve("wglDXRegisterObjectNV"), + wglDXUnregisterObjectNV = Resolve("wglDXUnregisterObjectNV"), + wglDXLockObjectsNV = Resolve("wglDXLockObjectsNV"), + wglDXUnlockObjectsNV = Resolve("wglDXUnlockObjectsNV"), + + wglDXSetResourceShareHandleNV = TryResolve("wglDXSetResourceShareHandleNV"), + + Loaded = true, + }; + + return b; + } + + public static string GetGlString(Bindings b, uint name) + { + IntPtr p = b.glGetString(name); + return p == IntPtr.Zero ? "" : Marshal.PtrToStringAnsi(p) ?? ""; + } + + public static string GetWglExtensionsString(IntPtr hdc) + { + var fn = TryResolve("wglGetExtensionsStringARB"); + if (fn == null) return string.Empty; + IntPtr p = fn(hdc); + return p == IntPtr.Zero ? string.Empty : Marshal.PtrToStringAnsi(p) ?? string.Empty; + } +} diff --git a/spikes/WglDxInterop/InteropTexture.cs b/spikes/WglDxInterop/InteropTexture.cs new file mode 100644 index 0000000..fe12cca --- /dev/null +++ b/spikes/WglDxInterop/InteropTexture.cs @@ -0,0 +1,165 @@ +// One unit of "shared" texture state: +// - A D3D9 RT texture on AC's-emulated device (POOL_DEFAULT, USAGE_RENDERTARGET). +// - A GL texture name + FBO bound to that texture via wglDXRegisterObjectNV. +// - The interop handle returned by Register that we Lock/Unlock per frame. +// +// The Phase A spike doesn't render Skia yet — it just clears the FBO to a known +// animated color so we can verify the chain visually. Skia integration is +// straight after the chain is proven. + +using System; +using System.Runtime.InteropServices; + +namespace WglDxInterop; + +internal sealed unsafe class InteropTexture : IDisposable +{ + public IntPtr D3D9Texture { get; private set; } + public IntPtr D3D9Surface { get; private set; } + public uint GlTexture { get; private set; } + public uint GlFramebuffer { get; private set; } + public IntPtr WglObject { get; private set; } + public int Width { get; } + public int Height { get; } + + private readonly Gl.Bindings _gl; + private readonly D3D9Host _d3d; + private readonly IntPtr _wglDevice; + + public InteropTexture(Gl.Bindings gl, D3D9Host d3d, IntPtr wglDevice, int width, int height) + { + _gl = gl; + _d3d = d3d; + _wglDevice = wglDevice; + Width = width; + Height = height; + + // Step 1 — D3D9 RT texture. If Ex, get a shared handle too. + IntPtr sharedHandle = IntPtr.Zero; + if (d3d.IsEx) + { + D3D9Texture = d3d.CreateRenderTargetTextureWithSharedHandle(width, height, out sharedHandle); + Console.WriteLine($"[spike] D3D9Ex RT created with sharedHandle=0x{sharedHandle:X8}"); + } + else + { + D3D9Texture = d3d.CreateRenderTargetTexture(width, height); + } + + // Step 1b — WGL_NV_DX_interop on D3D9 only supports SURFACES, not the + // ID3DTexture wrapper. Get the level-0 IDirect3DSurface9 and register + // that. The GL side still sees it as GL_TEXTURE_2D. + D3D9Surface = d3d.GetTextureSurfaceLevel0(D3D9Texture); + + // Step 1c — If we have a shared handle, register it BEFORE Register. + // This is required by NVIDIA's implementation when the resource has + // a shared handle, even when the GL context's interop device matches + // the D3D device that created the resource. + if (sharedHandle != IntPtr.Zero && gl.wglDXSetResourceShareHandleNV != null) + { + bool setOk = gl.wglDXSetResourceShareHandleNV(D3D9Surface, sharedHandle); + Console.WriteLine($"[spike] wglDXSetResourceShareHandleNV(surface) → {setOk}"); + if (!setOk) + throw new InvalidOperationException($"wglDXSetResourceShareHandleNV failed (LastError=0x{Marshal.GetLastWin32Error():X})."); + } + + // Step 2 — GL texture name to receive the binding. + uint glTex = 0; + gl.glGenTextures(1, &glTex); + if (glTex == 0) throw new InvalidOperationException("glGenTextures returned 0."); + GlTexture = glTex; + + // Step 3 — Register the D3D9 surface as a GL texture under the GL context. + // Try a sequence of (target, access) combinations and (texture vs surface) until one + // succeeds. NVIDIA's WGL_NV_DX_interop driver has historically been picky about + // which D3D9 source types it accepts. + var attempts = new[] { + (Label: "surface, GL_TEXTURE_2D, WRITE_DISCARD", Obj: D3D9Surface, Type: Gl.GL_TEXTURE_2D, Access: Gl.WGL_ACCESS_WRITE_DISCARD_NV), + (Label: "surface, GL_TEXTURE_2D, READ_WRITE", Obj: D3D9Surface, Type: Gl.GL_TEXTURE_2D, Access: Gl.WGL_ACCESS_READ_WRITE_NV), + (Label: "surface, GL_TEXTURE_RECTANGLE, RW", Obj: D3D9Surface, Type: Gl.GL_TEXTURE_RECTANGLE, Access: Gl.WGL_ACCESS_READ_WRITE_NV), + (Label: "texture, GL_TEXTURE_2D, WRITE_DISCARD", Obj: D3D9Texture, Type: Gl.GL_TEXTURE_2D, Access: Gl.WGL_ACCESS_WRITE_DISCARD_NV), + (Label: "texture, GL_TEXTURE_2D, READ_WRITE", Obj: D3D9Texture, Type: Gl.GL_TEXTURE_2D, Access: Gl.WGL_ACCESS_READ_WRITE_NV), + }; + + IntPtr wglObj = IntPtr.Zero; + string lastFail = ""; + foreach (var a in attempts) + { + wglObj = gl.wglDXRegisterObjectNV(_wglDevice, a.Obj, GlTexture, a.Type, a.Access); + if (wglObj != IntPtr.Zero) + { + Console.WriteLine($"[spike] wglDXRegisterObjectNV SUCCESS via: {a.Label}"); + break; + } + lastFail = $"{a.Label} → LastError=0x{Marshal.GetLastWin32Error():X}"; + Console.WriteLine($"[spike] wglDXRegisterObjectNV FAIL via: {lastFail}"); + } + + if (wglObj == IntPtr.Zero) + throw new InvalidOperationException($"wglDXRegisterObjectNV failed in all variants. Last: {lastFail}"); + + WglObject = wglObj; + + // Step 4 — Build an FBO with the GL texture as color attachment 0. + // FBO setup is done while the texture is NOT locked (legal per spec; the + // attachment binding is a GL state operation that doesn't touch contents). + // The first lock is the point at which GL can actually clear the texture. + uint fbo = 0; + gl.glGenFramebuffers(1, &fbo); + GlFramebuffer = fbo; + + gl.glBindFramebuffer(Gl.GL_FRAMEBUFFER, fbo); + gl.glFramebufferTexture2D(Gl.GL_FRAMEBUFFER, Gl.GL_COLOR_ATTACHMENT0, Gl.GL_TEXTURE_2D, GlTexture, 0); + + uint status = gl.glCheckFramebufferStatus(Gl.GL_FRAMEBUFFER); + gl.glBindFramebuffer(Gl.GL_FRAMEBUFFER, 0); + + if (status != Gl.GL_FRAMEBUFFER_COMPLETE) + throw new InvalidOperationException($"FBO incomplete after attaching interop texture, status=0x{status:X}."); + } + + /// Lock the D3D9 texture so the GL context has exclusive write access. + public bool Lock() + { + IntPtr h = WglObject; + return _gl.wglDXLockObjectsNV(_wglDevice, 1, &h); + } + + /// Release the D3D9 texture back to D3D9. After this, AC's render thread can sample. + public bool Unlock() + { + IntPtr h = WglObject; + return _gl.wglDXUnlockObjectsNV(_wglDevice, 1, &h); + } + + public void Dispose() + { + if (WglObject != IntPtr.Zero) + { + _gl.wglDXUnregisterObjectNV(_wglDevice, WglObject); + WglObject = IntPtr.Zero; + } + if (GlFramebuffer != 0) + { + uint fbo = GlFramebuffer; + _gl.glDeleteFramebuffers(1, &fbo); + GlFramebuffer = 0; + } + if (GlTexture != 0) + { + uint tex = GlTexture; + _gl.glDeleteTextures(1, &tex); + GlTexture = 0; + } + if (D3D9Surface != IntPtr.Zero) + { + _d3d.ReleaseObject(D3D9Surface); + D3D9Surface = IntPtr.Zero; + } + if (D3D9Texture != IntPtr.Zero) + { + _d3d.ReleaseObject(D3D9Texture); + D3D9Texture = IntPtr.Zero; + } + } +} diff --git a/spikes/WglDxInterop/Program.cs b/spikes/WglDxInterop/Program.cs new file mode 100644 index 0000000..725f782 --- /dev/null +++ b/spikes/WglDxInterop/Program.cs @@ -0,0 +1,337 @@ +// Phase A spike — WGL_NV_DX_interop2 architectural test. +// +// What it does end-to-end: +// 1. Open a normal Win32 window and create a plain D3D9 device on it. +// (Direct3DCreate9, NOT Ex — exactly what AC ships.) +// 2. Create a 'producer' window+DC and bring up a real OpenGL 3.3 core context. +// 3. Confirm WGL_NV_DX_interop2 is in the WGL extensions string. +// (Spike A8 — driver coverage. Hard-fail with a clear log if missing.) +// 4. Open the D3D9 device for interop and register a D3DUSAGE_RENDERTARGET +// texture under it as a GL texture. +// 5. Per frame: +// - Lock the texture for GL. +// - Bind FBO, set viewport, clear to an animated color (proves the GL +// path is actually writing into the D3D9 resource). +// - Unlock. +// - Use the D3D9 texture in a normal D3D9 fullscreen quad to the window. +// 6. Log frame timing every second so spike A3 (lock/unlock cost) gets data. +// +// This is intentionally Skia-free for the first cut. Skia layers on top +// trivially once the chain works (replace the glClearColor with a Skia render +// into the same FBO). Proving the chain first means a Skia rendering bug is +// disambiguated from an interop bug. + +using System; +using System.Diagnostics; +using System.Runtime.InteropServices; + +namespace WglDxInterop; + +internal static unsafe class Program +{ + private const int WindowWidth = 1280; + private const int WindowHeight = 720; + + private static IntPtr _hwnd; + private static bool _quitRequested; + + // Holding the WndProc delegate alive for the lifetime of the window — + // RegisterClassExW stores a function pointer; if the delegate is GC'd + // we get a callback into freed memory. + private static Win32.WndProcDelegate? _wndProc; + + [STAThread] + public static int Main(string[] args) + { + Console.WriteLine("[spike] WGL_NV_DX_interop2 architectural test"); + + try + { + CreateMainWindow(); + + // Spike branch — `--ex` flag selects D3D9Ex+shared-handle path so we can + // empirically test whether WGL_NV_DX_interop2 needs Ex's shared handles. + // Default is plain D3D9 to mirror AC's reality. + bool useEx = Array.IndexOf(args, "--ex") >= 0; + + using var d3d = new D3D9Host(); + if (useEx) d3d.InitializeEx(_hwnd, WindowWidth, WindowHeight); + else d3d.Initialize(_hwnd, WindowWidth, WindowHeight); + Console.WriteLine($"[spike] D3D9{(d3d.IsEx ? "Ex" : "")} device created on adapter {d3d.AdapterIndex}."); + + // GL context lives on the SAME thread as the message loop and D3D9. + // For the engine integration, the GL context will live on Avalonia's + // STA thread; here on the spike main thread is fine. + // + // Use a SEPARATE hidden window for the GL context so the GL default + // framebuffer doesn't compete with the D3D9 swap chain on the visible + // window. NVIDIA's WGL_NV_DX_interop layer is documented as needing + // this isolation for D3D9 sources. + IntPtr glHwnd = CreateHiddenGlWindow(); + IntPtr glContext = CreateGlContext(glHwnd, out IntPtr hdcUsed); + if (glContext == IntPtr.Zero) + return Fail("Could not create OpenGL context."); + + string wglExt = Gl.GetWglExtensionsString(hdcUsed); + Console.WriteLine($"[spike] WGL extensions: {wglExt.Length} chars."); + bool hasInterop2 = wglExt.Contains("WGL_NV_DX_interop2"); + bool hasInterop1 = wglExt.Contains("WGL_NV_DX_interop"); + Console.WriteLine($"[spike] WGL_NV_DX_interop = {hasInterop1}, WGL_NV_DX_interop2 = {hasInterop2}"); + if (!hasInterop2 && !hasInterop1) + return Fail("Driver does not advertise WGL_NV_DX_interop. Spike cannot run on this hardware."); + + var gl = Gl.LoadAll(); + Console.WriteLine($"[spike] GL_VENDOR = {Gl.GetGlString(gl, Gl.GL_VENDOR)}"); + Console.WriteLine($"[spike] GL_RENDERER = {Gl.GetGlString(gl, Gl.GL_RENDERER)}"); + Console.WriteLine($"[spike] GL_VERSION = {Gl.GetGlString(gl, Gl.GL_VERSION)}"); + + IntPtr wglDevice = gl.wglDXOpenDeviceNV(d3d.Device); + if (wglDevice == IntPtr.Zero) + return Fail($"wglDXOpenDeviceNV failed (LastError=0x{Marshal.GetLastWin32Error():X})."); + Console.WriteLine($"[spike] wglDXOpenDeviceNV → 0x{wglDevice:X}"); + + using var tex = new InteropTexture(gl, d3d, wglDevice, WindowWidth, WindowHeight); + Console.WriteLine($"[spike] Registered D3D9 RT 0x{tex.D3D9Texture:X} as GL tex {tex.GlTexture}, FBO {tex.GlFramebuffer}, wglObj 0x{tex.WglObject:X}."); + + RunRenderLoop(d3d, gl, tex); + + // Teardown order matters — Unregister + CloseDeviceNV before D3D9 release. + gl.wglDXCloseDeviceNV(wglDevice); + Gl.wglMakeCurrent(IntPtr.Zero, IntPtr.Zero); + Gl.wglDeleteContext(glContext); + + Console.WriteLine("[spike] Clean exit."); + return 0; + } + catch (Exception ex) + { + return Fail($"Unhandled: {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}"); + } + } + + private static int Fail(string msg) + { + Console.Error.WriteLine($"[spike] FAILED: {msg}"); + return 1; + } + + // ─── Window ─────────────────────────────────────────────────────────── + private static void CreateMainWindow() + { + _wndProc = StaticWndProc; + IntPtr wndProcPtr = Marshal.GetFunctionPointerForDelegate(_wndProc); + + var wc = new Win32.WNDCLASSEXW + { + cbSize = (uint)Marshal.SizeOf(), + style = 0, + lpfnWndProc = wndProcPtr, + hInstance = Win32.GetModuleHandleW(null), + hCursor = IntPtr.Zero, + hbrBackground = IntPtr.Zero, + lpszMenuName = IntPtr.Zero, + lpszClassName = Marshal.StringToHGlobalUni("WglDxInteropSpike"), + }; + + ushort atom = Win32.RegisterClassExW(ref wc); + if (atom == 0) + throw new InvalidOperationException($"RegisterClassExW failed: {Marshal.GetLastWin32Error()}"); + + _hwnd = Win32.CreateWindowExW( + 0, "WglDxInteropSpike", "WGL_NV_DX_interop2 spike", + Win32.WS_OVERLAPPEDWINDOW | Win32.WS_VISIBLE, + Win32.CW_USEDEFAULT, Win32.CW_USEDEFAULT, WindowWidth, WindowHeight, + IntPtr.Zero, IntPtr.Zero, Win32.GetModuleHandleW(null), IntPtr.Zero); + + if (_hwnd == IntPtr.Zero) + throw new InvalidOperationException($"CreateWindowExW failed: {Marshal.GetLastWin32Error()}"); + + Win32.ShowWindow(_hwnd, Win32.SW_SHOW); + } + + private static IntPtr StaticWndProc(IntPtr hwnd, uint msg, IntPtr wParam, IntPtr lParam) + { + switch (msg) + { + case Win32.WM_CLOSE: + _quitRequested = true; + Win32.PostQuitMessage(0); + return IntPtr.Zero; + case Win32.WM_DESTROY: + Win32.PostQuitMessage(0); + return IntPtr.Zero; + } + return Win32.DefWindowProcW(hwnd, msg, wParam, lParam); + } + + private static IntPtr CreateHiddenGlWindow() + { + IntPtr hwnd = Win32.CreateWindowExW( + 0, "WglDxInteropSpike", "GL helper", + Win32.WS_POPUP, + 0, 0, 16, 16, + IntPtr.Zero, IntPtr.Zero, Win32.GetModuleHandleW(null), IntPtr.Zero); + if (hwnd == IntPtr.Zero) + throw new InvalidOperationException($"GL helper CreateWindowExW failed: {Marshal.GetLastWin32Error()}"); + return hwnd; + } + + // ─── GL context bootstrap ───────────────────────────────────────────── + private static IntPtr CreateGlContext(IntPtr hwnd, out IntPtr hdcOut) + { + IntPtr hdc = Win32.GetDC(hwnd); + if (hdc == IntPtr.Zero) { hdcOut = IntPtr.Zero; return IntPtr.Zero; } + + var pfd = new Win32.PIXELFORMATDESCRIPTOR + { + nSize = (ushort)Marshal.SizeOf(), + nVersion = 1, + dwFlags = (uint)(Win32.PFD_DRAW_TO_WINDOW | Win32.PFD_SUPPORT_OPENGL | Win32.PFD_DOUBLEBUFFER), + iPixelType = Win32.PFD_TYPE_RGBA, + cColorBits = 32, + cAlphaBits = 8, + cDepthBits = 0, + cStencilBits = 0, + iLayerType = Win32.PFD_MAIN_PLANE, + }; + + int format = Win32.ChoosePixelFormat(hdc, ref pfd); + if (format == 0) { hdcOut = IntPtr.Zero; return IntPtr.Zero; } + if (!Win32.SetPixelFormat(hdc, format, ref pfd)) { hdcOut = IntPtr.Zero; return IntPtr.Zero; } + + IntPtr glrc = Gl.wglCreateContext(hdc); + if (glrc == IntPtr.Zero) { hdcOut = IntPtr.Zero; return IntPtr.Zero; } + if (!Gl.wglMakeCurrent(hdc, glrc)) { hdcOut = IntPtr.Zero; return IntPtr.Zero; } + + // Try to upgrade to GL 3.3 core via wglCreateContextAttribsARB. + // If unavailable (very old driver) the fallback 1.x context is used — + // that may or may not have FBO support. Fail gracefully. + var createAttribs = Gl.TryResolve("wglCreateContextAttribsARB"); + if (createAttribs != null) + { + int* attribs = stackalloc int[] + { + Gl.WGL_CONTEXT_MAJOR_VERSION_ARB, 3, + Gl.WGL_CONTEXT_MINOR_VERSION_ARB, 3, + Gl.WGL_CONTEXT_PROFILE_MASK_ARB, Gl.WGL_CONTEXT_CORE_PROFILE_BIT_ARB, + 0, + }; + + IntPtr coreCtx = createAttribs(hdc, IntPtr.Zero, attribs); + if (coreCtx != IntPtr.Zero) + { + Gl.wglMakeCurrent(IntPtr.Zero, IntPtr.Zero); + Gl.wglDeleteContext(glrc); + glrc = coreCtx; + Gl.wglMakeCurrent(hdc, glrc); + Console.WriteLine("[spike] Upgraded to GL 3.3 core context."); + } + else + { + Console.WriteLine("[spike] wglCreateContextAttribsARB returned null — staying on legacy context."); + } + } + else + { + Console.WriteLine("[spike] wglCreateContextAttribsARB not available — staying on legacy context."); + } + + hdcOut = hdc; + return glrc; + } + + // ─── Render loop ────────────────────────────────────────────────────── + private static void RunRenderLoop(D3D9Host d3d, Gl.Bindings gl, InteropTexture tex) + { + var sw = Stopwatch.StartNew(); + long frameStartTicks; + long lockTotalTicks = 0; + long unlockTotalTicks = 0; + long unlockMaxTicks = 0; + int frame = 0; + long secondAnchor = sw.ElapsedTicks; + int framesThisSecond = 0; + + while (!_quitRequested) + { + // Drain Win32 messages. + while (Win32.PeekMessageW(out Win32.MSG msg, IntPtr.Zero, 0, 0, Win32.PM_REMOVE)) + { + if (msg.message == Win32.WM_QUIT) + { + _quitRequested = true; + break; + } + Win32.TranslateMessage(ref msg); + Win32.DispatchMessageW(ref msg); + } + if (_quitRequested) break; + + frameStartTicks = sw.ElapsedTicks; + + // ── GL phase: lock → render to FBO → unlock ── + long lockStart = sw.ElapsedTicks; + if (!tex.Lock()) + { + Console.Error.WriteLine($"[spike] wglDXLockObjectsNV failed at frame {frame}."); + break; + } + long lockEnd = sw.ElapsedTicks; + lockTotalTicks += (lockEnd - lockStart); + + // Bind the interop FBO and clear to an animated color so it's visually + // obvious the GL path is writing into the D3D9 texture. Swizzle is + // intentional: we want to see whether glClearColor's RGBA is sampled + // as RGBA or as BGRA when drawn through D3D9's quad shader path. + // Spike question A2 — color format mapping. + float t = (frame % 600) / 600.0f; + float r = (float)(0.5 + 0.5 * Math.Sin(t * 2 * Math.PI)); + float g = (float)(0.5 + 0.5 * Math.Sin(t * 2 * Math.PI + 2.0)); + float b = (float)(0.5 + 0.5 * Math.Sin(t * 2 * Math.PI + 4.0)); + + gl.glBindFramebuffer(Gl.GL_FRAMEBUFFER, tex.GlFramebuffer); + gl.glViewport(0, 0, tex.Width, tex.Height); + gl.glClearColor(r, g, b, 1.0f); + gl.glClear(Gl.GL_COLOR_BUFFER_BIT); + gl.glBindFramebuffer(Gl.GL_FRAMEBUFFER, 0); + gl.glFlush(); + + long unlockStart = sw.ElapsedTicks; + if (!tex.Unlock()) + { + Console.Error.WriteLine($"[spike] wglDXUnlockObjectsNV failed at frame {frame}."); + break; + } + long unlockEnd = sw.ElapsedTicks; + long unlockTicks = unlockEnd - unlockStart; + unlockTotalTicks += unlockTicks; + if (unlockTicks > unlockMaxTicks) unlockMaxTicks = unlockTicks; + + // ── D3D9 phase: render the texture as a fullscreen quad ── + d3d.Clear(0xFF000000); // opaque black, so quad alpha is visible + d3d.BeginScene(); + d3d.DrawTexturedQuad(tex.D3D9Texture, WindowWidth, WindowHeight); + d3d.EndScene(); + d3d.Present(); + + frame++; + framesThisSecond++; + + // Per-second telemetry — feeds Spike question A3. + long now = sw.ElapsedTicks; + if ((now - secondAnchor) >= Stopwatch.Frequency) + { + double avgLockMs = (lockTotalTicks / (double)Stopwatch.Frequency) * 1000.0 / Math.Max(framesThisSecond, 1); + double avgUnlockMs = (unlockTotalTicks / (double)Stopwatch.Frequency) * 1000.0 / Math.Max(framesThisSecond, 1); + double maxUnlockMs = (unlockMaxTicks / (double)Stopwatch.Frequency) * 1000.0; + Console.WriteLine($"[spike] frame={frame} fps={framesThisSecond} lock={avgLockMs:F3}ms avgUnlock={avgUnlockMs:F3}ms maxUnlock={maxUnlockMs:F3}ms"); + + lockTotalTicks = 0; + unlockTotalTicks = 0; + unlockMaxTicks = 0; + framesThisSecond = 0; + secondAnchor = now; + } + } + } +} diff --git a/spikes/WglDxInterop/WglDxInterop.csproj b/spikes/WglDxInterop/WglDxInterop.csproj new file mode 100644 index 0000000..6662384 --- /dev/null +++ b/spikes/WglDxInterop/WglDxInterop.csproj @@ -0,0 +1,24 @@ + + + + Exe + net10.0-windows + x86 + win-x86 + x86 + enable + true + WglDxInterop + WglDxInterop + false + false + + + + + diff --git a/spikes/WglDxInterop/Win32.cs b/spikes/WglDxInterop/Win32.cs new file mode 100644 index 0000000..ffa016b --- /dev/null +++ b/spikes/WglDxInterop/Win32.cs @@ -0,0 +1,141 @@ +// Win32 P/Invoke surface for the spike. Kept narrow — we only need window +// creation, a message loop, DC management, and pixel-format setup. All the +// GL-side P/Invokes live in Gl.cs; D3D9 P/Invokes live in D3D9.cs. + +using System; +using System.Runtime.InteropServices; + +namespace WglDxInterop; + +internal static unsafe class Win32 +{ + public const int WS_OVERLAPPEDWINDOW = 0x00CF0000; + public const int WS_VISIBLE = 0x10000000; + public const int WS_POPUP = unchecked((int)0x80000000); + public const int CW_USEDEFAULT = unchecked((int)0x80000000); + public const int SW_SHOW = 5; + + public const uint WM_DESTROY = 0x0002; + public const uint WM_QUIT = 0x0012; + public const uint WM_SIZE = 0x0005; + public const uint WM_CLOSE = 0x0010; + public const uint WM_PAINT = 0x000F; + + public const int PFD_DRAW_TO_WINDOW = 0x00000004; + public const int PFD_SUPPORT_OPENGL = 0x00000020; + public const int PFD_DOUBLEBUFFER = 0x00000001; + public const int PFD_TYPE_RGBA = 0; + public const byte PFD_MAIN_PLANE = 0; + + [StructLayout(LayoutKind.Sequential)] + public struct PIXELFORMATDESCRIPTOR + { + public ushort nSize; + public ushort nVersion; + public uint dwFlags; + public byte iPixelType; + public byte cColorBits; + public byte cRedBits, cRedShift; + public byte cGreenBits, cGreenShift; + public byte cBlueBits, cBlueShift; + public byte cAlphaBits, cAlphaShift; + public byte cAccumBits, cAccumRedBits, cAccumGreenBits, cAccumBlueBits, cAccumAlphaBits; + public byte cDepthBits, cStencilBits, cAuxBuffers; + public byte iLayerType; + public byte bReserved; + public uint dwLayerMask, dwVisibleMask, dwDamageMask; + } + + [StructLayout(LayoutKind.Sequential)] + public struct MSG + { + public IntPtr hwnd; + public uint message; + public IntPtr wParam; + public IntPtr lParam; + public uint time; + public int ptX; + public int ptY; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + public struct WNDCLASSEXW + { + public uint cbSize; + public uint style; + public IntPtr lpfnWndProc; + public int cbClsExtra; + public int cbWndExtra; + public IntPtr hInstance; + public IntPtr hIcon; + public IntPtr hCursor; + public IntPtr hbrBackground; + public IntPtr lpszMenuName; + public IntPtr lpszClassName; + public IntPtr hIconSm; + } + + public delegate IntPtr WndProcDelegate(IntPtr hwnd, uint msg, IntPtr wParam, IntPtr lParam); + + [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + public static extern ushort RegisterClassExW(ref WNDCLASSEXW wc); + + [DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + public static extern IntPtr CreateWindowExW( + int dwExStyle, string lpClassName, string lpWindowName, int dwStyle, + int x, int y, int nWidth, int nHeight, + IntPtr hWndParent, IntPtr hMenu, IntPtr hInstance, IntPtr lpParam); + + [DllImport("user32.dll", CharSet = CharSet.Unicode)] + public static extern IntPtr DefWindowProcW(IntPtr hwnd, uint msg, IntPtr wParam, IntPtr lParam); + + [DllImport("user32.dll", SetLastError = true)] + public static extern bool DestroyWindow(IntPtr hwnd); + + [DllImport("user32.dll")] + public static extern bool ShowWindow(IntPtr hwnd, int nCmdShow); + + [DllImport("user32.dll")] + public static extern IntPtr GetDC(IntPtr hwnd); + + [DllImport("user32.dll")] + public static extern int ReleaseDC(IntPtr hwnd, IntPtr hdc); + + [DllImport("user32.dll")] + public static extern bool PeekMessageW(out MSG msg, IntPtr hwnd, uint wMsgFilterMin, uint wMsgFilterMax, uint wRemoveMsg); + + [DllImport("user32.dll")] + public static extern bool TranslateMessage(ref MSG msg); + + [DllImport("user32.dll", CharSet = CharSet.Unicode)] + public static extern IntPtr DispatchMessageW(ref MSG msg); + + [DllImport("user32.dll")] + public static extern void PostQuitMessage(int nExitCode); + + [DllImport("user32.dll")] + public static extern bool GetClientRect(IntPtr hwnd, out RECT lpRect); + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] + public static extern IntPtr GetModuleHandleW(string? lpModuleName); + + [DllImport("kernel32.dll", CharSet = CharSet.Ansi)] + public static extern IntPtr LoadLibraryA(string lpFileName); + + [DllImport("kernel32.dll", CharSet = CharSet.Ansi)] + public static extern IntPtr GetProcAddress(IntPtr hModule, string procName); + + [DllImport("gdi32.dll")] + public static extern int ChoosePixelFormat(IntPtr hdc, ref PIXELFORMATDESCRIPTOR ppfd); + + [DllImport("gdi32.dll")] + public static extern bool SetPixelFormat(IntPtr hdc, int format, ref PIXELFORMATDESCRIPTOR ppfd); + + [DllImport("gdi32.dll")] + public static extern bool SwapBuffers(IntPtr hdc); + + [StructLayout(LayoutKind.Sequential)] + public struct RECT { public int Left, Top, Right, Bottom; } + + public const uint PM_REMOVE = 0x0001; +} diff --git a/spikes/WglDxInterop/findings.md b/spikes/WglDxInterop/findings.md new file mode 100644 index 0000000..cdbcdba --- /dev/null +++ b/spikes/WglDxInterop/findings.md @@ -0,0 +1,76 @@ +# Phase A spike findings — WGL_NV_DX_interop2 for D3D9 sources + +**Verdict: NOT VIABLE on this hardware.** + +The technique recommended in `wgl-interop-plan.md` does not work for D3D9 sources on the user's machine. This invalidates the plan as written. **Stop and pivot before any engine code changes.** + +--- + +## What was tested + +Hardware: NVIDIA GeForce GTX 1650 SUPER, driver 560.94 (current). + +OS: Windows 10 Pro 19045. + +GL: 3.3.0 NVIDIA 560.94, real ICD context (not Microsoft GDI fallback). 809 chars of WGL extension string, both `WGL_NV_DX_interop` and `WGL_NV_DX_interop2` advertised as supported. + +Spike code: `C:\Projects\RynthCore\spikes\WglDxInterop\` — ~600 LOC, builds clean as managed x86. + +## Results + +`wglDXOpenDeviceNV(deviceHandle)`: **succeeds** for both plain D3D9 and D3D9Ex. Returns a non-null handle. Already informative — the D3D device is recognized as a valid interop source. + +`wglDXSetResourceShareHandleNV(surface, sharedHandle)`: **succeeds** for D3D9Ex render-target textures created with a non-null `pSharedHandle` slot. + +`wglDXRegisterObjectNV(...)`: **fails (returns NULL)** in 10 distinct configurations: + +| Device | Source | Type | Access | Result | +|---|---|---|---|---| +| Plain D3D9 | IDirect3DSurface9 | GL_TEXTURE_2D | WRITE_DISCARD_NV | NULL (LastError 0xC007006E first call, 0x0 subsequent) | +| Plain D3D9 | IDirect3DSurface9 | GL_TEXTURE_2D | READ_WRITE_NV | NULL | +| Plain D3D9 | IDirect3DSurface9 | GL_TEXTURE_RECTANGLE | READ_WRITE_NV | NULL | +| Plain D3D9 | IDirect3DTexture9 | GL_TEXTURE_2D | WRITE_DISCARD_NV | NULL | +| Plain D3D9 | IDirect3DTexture9 | GL_TEXTURE_2D | READ_WRITE_NV | NULL | +| D3D9Ex (shared handle set) | IDirect3DSurface9 | GL_TEXTURE_2D | WRITE_DISCARD_NV | NULL | +| D3D9Ex (shared handle set) | IDirect3DSurface9 | GL_TEXTURE_2D | READ_WRITE_NV | NULL | +| D3D9Ex (shared handle set) | IDirect3DSurface9 | GL_TEXTURE_RECTANGLE | READ_WRITE_NV | NULL | +| D3D9Ex (shared handle set) | IDirect3DTexture9 | GL_TEXTURE_2D | WRITE_DISCARD_NV | NULL | +| D3D9Ex (shared handle set) | IDirect3DTexture9 | GL_TEXTURE_2D | READ_WRITE_NV | NULL | + +Other variables ruled out: +- `D3DCREATE_MULTITHREADED` flag: tested both on and off. Same failure either way. +- `D3DCREATE_HARDWARE_VERTEXPROCESSING` vs `_SOFTWARE_VERTEXPROCESSING`: tested both. Same failure. +- Shared focus window vs isolated hidden window for the GL context: tested both. Same failure. +- Texture format / dimensions: A8R8G8B8, 1280×720, D3DPOOL_DEFAULT, D3DUSAGE_RENDERTARGET — the canonical "supported" combination per spec. + +The `0xC007006E = HRESULT_FROM_WIN32(ERROR_INVALID_HANDLE)` on the very first call (subsequent calls leave LastError as 0, suggesting the driver doesn't reliably call `SetLastError`) is the only diagnostic NVIDIA's driver gives us. There is no way to query a more specific error. + +## Interpretation + +The published NV_DX_interop spec lists D3D9 surfaces as supported, but **NVIDIA's current driver implementation does not work for D3D9 sources** in the configurations a real-world overlay would need. This matches scattered third-party reports (Chromium's interop code carries D3D11 fallbacks and explicit notes about D3D9 quirkiness; various Steam/MSI Afterburner reverse-engineerings show they use D3D11 internally and composite differently). **WGL_NV_DX_interop2 is essentially a D3D11-and-newer interop in practice, even though the spec language is broader.** + +Key implication: **the recommendation in `wgl-interop-plan.md` was wrong.** I led the user there based on the spec text and well-known overlay-in-D3D9-game examples — but those examples almost universally use D3D11 internally, not D3D9. The "render into AC's D3D9 texture via WGL interop" path is closed on this driver, and likely on every modern NVIDIA driver. + +## What's left + +The original GPU-rendering option space, re-evaluated against this finding: + +1. **D3D11 producer via WGL_NV_DX_interop2 → AC's plain D3D9 consumer.** Not tested in the spike yet, but the *interop* part is the well-trodden one and almost certainly works. The hard part was always "→ AC's plain D3D9 consumer", which still requires either: + - **(a) Hook `Direct3DCreate9` in acclient.exe at runtime to substitute `Direct3DCreate9Ex`.** Makes AC's device Ex. Ex devices CAN open shared HANDLEs from D3D11 (via DXGI sharing). MANAGED-pool wrapper required for AC's textures, lost-device semantics need shimming. + - **(b) CPU readback of the D3D11 texture, then D3D9 LockRect+memcpy.** Same as today's software path with extra GPU latency. Nets nothing. + +2. **Layered/child window approach.** No AC modification. Avalonia renders to its own ANGLE+D3D11 swap chain on a separate Win32 window, DWM composites it over AC. The mover bug (Phase 2a diagnostic — ~50 LOC fix) needs landing first. Then we'd extend layered windows to cover the bar + docked panels too, retiring the EndScene composite path. + +3. **Fix software Skia.** Pursue the LFH AV at its actual source (Skia teardown allocations) rather than trying to GPU-accelerate a path that's blocked at the consumer side. + +Path 1(a) is the same "hook Direct3DCreate9 → Ex" we discussed before the spike — runtime hook, no acclient.exe disk patch, no other-user impact. The spike's value here is that it confirms WGL interop is fine for D3D11 (assumed; would need a 30-minute test to verify), and the only structural blocker remaining is making AC's device Ex. + +Path 2 has the largest scope but the smallest risk to AC stability. Coexistence-mode-friendly for free. + +Path 3 is the smallest and probably the most-immediate-value option (the LFH AV is the actual blocker for daily use, not the lack of GPU rendering). + +## Recommendation + +Stop pursuing the WGL_NV_DX_interop2 → AC's D3D9 plan. Present the three remaining paths and let the user pick. None of them are a small follow-up on the current investigation — each is a meaningful pivot. + +The spike was an unambiguous win: ~3 hours invested, conclusive data, prevented a multi-weekend integration on a foundation that wouldn't have worked. diff --git a/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml b/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml index c8bf062..f81b037 100644 --- a/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml +++ b/src/RynthCore.App.Avalonia/AccountProfileDialog.axaml @@ -1,8 +1,8 @@ + + + + +