Fix logout crash, add OnLogout plugin export, and read true buffed skill

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 <noreply@anthropic.com>
This commit is contained in:
tombohar 2026-04-25 23:36:56 -04:00
commit 8260c60494
17 changed files with 539 additions and 125 deletions

View file

@ -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;

View file

@ -117,6 +117,17 @@ internal static class ChatHooks
/// </summary>
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;
}
}
/// <summary>
/// Drops the cached <c>gmMainChatUI</c> singleton pointer. Called from the
/// logout pipeline so we don't reuse a freed pointer after the next login —
/// <see cref="ListenDetour"/> re-captures the fresh instance on the next
/// chat-UI message dispatch.
/// </summary>
public static void ResetCachedInstance()
{
_gmMainChatInstance = IntPtr.Zero;
_isHiddenAsserted = false;
}
}

View file

@ -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;

View file

@ -92,6 +92,18 @@ internal static class LoginLifecycleHooks
}
}
/// <summary>
/// Clears the one-shot observation flag so the next <c>SendLoginCompleteNotification</c>
/// raises <see cref="LoginComplete"/> again. Called by the logout pipeline so the
/// following login (e.g. swapping characters) re-runs login-gated startup.
/// </summary>
public static void ResetObservation()
{
HasObservedLoginComplete = false;
_statusMessage = "Awaiting next SendLoginCompleteNotification.";
_waitingLogged = false;
}
public static void Poll()
{
if (HasObservedLoginComplete || !IsInstalled)

View file

@ -0,0 +1,168 @@
using System;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// 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:
/// - <c>CPlayerSystem::ExecuteLogOff(void)</c> — 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
/// <c>gmGamePlayUI::RecvNotice_EndCharacterSession</c> — 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.)
/// - <c>gmGamePlayUI::RecvNotice_Logoff(void)</c> — server-driven full logoff
/// notice. Belt-and-braces in case ExecuteLogOff is bypassed in some flow.
///
/// Either one raises <see cref="LogoutComplete"/> 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.)
/// </summary>
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;
/// <summary>Fires once per logout cycle, after the first observed logout signal returns from its original.</summary>
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<ThisCallVoidDelegate>(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;
}
}
/// <summary>Resets the observation flag so the next logout-class notice fires <see cref="LogoutComplete"/> again.</summary>
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");
}
/// <summary>
/// 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
/// <see cref="ResetObservation"/> runs after the next login.
/// </summary>
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}");
}
}
}

View file

@ -178,9 +178,12 @@ internal static class UpdateObjectInventoryHooks
}
/// <summary>
/// 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."
/// </summary>
private static int ScanByContainerId(uint containerId, Span<uint> 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;
}

View file

@ -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<EXCEPTION_RECORD>();
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;
}
/// <summary>
/// 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.
/// </summary>
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} <unknown>");
}
// 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
{
}
}
/// <summary>
/// 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.
/// </summary>
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<MEMORY_BASIC_INFORMATION>()) == 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;

View file

@ -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);

View file

@ -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)

View file

@ -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; }

View file

@ -510,7 +510,7 @@ internal struct RynthCoreAPI
/// <summary>Current API version. Bump when adding fields to RynthCoreAPI.</summary>
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();

View file

@ -171,6 +171,10 @@ internal static class PluginLoader
if (onLoginCompletePtr != IntPtr.Zero)
plugin.OnLoginComplete = Marshal.GetDelegateForFunctionPointer<PluginOnLoginCompleteDelegate>(onLoginCompletePtr);
IntPtr onLogoutPtr = GetProcAddress(handle, "RynthPluginOnLogout");
if (onLogoutPtr != IntPtr.Zero)
plugin.OnLogout = Marshal.GetDelegateForFunctionPointer<PluginOnLogoutDelegate>(onLogoutPtr);
IntPtr onUiInitializedPtr = GetProcAddress(handle, "RynthPluginOnUIInitialized");
if (onUiInitializedPtr != IntPtr.Zero)
plugin.OnUIInitialized = Marshal.GetDelegateForFunctionPointer<PluginOnUIInitializedDelegate>(onUiInitializedPtr);
@ -358,6 +362,7 @@ internal static class PluginLoader
{
var parts = new List<string>(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-");

View file

@ -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.");
}
/// <summary>
/// Hooked to <see cref="LogoutLifecycleHooks.LogoutComplete"/>. Runs on AC's UI
/// thread INSIDE <c>gmGamePlayUI::RecvNotice_Logoff</c>, 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 <see cref="ProcessPendingActions"/>.
/// </summary>
private static void OnLogoutObserved()
{
if (_logoutDispatchPending)
return;
_logoutDispatchPending = true;
RynthLog.Plugin("PluginManager: OnLogout observed - queued for next EndScene frame.");
}
/// <summary>
/// Drained from <see cref="ProcessPendingActions"/> on the EndScene thread.
/// </summary>
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))