RynthCore as of 2026-09-05 (internal f9abab9)

A snapshot of the working tree for aelrynth.com/git/: the code, build files
and public docs. Internal review notes and agent instructions are left out.
MIT licensed; see LICENSE.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tom Bohar 2026-09-25 21:22:59 -04:00
commit 68c301dac8
277 changed files with 86286 additions and 0 deletions

View file

@ -0,0 +1,79 @@
// ============================================================================
// AcActionTrace.cs — Temporary diagnostic for Class B AVs (AC UIElement::
// GetAttribute_* AVs that fire with NO RynthCore frame on the faulting stack).
//
// Lock-free 256-entry ring buffer that records every RynthCore-issued AC-
// mutating call (SelectItem / UseObject / ChangeCombatMode / Cast / attacks)
// with a timestamp. Dumped to the log by ProcessExitHooks.LogTermination on
// any process-exit path so post-crash analysis shows the literal sequence of
// switches RynthCore made in the milliseconds before death — tests the
// "too many switches" hypothesis without behavioural change.
//
// Zero per-call allocation: struct array preallocated at startup, lock-free
// via Interlocked.Increment. Concurrent overwrites of the same slot are
// tolerated (rare at depth 256; we only need the rough recent sequence).
//
// REMOVE once Class B is diagnosed and fixed.
// ============================================================================
using System;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
internal static class AcActionTrace
{
private struct Entry
{
public long Ticks; // DateTime.UtcNow.Ticks
public string Name; // string literal at call site → no per-call alloc
public uint A; // primary arg (typically objectId)
public uint B; // secondary arg (e.g. spellId, mode, attackHeight)
}
private const int Capacity = 256; // power of 2 for cheap mask
private const int Mask = Capacity - 1;
private static readonly Entry[] _slots = new Entry[Capacity];
private static int _next; // Interlocked-incremented counter
/// <summary>
/// Record an AC-mutating action at the engine callback entry. Safe from
/// any thread; per call cost = one Interlocked.Increment + 4 struct field
/// writes. Name MUST be a string literal (no per-call allocation).
/// </summary>
public static void Record(string name, uint a = 0, uint b = 0)
{
int slot = (Interlocked.Increment(ref _next) - 1) & Mask;
_slots[slot].Ticks = DateTime.UtcNow.Ticks;
_slots[slot].Name = name;
_slots[slot].A = a;
_slots[slot].B = b;
}
/// <summary>
/// Dump the buffer to the log. Called by ProcessExitHooks.LogTermination
/// on every termination path so the action history is preserved across
/// AV / fail-fast / clean exit.
/// </summary>
public static void DumpToLog()
{
try
{
int total = Volatile.Read(ref _next);
int count = Math.Min(total, Capacity);
int start = total - count;
RynthLog.Info($"[AcActionTrace] dumping last {count} actions (total counter={total}):");
for (int i = start; i < total; i++)
{
Entry e = _slots[i & Mask];
if (e.Name == null) continue;
DateTime dt = new DateTime(e.Ticks, DateTimeKind.Utc).ToLocalTime();
RynthLog.Info($"[AcActionTrace] {dt:HH:mm:ss.fff} {e.Name}(0x{e.A:X8}, 0x{e.B:X8})");
}
}
catch (Exception ex)
{
RynthLog.Info($"[AcActionTrace] dump exception: {ex.Message}");
}
}
}

View file

@ -0,0 +1,119 @@
using System;
using System.Runtime.InteropServices;
namespace RynthCore.Engine.Compatibility;
internal readonly struct AcClientTextSection
{
public AcClientTextSection(IntPtr moduleBase, int imageSize, int textBaseVa, byte[] bytes)
{
ModuleBase = moduleBase;
ImageSize = imageSize;
TextBaseVa = textBaseVa;
Bytes = bytes;
}
public IntPtr ModuleBase { get; }
public int ImageSize { get; }
public int TextBaseVa { get; }
public byte[] Bytes { get; }
}
internal static class AcClientModule
{
private const int DefaultTextRva = 0x1000;
private const int MaxTextSectionBytes = 0x400000;
private const int SuspiciousTextSectionBytes = 0x500000;
private const ushort ImageDosSignature = 0x5A4D;
private const uint ImageNtSignature = 0x00004550;
private const int DosHeaderPeOffset = 0x3C;
private const int NtOptionalHeaderOffset = 0x18;
private const int OptionalHeaderSizeOfImageOffset = 0x38;
private static bool _loggedBaseOnce;
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr GetModuleHandleW(string? lpModuleName);
public static bool TryReadTextSection(out AcClientTextSection textSection)
{
textSection = default;
try
{
IntPtr moduleBase = GetModuleHandleW("acclient.exe");
if (moduleBase == IntPtr.Zero)
moduleBase = GetModuleHandleW(null);
if (moduleBase == IntPtr.Zero)
{
RynthLog.Compat($"Compat: acclient.exe module not found (error {Marshal.GetLastWin32Error()}).");
return false;
}
if (!TryReadImageSize(moduleBase, out int imageSize))
{
RynthLog.Compat("Compat: failed to read acclient.exe PE headers.");
return false;
}
if (!_loggedBaseOnce)
{
_loggedBaseOnce = true;
RynthLog.Verbose($"Compat: acclient.exe base=0x{moduleBase.ToInt32():X8}, size=0x{imageSize:X}");
}
int rawTextSize = imageSize - DefaultTextRva;
int textSize = rawTextSize;
if (textSize <= 0 || textSize > SuspiciousTextSectionBytes)
{
textSize = Math.Min(Math.Max(0, rawTextSize), MaxTextSectionBytes);
}
else
{
textSize = Math.Min(textSize, MaxTextSectionBytes);
}
if (textSize <= 0)
{
RynthLog.Compat("Compat: failed to derive a readable acclient .text window.");
return false;
}
IntPtr textBase = IntPtr.Add(moduleBase, DefaultTextRva);
byte[] bytes = new byte[textSize];
Marshal.Copy(textBase, bytes, 0, bytes.Length);
textSection = new AcClientTextSection(
moduleBase,
imageSize,
moduleBase.ToInt32() + DefaultTextRva,
bytes);
return true;
}
catch (Exception ex)
{
RynthLog.Compat($"Compat: failed to read acclient text section - {ex.Message}");
return false;
}
}
private static bool TryReadImageSize(IntPtr moduleBase, out int imageSize)
{
imageSize = 0;
if ((ushort)Marshal.ReadInt16(moduleBase) != ImageDosSignature)
return false;
int peOffset = Marshal.ReadInt32(moduleBase, DosHeaderPeOffset);
if (peOffset <= 0)
return false;
IntPtr ntHeaders = IntPtr.Add(moduleBase, peOffset);
if ((uint)Marshal.ReadInt32(ntHeaders) != ImageNtSignature)
return false;
imageSize = Marshal.ReadInt32(ntHeaders, NtOptionalHeaderOffset + OptionalHeaderSizeOfImageOffset);
return imageSize > DefaultTextRva;
}
}

View file

@ -0,0 +1,616 @@
using System;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
// Marshals off-thread bot ACTIONS onto AC's main (game) thread.
//
// AC is single-threaded and non-reentrant. The plugin pump (and chat-command /
// UI threads) run OFF AC's main thread; when they invoke AC state-mutating
// functions directly — combat-mode flips, melee/missile attacks, movement,
// object use — they race AC's own per-tick bookkeeping and corrupt its
// object / range lists. AC then access-violates LATER on its own thread during
// routine teardown / range recompute: the dump-verified object-teardown class
// 0x0055FA24 (List<ObjectRangeInfo>::remove via CPlayerSystem::CalculateObjectRangeChecks)
// and 0x00416C86 (DBOCache::DestroyObj). The per-callsite SEH trampoline only
// CONTAINS an AV that fires inside OUR call — it cannot stop AC tripping over
// corruption we left behind. The only real fix is to not mutate off-thread:
// enqueue here, execute on the main thread.
//
// Drained from the always-on EngineFrameController.OnEndScene tick (AC's main
// thread; ~22-33 Hz; fires regardless of EnableImGuiBackend / idle / combat).
//
// Multi-producer-safe: Enqueue takes a short lock (it runs on engine-owned
// threads, never inside an AC detour, so a lock is fine). Drain is the single
// consumer (the main thread) and is lock-free + zero-alloc, so it never blocks
// inside the reverse-P/Invoke detour and never reintroduces the GC-in-detour
// fail-fast class.
//
// The drain re-invokes the EXISTING public action methods. Each of those
// methods self-gates on MainThreadGuard.IsOnMainThread(): off-thread it
// enqueues here; on the main thread (i.e. when called from Drain, or from any
// legitimately main-thread caller) it executes the AC call directly. So there
// is no separate "Direct" body to keep in sync, and no risk of an enqueue loop.
//
// CASTS: routed via the separate cast slot below (EnqueueCast / DrainCasts),
// drained from AC's GAME-LOGIC tick (Client::UseTime, via GameTickHooks) — NOT
// EndScene. EndScene is the render phase and does not drive AC's cast state machine
// to completion (proven dead-end, reverted 2026-05-19); UseTime is where AC processes
// player actions, so the cast completes there. SelectItem is paired inside
// CombatActionHooks.CastSpell's main-thread path, so it stays ordered with the cast.
internal static class AcMainThreadQueue
{
internal enum ActionKind : byte
{
ChangeCombatMode,
MeleeAttack,
MissileAttack,
DoMovement,
StopMovement,
Jump,
UseObject,
// Item mutators marshalled 2026-06-05 (off-thread UseObjectOn/MoveItem/stack ops
// raced AC's per-tick object graph -> null-deref AVs in Client::UseTime, e.g.
// acclient+0xF24E0; same off-thread class as the P1 UseObject fix).
UseObjectOn,
UseEquippedItem,
MoveItemExternal,
MoveItemInternal,
SplitStackInternal,
MergeStackInternal,
GiveObjectTo,
// CommandInterpreter movement marshalled 2026-06-12: SetAutoRun /
// TurnToHeading / StopCompletely were the last direct off-thread AC
// mutators (dump-proven: a SetAutoRun executed 15s after a main thread
// had wedged) — they rewrite the locomotion channels of the SAME
// CommandInterpreter/motion graph the CSequence-AV class corrupts.
SetAutoRun,
TurnToHeading,
StopCompletely,
SetMotion,
// SetSelectedObject marshalled 2026-06-13: the host-API SelectItem /
// SetSelectedObjectId (looting/targeting) was the LAST AC-mutating helper
// still calling AC directly off the pump thread. AC's SetSelectedObject
// (0x0058D110) updates the selection/targeting UIElement subtree; run off
// the main thread it raced AC's own UI walk -> deterministic corruption AV
// at acclient+0x60D1D (UIElement smart-ptr refcount writeback into
// read-only .text, 5 captures in native-crash.log, two threads at once).
SetSelectedObject,
// NativeAttack marshalled 2026-09-01 (deep-audit finding #15): the
// ClientCombatSystem StartAttackRequest/EndAttackRequest pair (plus the
// height-change notify) had no MainThreadGuard gate, unlike the sibling
// MeleeAttack/MissileAttack/ChangeCombatMode. UseNativeAttack defaults
// true, so CombatManager.FireAttack ran this un-marshalled every fight
// right after a correctly-marshalled SelectItem on the same pump thread.
// Carried as one entry (not split) so the whole ordered sequence executes
// atomically after the paired selection, per the audit's fix note.
NativeAttack,
// Jump trio marshalled 2026-09-02 (deep-audit finding #2): CommenceJump/
// DoJump/TapJump call native CommandInterpreter members through
// _boundCmdInterp with zero MainThreadGuard gate — unlike every sibling
// (SetAutoRun/SetMotion/StopCompletely/TurnToHeading), which all marshal
// via this queue. Live-exercised off-thread today via Jumper.cs's
// Decal-coexistence pump-thread tick. CommenceJump and the later
// DoJump/LaunchJumpWithMotion release land in separate queue entries
// (separate ticks, ~msToHoldDown apart) — that's fine, the ordering
// just needs to stay FIFO within this single-consumer queue, which it does.
CommenceJump,
TapJump,
DoJumpAutonomous,
// LaunchJumpWithMotion (PlayerPhysicsHooks.cs) is the more dangerous of
// the two release paths: it Marshal.WriteInt32's directly into
// CMotionInterp's forward/strafe/turn fields with NO thread gate at
// all (not even the thiscall-through-delegate try/catch the
// CommandInterpreter trio has) before calling DoJump. A torn write here
// racing AC's own motion-graph tick is exactly the CSequence corruption
// class. Carries the 5 hold-flags packed into A (bit0=shift, bit1=W,
// bit2=X, bit3=Z, bit4=C).
LaunchJumpWithMotion,
}
// Four payload slots cover every routed action (the 4th was added for
// MoveItemInternal/SplitStackInternal: id, container, slot, amount). Floats are
// carried as their IEEE bit pattern in a uint slot (BitConverter round-trip).
private readonly struct Entry(AcMainThreadQueue.ActionKind kind, uint a, uint b, uint c, uint d)
{
public readonly ActionKind Kind = kind;
public readonly uint A = a;
public readonly uint B = b;
public readonly uint C = c;
public readonly uint D = d;
}
private const int Capacity = 256; // power of two
private const int Mask = Capacity - 1;
private static readonly Entry[] _slots = new Entry[Capacity];
private static readonly object _producerLock = new();
// Monotonic counters. Producers advance _tail under _producerLock; the sole
// consumer (main thread) advances _head.
private static int _head;
private static int _tail;
private static long _dropped;
public static long DroppedCount => Interlocked.Read(ref _dropped);
private static bool Enqueue(ActionKind kind, uint a, uint b, uint c, uint d = 0)
{
lock (_producerLock)
{
int tail = _tail;
int head = Volatile.Read(ref _head);
if (tail - head >= Capacity)
{
// Full. Drop rather than block or fall back to an off-thread AC
// mutation — a dropped movement/attack tick self-corrects on the
// next bot tick; an off-thread mutation can crash the client.
Interlocked.Increment(ref _dropped);
return false;
}
_slots[tail & Mask] = new Entry(kind, a, b, c, d);
Volatile.Write(ref _tail, tail + 1);
return true;
}
}
// ── Typed enqueue helpers (called by the public action methods when they
// detect they're running off AC's main thread) ───────────────────────
public static bool EnqueueChangeCombatMode(int mode) =>
Enqueue(ActionKind.ChangeCombatMode, unchecked((uint)mode), 0, 0);
public static bool EnqueueMeleeAttack(uint targetId, int attackHeight, float powerLevel) =>
Enqueue(ActionKind.MeleeAttack, targetId, unchecked((uint)attackHeight),
BitConverter.SingleToUInt32Bits(powerLevel));
public static bool EnqueueMissileAttack(uint targetId, int attackHeight, float accuracyLevel) =>
Enqueue(ActionKind.MissileAttack, targetId, unchecked((uint)attackHeight),
BitConverter.SingleToUInt32Bits(accuracyLevel));
public static bool EnqueueDoMovement(uint motion, float speed, int holdKey) =>
Enqueue(ActionKind.DoMovement, motion, unchecked((uint)holdKey),
BitConverter.SingleToUInt32Bits(speed));
public static bool EnqueueStopMovement(uint motion, int holdKey) =>
Enqueue(ActionKind.StopMovement, motion, unchecked((uint)holdKey), 0);
public static bool EnqueueSetAutoRun(bool enabled) =>
Enqueue(ActionKind.SetAutoRun, enabled ? 1u : 0u, 0, 0);
public static bool EnqueueTurnToHeading(float headingDegrees) =>
Enqueue(ActionKind.TurnToHeading, BitConverter.SingleToUInt32Bits(headingDegrees), 0, 0);
public static bool EnqueueStopCompletely() =>
Enqueue(ActionKind.StopCompletely, 0, 0, 0);
public static bool EnqueueSetMotion(uint motion, bool enabled) =>
Enqueue(ActionKind.SetMotion, motion, enabled ? 1u : 0u, 0);
public static bool EnqueueJump(float extent) =>
Enqueue(ActionKind.Jump, BitConverter.SingleToUInt32Bits(extent), 0, 0);
public static bool EnqueueUseObject(uint objectId) =>
Enqueue(ActionKind.UseObject, objectId, 0, 0);
public static bool EnqueueUseObjectOn(uint sourceObjectId, uint targetObjectId) =>
Enqueue(ActionKind.UseObjectOn, sourceObjectId, targetObjectId, 0);
public static bool EnqueueUseEquippedItem(uint sourceObjectId, uint targetObjectId) =>
Enqueue(ActionKind.UseEquippedItem, sourceObjectId, targetObjectId, 0);
public static bool EnqueueMoveItemExternal(uint objectId, uint targetContainerId, int amount) =>
Enqueue(ActionKind.MoveItemExternal, objectId, targetContainerId, unchecked((uint)amount));
public static bool EnqueueMoveItemInternal(uint objectId, uint targetContainerId, int slot, int amount) =>
Enqueue(ActionKind.MoveItemInternal, objectId, targetContainerId, unchecked((uint)slot), unchecked((uint)amount));
public static bool EnqueueSplitStackInternal(uint objectId, uint targetContainerId, int slot, int amount) =>
Enqueue(ActionKind.SplitStackInternal, objectId, targetContainerId, unchecked((uint)slot), unchecked((uint)amount));
public static bool EnqueueMergeStackInternal(uint sourceObjectId, uint targetObjectId) =>
Enqueue(ActionKind.MergeStackInternal, sourceObjectId, targetObjectId, 0);
public static bool EnqueueGiveObjectTo(uint objectId, uint targetId, int amount) =>
Enqueue(ActionKind.GiveObjectTo, objectId, targetId, unchecked((uint)amount));
public static bool EnqueueSetSelectedObject(uint objectId) =>
Enqueue(ActionKind.SetSelectedObject, objectId, 0, 0);
public static bool EnqueueNativeAttack(int attackHeight, float power) =>
Enqueue(ActionKind.NativeAttack, unchecked((uint)attackHeight),
BitConverter.SingleToUInt32Bits(power), 0);
public static bool EnqueueCommenceJump() => Enqueue(ActionKind.CommenceJump, 0, 0, 0);
public static bool EnqueueTapJump() => Enqueue(ActionKind.TapJump, 0, 0, 0);
public static bool EnqueueDoJumpAutonomous(bool autonomous) =>
Enqueue(ActionKind.DoJumpAutonomous, autonomous ? 1u : 0u, 0, 0);
public static bool EnqueueLaunchJumpWithMotion(bool shift, bool holdW, bool holdX, bool holdZ, bool holdC)
{
uint flags = (shift ? 1u : 0u) | (holdW ? 2u : 0u) | (holdX ? 4u : 0u) | (holdZ ? 8u : 0u) | (holdC ? 16u : 0u);
return Enqueue(ActionKind.LaunchJumpWithMotion, flags, 0, 0);
}
// Latched by EngineLifecycle.Shutdown: once teardown begins, queued plugin
// actions must NOT keep executing on AC's main thread — the detours stay
// live until MH_DisableHook(ALL), so without this latch a marshalled
// mutation (SetAutoRun etc.) can run mid-teardown against state that
// plugin Shutdowns are concurrently freeing (observed live at
// 2026-06-11 07:44:03: "Move: SetAutoRun(False)" fired between plugin
// shutdown steps). Abandoned entries are benign.
private static volatile bool _disarmed;
/// <summary>Stop executing queued actions/casts permanently (engine teardown).</summary>
public static void Disarm() => _disarmed = true;
// Single-consumer drain on AC's main thread (EngineFrameController.OnEndScene).
// Re-invokes the public action methods; on the main thread they execute the
// real AC call directly (their IsOnMainThread gate is satisfied here).
// Gesture-phase defer state for the action ring (mirrors the cast slot's
// 56e6946 guard; see DrainDeferTickCap note below for why we PROCEED
// rather than drop after the cap).
private static int _drainDeferTicks;
private const int DrainDeferTickCap = 250;
public static void Drain()
{
if (_disarmed) return;
// Deep-audit finding #22 (2026-06-18): these three queues are
// documented as deliberately separate from the gesture-gated action
// ring below specifically so appraisals/chat "can never get
// gesture-deferred" — but the gesture-defer early-return further
// down used to run BEFORE these calls, so a non-empty action ring
// sitting behind an in-flight gesture silently stalled chat output
// and 0xC8 appraisal sends too, contradicting that invariant. Each
// drains only while ITS OWN queue is non-empty, so moving them here
// costs nothing when they're empty (the common case).
DrainChat();
DrainChatCommands();
DrainRequestIds();
int head = _head; // only the main thread writes _head
int tail = Volatile.Read(ref _tail);
// ── Gesture-phase serialization (extends the 56e6946 anim-walk guard
// to the whole ring) ─────────────────────────────────────────────────
// Every ring action perturbs AC's action/motion state to some degree:
// UseObject starts a reach gesture, ChangeCombatMode rebuilds the
// motion graph, movement rewrites locomotion channels. Retail AC
// serializes these against the IN-FLIGHT gesture via its action queue;
// we previously serialized thread + tick-phase but not gesture-phase.
// Defer the drain while the pending-motion list [CMI+0x80] is
// non-empty — bounded, then PROCEED (unlike the cast slot we never
// drop: dropping arbitrary item/movement actions desyncs the bot far
// worse than a late injection, and the pre-2026-06-12 behavior was
// "always inject" anyway, so proceeding past the cap is never worse).
if (head != tail)
{
if (PlayerPhysicsHooks.TryGetCastGestureInProgress(out bool gestureInFlight) && gestureInFlight
&& ++_drainDeferTicks <= DrainDeferTickCap)
return;
_drainDeferTicks = 0;
}
while (head != tail)
{
Entry e = _slots[head & Mask];
Volatile.Write(ref _head, ++head);
try
{
switch (e.Kind)
{
case ActionKind.ChangeCombatMode:
CombatActionHooks.ChangeCombatMode(unchecked((int)e.A));
break;
case ActionKind.MeleeAttack:
CombatActionHooks.MeleeAttack(e.A, unchecked((int)e.B),
BitConverter.UInt32BitsToSingle(e.C));
break;
case ActionKind.MissileAttack:
CombatActionHooks.MissileAttack(e.A, unchecked((int)e.B),
BitConverter.UInt32BitsToSingle(e.C));
break;
case ActionKind.DoMovement:
MovementActionHooks.DoMovement(e.A,
BitConverter.UInt32BitsToSingle(e.C), unchecked((int)e.B));
break;
case ActionKind.StopMovement:
MovementActionHooks.StopMovement(e.A, unchecked((int)e.B));
break;
case ActionKind.Jump:
MovementActionHooks.JumpNonAutonomous(BitConverter.UInt32BitsToSingle(e.A));
break;
case ActionKind.UseObject:
ClientHelperHooks.UseObject(e.A);
break;
case ActionKind.UseObjectOn:
ClientHelperHooks.UseObjectOn(e.A, e.B);
break;
case ActionKind.UseEquippedItem:
ClientHelperHooks.UseEquippedItem(e.A, e.B);
break;
case ActionKind.MoveItemExternal:
ClientHelperHooks.MoveItemExternal(e.A, e.B, unchecked((int)e.C));
break;
case ActionKind.MoveItemInternal:
ClientHelperHooks.MoveItemInternal(e.A, e.B, unchecked((int)e.C), unchecked((int)e.D));
break;
case ActionKind.SplitStackInternal:
ClientHelperHooks.SplitStackInternal(e.A, e.B, unchecked((int)e.C), unchecked((int)e.D));
break;
case ActionKind.MergeStackInternal:
ClientHelperHooks.MergeStackInternal(e.A, e.B);
break;
case ActionKind.GiveObjectTo:
ClientHelperHooks.GiveObjectTo(e.A, e.B, unchecked((int)e.C));
break;
case ActionKind.SetSelectedObject:
// On the main thread now -> SetSelectedObjectId's gate is
// satisfied and it calls AC's SetSelectedObject directly.
ClientHelperHooks.SetSelectedObjectId(e.A);
break;
case ActionKind.NativeAttack:
// On the main thread now -> NativeAttack's gate is
// satisfied and it fires the real StartAttackRequest/
// EndAttackRequest pair directly.
ClientCombatHooks.NativeAttack(unchecked((int)e.A),
BitConverter.UInt32BitsToSingle(e.B));
break;
case ActionKind.CommenceJump:
CommandInterpreterHooks.CommenceJump();
break;
case ActionKind.TapJump:
CommandInterpreterHooks.TapJump();
break;
case ActionKind.DoJumpAutonomous:
CommandInterpreterHooks.DoJump(e.A != 0);
break;
case ActionKind.LaunchJumpWithMotion:
PlayerPhysicsHooks.LaunchJumpWithMotion(
(e.A & 1u) != 0, (e.A & 2u) != 0, (e.A & 4u) != 0,
(e.A & 8u) != 0, (e.A & 16u) != 0);
break;
case ActionKind.SetAutoRun:
CommandInterpreterHooks.SetAutoRun(e.A != 0);
break;
case ActionKind.TurnToHeading:
CommandInterpreterHooks.TurnToHeading(BitConverter.UInt32BitsToSingle(e.A));
break;
case ActionKind.StopCompletely:
CommandInterpreterHooks.StopCompletely();
break;
case ActionKind.SetMotion:
CommandInterpreterHooks.SetMotion(e.A, e.B != 0);
break;
}
}
catch
{
// One action must never break the drain loop. (AC-side AVs are
// not managed exceptions and won't be caught here — but these
// now run on the correct thread, which is the whole point.)
}
tail = Volatile.Read(ref _tail);
}
}
// ── RequestId slot (0xC8 appraisal sends from AutoIdService) ──────────────────
// AutoIdService runs on a Timer thread; sending 0xC8 directly there does AC heap
// allocation + a non-atomic shared UI-counter increment off AC's main thread (the
// off-thread-send class flagged for RequestId). Marshal onto the main thread here.
// Kept in its OWN queue — NOT the gesture-deferred action ring above — so a backlog
// of appraisals can never crowd out combat/movement actions or get gesture-deferred:
// an appraisal is just a packet send and doesn't perturb AC's motion/UI state.
private static readonly System.Collections.Generic.Queue<uint> _requestIdQueue = new();
private static readonly object _requestIdLock = new();
private const int MaxRequestIdQueue = 256;
// Pump/Timer-thread enqueue. Drops (returns false) if the queue is full.
public static bool EnqueueRequestId(uint objectId)
{
if (objectId == 0) return false;
lock (_requestIdLock)
{
if (_requestIdQueue.Count >= MaxRequestIdQueue)
{
Interlocked.Increment(ref _dropped);
return false;
}
_requestIdQueue.Enqueue(objectId);
return true;
}
}
// Single-consumer drain on AC's main thread (from Drain()). On the main thread
// CombatActionHooks.RequestId sends the 0xC8 directly.
private static void DrainRequestIds()
{
while (true)
{
uint id;
lock (_requestIdLock)
{
if (_requestIdQueue.Count == 0) return;
id = _requestIdQueue.Dequeue();
}
try { CombatActionHooks.RequestId(id); } catch { }
}
}
// ── Chat slot (WriteToChat strings) ──────────────────────────────────────────
// WriteToChat carries a string, which can't ride the uint Entry queue. Off-thread
// AddTextToScroll races AC's chat-scroll buffer and corrupts it (the recurring
// 0x00460D1D write-AV that killed a 5h+ session 2026-06-05). Chat writes marshal
// here and drain on the main thread from Drain(), alongside the item/movement
// actions. WriteToChat's 100 ms rate-limit runs BEFORE the enqueue, so a bot retry
// burst is dropped on the pump thread and this queue never fills with spam.
private static readonly System.Collections.Generic.Queue<(string Text, int ChatType)> _chatQueue = new();
private static readonly object _chatLock = new();
private const int MaxChatQueue = 64;
// Pump-thread enqueue. Drops (returns false) if the queue is full.
public static bool EnqueueWriteToChat(string text, int chatType)
{
lock (_chatLock)
{
if (_chatQueue.Count >= MaxChatQueue)
{
Interlocked.Increment(ref _dropped);
return false;
}
_chatQueue.Enqueue((text, chatType));
return true;
}
}
// Single-consumer drain on AC's main thread. Re-invokes WriteToChat, whose
// IsOnMainThread gate is satisfied here so it runs AddTextToScroll directly.
private static void DrainChat()
{
while (true)
{
(string Text, int ChatType) item;
lock (_chatLock)
{
if (_chatQueue.Count == 0) return;
item = _chatQueue.Dequeue();
}
try { ClientHelperHooks.WriteToChat(item.Text, item.ChatType); }
catch { }
}
}
// ── Chat COMMAND slot (full ChatCommandDispatcher.Dispatch lines) ────────────
// Deep-audit finding #4 (2026-06-18): ChatCommandDispatcher.Dispatch is not
// network-only — it runs arbitrary plugin OnChatBarEnter handlers,
// constructs/destructs AC's native PStringBase<char> (alloc/free in AC's
// heap), and calls Event_Talk/Event_Emote/etc. directly against AC's live
// chat-manager, all of which assumed (incorrectly) "safe from any thread".
// Off-thread callers exist today: OnLoginCommandRunner (ThreadPool via
// Task.Run), ChatFileDispatcher (FileSystemWatcher thread), and
// Host.InvokeChatParser (plugin export, any thread). Gating inside
// Dispatch() itself (rather than at each caller) covers all three at once.
// A full command line can't ride the uint Entry ring, so it gets its own
// string queue, same shape as the WriteToChat slot above.
private static readonly System.Collections.Generic.Queue<string> _chatCommandQueue = new();
private static readonly object _chatCommandLock = new();
private const int MaxChatCommandQueue = 64;
// Off-thread enqueue. Drops (returns false) if the queue is full.
public static bool EnqueueChatCommand(string text)
{
lock (_chatCommandLock)
{
if (_chatCommandQueue.Count >= MaxChatCommandQueue)
{
Interlocked.Increment(ref _dropped);
return false;
}
_chatCommandQueue.Enqueue(text);
return true;
}
}
// Single-consumer drain on AC's main thread. Re-invokes Dispatch, whose
// IsOnMainThread gate is satisfied here so it runs the full body directly
// instead of re-enqueuing.
private static void DrainChatCommands()
{
while (true)
{
string text;
lock (_chatCommandLock)
{
if (_chatCommandQueue.Count == 0) return;
text = _chatCommandQueue.Dequeue();
}
try { ChatCommandDispatcher.Dispatch(text); }
catch { }
}
}
// ── Cast slot (SelectItem + CastSpell pair) ─────────────────────────────────
// Drained at AC's GAME-LOGIC tick (Client::UseTime via GameTickHooks), NOT the
// EndScene render tick. Single-outstanding: EnqueueCast returns false while a cast
// is pending so the off-thread caller (BuffManager / CombatManager) retries next
// tick — they already handle a false return without wedging. At ~frame-rate drain
// the slot clears within ~1 frame. This is the LAST off-thread AC mutator to be
// marshalled, closing the off-thread object-graph corruption class at its source.
private static int _castPending;
private static uint _castTargetId;
private static uint _castSpellId;
private static readonly object _castLock = new();
// Ticks DrainCasts has deferred the pending cast because a motion gesture was
// still in flight. Bounded so a stuck gesture (the documented wand-wield wedge
// variant) can't park a cast forever: past the cap the cast is DROPPED — the
// plugin's no-chat-resolve machinery already retries casts that produce no
// chat, so a drop degrades to one retry cycle, never a wedge.
private static int _castDeferTicks;
private static long _castDeferDrops;
private const int CastDeferTickCap = 250; // ~4-8 s at the 30-63 Hz UseTime rate
/// <summary>Casts dropped after deferring CastDeferTickCap ticks (stuck gesture).</summary>
public static long CastDeferDropCount => Interlocked.Read(ref _castDeferDrops);
// Pump-thread enqueue. Returns false (caller retries next tick) if a cast is
// already pending.
public static bool EnqueueCast(uint targetId, uint spellId)
{
lock (_castLock)
{
if (_castPending != 0) return false;
_castTargetId = targetId;
_castSpellId = spellId;
_castPending = 1;
return true;
}
}
// Drained on AC's MAIN thread from the Client::UseTime detour (game-logic tick).
// Re-invokes CombatActionHooks.CastSpell, which on the main thread executes the
// cast directly (SelectItem + ClientMagicSystem::CastSpell via the SEH trampoline).
public static void DrainCasts()
{
if (_disarmed) return; // engine teardown in progress
if (Volatile.Read(ref _castPending) == 0) return; // alloc-free fast path
// ── Anim-walk race guard (dump-proven 2026-06-12) ────────────────────
// DrainCasts runs PRE-tick (selection timing), but a cast initiates a
// wind-up gesture that REPLACES the player's pending CSequence motions —
// and the SAME UseTime call then walks that sequence. If a gesture is
// already mid-flight when we inject, the walker can hit a freed/null
// node: AV at acclient 0x00526840 AnimSequenceNode::get_part_frame
// [null+0xC], full stack in CrashDumps\acclient_anim_av_4716.dmp
// (7.6 h overnight soak, crash INSIDE _originalUseTime, our detour on
// the stack below it). Same mechanism the post-tick reorder fixed for
// UseObject/movement — casts were exempted and carried the residue.
// Defer while the pending-motion list is non-empty (the exact structure
// the tick walks); main-thread read, alloc-free, fail-open: if the read
// itself fails we cast (pre-fix behavior) rather than park.
if (PlayerPhysicsHooks.TryGetCastGestureInProgress(out bool gestureInFlight) && gestureInFlight)
{
if (++_castDeferTicks <= CastDeferTickCap)
return; // retry next tick
// Gesture stuck past the cap — drop the cast instead of injecting
// into a wedged motion graph; the plugin retries via no-chat-resolve.
lock (_castLock) { _castPending = 0; }
_castDeferTicks = 0;
Interlocked.Increment(ref _castDeferDrops);
return;
}
_castDeferTicks = 0;
uint target, spell;
lock (_castLock)
{
if (_castPending == 0) return;
target = _castTargetId;
spell = _castSpellId;
_castPending = 0;
}
CombatActionHooks.CastSpell(target, unchecked((int)spell));
}
}

View file

@ -0,0 +1,296 @@
using System;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Reads the current account name via Client::GetInstance() + Client::GetAccountName().
/// Captures the world/server name by hooking ECM_Login::SendNotice_WorldName (cdecl),
/// with a fallback to the launcher's per-process JSON context file.
///
/// Client::GetInstance() — static cdecl, Map: 000104C0 → live VA: 0x004114C0
/// Client::GetAccountName() — thiscall, Map: 00000D90 → live VA: 0x00401D90
/// Returns accountID* where first field is PStringBase&lt;char&gt; (4-byte ptr to PSRefBuffer&lt;char&gt;).
///
/// ECM_Login::SendNotice_WorldName — cdecl, Map: 00292A60 → live VA: 0x00693A60
/// Called once during login when the server announces the world name.
/// Parameter: AC1Legacy::PStringBase&lt;char&gt; const& — same PSRefBuffer layout as account name.
///
/// PSRefBuffer&lt;char&gt; layout (confirmed from ClientObjectHooks InqString):
/// +0: Turbine_RefCount { vfptr(4), m_cRef(4) } = 8 bytes
/// +8: m_len (Int32, includes null terminator)
/// +20: m_data[] (ANSI string)
/// </summary>
internal static class AccountHooks
{
private const int ReferenceClientGetInstance = 0x004114C0;
private const int ReferenceClientGetAccountName = 0x00401D90;
private const int SendNoticeWorldNameFallbackVa = 0x00693A60;
private const int PStringBufferLenOffset = 8;
private const int PStringBufferDataOffset = 20;
// ECM_Login::SendNotice_WorldName(AC1Legacy::PStringBase<char> const&) — bool (cdecl)
// Distinctive: vftable-call via push 0x186A2 (UI message ID for world-name notice).
private static readonly byte?[] SendNoticeWorldNamePattern =
[
0xE8, null, null, null, null, // call rel32
0x8B, 0x10, 0x68, 0xA2, 0x86, 0x01, 0x00, // mov edx,[eax]; push 0x186A2
0x8B, 0xC8, 0xFF, 0x52, 0x10, // mov ecx,eax; call [edx+0x10]
0x85, 0xC0, 0x74, 0x22, 0x56, 0x8B, 0x70, 0x04
];
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr ClientGetInstanceDelegate();
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate IntPtr ClientGetAccountNameDelegate(IntPtr clientPtr);
// ECM_Login::SendNotice_WorldName(AC1Legacy::PStringBase<char> const& i_strName) → bool
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate byte SendNoticeWorldNameDelegate(IntPtr pstringPtr);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern int VirtualQuery(IntPtr lpAddress, out MEMORY_BASIC_INFORMATION lpBuffer, int dwLength);
[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 = 0x1000;
private const uint PAGE_NOACCESS = 0x01;
private const uint PAGE_GUARD = 0x100;
private static ClientGetInstanceDelegate? _getClientInstance;
private static ClientGetAccountNameDelegate? _getAccountName;
private static SendNoticeWorldNameDelegate? _originalSendNoticeWorldName;
private static SendNoticeWorldNameDelegate? _sendNoticeWorldNameDetour;
private static string? _cachedAccountName;
private static string? _cachedWorldName;
public static bool IsInitialized { get; private set; }
public static bool WorldHookInstalled { get; private set; }
public static void Initialize()
{
try
{
_getClientInstance = Marshal.GetDelegateForFunctionPointer<ClientGetInstanceDelegate>(
new IntPtr(ReferenceClientGetInstance));
_getAccountName = Marshal.GetDelegateForFunctionPointer<ClientGetAccountNameDelegate>(
new IntPtr(ReferenceClientGetAccountName));
IsInitialized = true;
RynthLog.Verbose("Compat: account hooks ready.");
}
catch (Exception ex)
{
RynthLog.Compat($"Compat: account hooks failed - {ex.Message}");
}
HookWorldName();
}
private static void HookWorldName()
{
try
{
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
{
RynthLog.Compat("AccountHooks: world-name hook skipped - acclient.exe not available.");
return;
}
var resolved = HookResolver.Resolve(textSection, "AccountHooks.SendNotice_WorldName",
SendNoticeWorldNamePattern, SendNoticeWorldNameFallbackVa);
if (!resolved.Success)
return;
_sendNoticeWorldNameDetour = SendNoticeWorldNameDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_sendNoticeWorldNameDetour);
_originalSendNoticeWorldName = Marshal.GetDelegateForFunctionPointer<SendNoticeWorldNameDelegate>(
MinHook.HookCreate(resolved.Address, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(resolved.Address);
WorldHookInstalled = true;
RynthLog.Compat($"AccountHooks: world-name hook ready @ 0x{resolved.Address.ToInt32():X8}.");
}
catch (Exception ex)
{
RynthLog.Compat($"AccountHooks: world-name hook install threw {ex.GetType().Name}: {ex.Message}");
}
}
private static byte SendNoticeWorldNameDetour(IntPtr pstringPtr)
{
RecursionGuard.Tick("AccountHooks.SendNoticeWorldName");
byte result = 0;
try { result = _originalSendNoticeWorldName!(pstringPtr); } catch { }
try
{
if (pstringPtr != IntPtr.Zero && IsReadable(pstringPtr))
{
// AC1Legacy::PStringBase<char>: first field is PSRefBuffer<char>*
IntPtr bufferPtr = Marshal.ReadIntPtr(pstringPtr);
if (bufferPtr != IntPtr.Zero && IsReadable(bufferPtr + PStringBufferDataOffset))
{
int len = Marshal.ReadInt32(bufferPtr + PStringBufferLenOffset);
// Clamp + length-aware check (finding #29): len comes from
// AC's own heap, only floor-checked before — a corrupt/torn
// value could otherwise drive a copy past the committed page.
if (len > 1 && len <= 256 && IsReadable(bufferPtr + PStringBufferDataOffset, len - 1))
{
string? name = Marshal.PtrToStringAnsi(bufferPtr + PStringBufferDataOffset, len - 1);
if (!string.IsNullOrEmpty(name))
{
_cachedWorldName = name;
RynthLog.Verbose($"Compat: world name captured - \"{name}\".");
}
}
}
}
}
catch { }
return result;
}
/// <summary>
/// Returns the current account name. Result is cached after the first successful read.
/// </summary>
public static bool TryGetAccountName(out string name)
{
name = string.Empty;
if (_cachedAccountName != null)
{
name = _cachedAccountName;
return true;
}
if (_getClientInstance == null || _getAccountName == null)
return false;
try
{
IntPtr clientPtr = _getClientInstance();
if (clientPtr == IntPtr.Zero || !IsReadable(clientPtr))
return false;
IntPtr accountIdPtr = _getAccountName(clientPtr);
if (accountIdPtr == IntPtr.Zero || !IsReadable(accountIdPtr))
return false;
// accountID.name is PStringBase<char> — a 4-byte pointer to PSRefBuffer<char>
IntPtr bufferPtr = Marshal.ReadIntPtr(accountIdPtr);
if (bufferPtr == IntPtr.Zero || !IsReadable(bufferPtr + PStringBufferDataOffset))
return false;
int len = Marshal.ReadInt32(bufferPtr + PStringBufferLenOffset);
// Clamp + length-aware check (finding #29): same rationale as
// SendNoticeWorldNameDetour above.
if (len <= 1 || len > 256 || !IsReadable(bufferPtr + PStringBufferDataOffset, len - 1))
return false;
string? str = Marshal.PtrToStringAnsi(bufferPtr + PStringBufferDataOffset, len - 1);
if (string.IsNullOrEmpty(str))
return false;
_cachedAccountName = str;
name = str;
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Returns the world/server name. Populated by the ECM_Login::SendNotice_WorldName hook
/// when the server announces it during login. Falls back to the RynthCore launcher's
/// per-process JSON context file if the hook hasn't fired yet.
/// </summary>
public static bool TryGetWorldName(out string name)
{
name = string.Empty;
if (_cachedWorldName != null)
{
name = _cachedWorldName;
return true;
}
// Fallback: read from launcher context file (only present if launched via RynthCore)
try
{
string appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string path = System.IO.Path.Combine(appData, "RynthCore", "launch_contexts",
$"launch_context_{Environment.ProcessId}.json");
if (!System.IO.File.Exists(path))
return false;
string json = System.IO.File.ReadAllText(path);
const string key = "\"ServerName\":\"";
int idx = json.IndexOf(key, StringComparison.Ordinal);
if (idx < 0)
return false;
int start = idx + key.Length;
int end = json.IndexOf('"', start);
if (end <= start)
return false;
string serverName = json.Substring(start, end - start);
if (string.IsNullOrEmpty(serverName))
return false;
_cachedWorldName = serverName;
name = serverName;
return true;
}
catch
{
return false;
}
}
private static bool IsReadable(IntPtr ptr)
{
if (ptr == IntPtr.Zero) return false;
if (VirtualQuery(ptr, out var mbi, Marshal.SizeOf<MEMORY_BASIC_INFORMATION>()) == 0) return false;
if (mbi.State != MEM_COMMIT) return false;
if ((mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD)) != 0) return false;
return true;
}
// Deep-audit finding #29 (2026-06-18): the single-arg IsReadable above
// only validates the START page. All three PtrToStringAnsi call sites in
// this file then do a len-driven copy (len from AC's own heap, only
// floor-checked at >1) that can cross into an uncommitted page if len is
// corrupt or torn — a length-aware check (mirroring CrashLogger's
// IsReadable(addr, bytes), which isn't accessible from here) is needed
// for the actual byte span being copied, not just its first byte.
private static bool IsReadable(IntPtr ptr, int bytes)
{
if (ptr == IntPtr.Zero || bytes <= 0) return false;
if (VirtualQuery(ptr, out var mbi, Marshal.SizeOf<MEMORY_BASIC_INFORMATION>()) == 0) return false;
if (mbi.State != MEM_COMMIT) return false;
if ((mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD)) != 0) return false;
long endRequested = ptr.ToInt64() + bytes;
long endRegion = mbi.BaseAddress.ToInt64() + mbi.RegionSize.ToInt64();
return endRequested <= endRegion;
}
}

View file

@ -0,0 +1,588 @@
// ============================================================================
// RynthCore.Engine - Compatibility/AppraisalHooks.cs
//
// Hooks CM_Examine::SendNotice_SetAppraiseInfo to cache appraisal bool
// properties for inventory items whose m_pQualities is null.
// CBaseQualities::InqBool returns 0 for such items because the property
// setter skips CBaseQualities storage when m_pQualities is null.
//
// VA derivation (map_offset + 0x00401000 = live VA):
// 002AF5B0 CM_Examine::SendNotice_SetAppraiseInfo → 0x006B05B0
//
// AppraisalProfile layout (from AppraisalProfile::Clear at 0x005B3BB0):
// +0x00 vtable
// +0x04 success_flag
// +0x08 creature_profile*
// +0x0c hook_profile*
// +0x10 weapon_profile*
// +0x14 armor_profile*
// +0x18 _intStatsTable*
// +0x1c _int64StatsTable*
// +0x20 _boolStatsTable* ← used here
// +0x24 _floatStatsTable*
// +0x28 _strStatsTable*
// +0x2c _didStatsTable*
// ...
//
// PackableHashTable<uint,int> layout (from FUN_005d5760 lookup):
// +0x08 bucket_array (IntPtr[] of node ptrs)
// +0x0c bucket_count (modulus for key % count)
// Node: [+0]=key(uint32), [+4]=value(int), [+8]=next(node* or null)
// ============================================================================
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
namespace RynthCore.Engine.Compatibility;
internal static class AppraisalHooks
{
// CM_Examine::SendNotice_SetAppraiseInfo — cdecl (uint guid, AppraisalProfile*)
// Map: 002AF5B0 → live VA: 0x006B05B0
private const int SendNoticeSetAppraiseInfoVa = 0x006B05B0;
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int SendNoticeSetAppraiseInfoDelegate(uint guid, IntPtr profilePtr);
private static SendNoticeSetAppraiseInfoDelegate? _originalSendNotice;
private static SendNoticeSetAppraiseInfoDelegate? _sendNoticeDetour; // held alive to prevent GC
private static bool _hookInstalled;
private static string _statusMessage = "Not initialized.";
// Tracks every guid for which we've received a SendNotice_SetAppraiseInfo (has assess data)
private static readonly HashSet<uint> _appraisedGuids = new();
// Unix timestamp (seconds) of last appraisal receipt per guid
private static readonly Dictionary<uint, long> _lastIdTime = new();
// Int property cache: guid → (stype → value)
private static readonly Dictionary<uint, Dictionary<uint, int>> _intCache = new();
// Bool property cache: guid → (stype → value)
private static readonly Dictionary<uint, Dictionary<uint, bool>> _boolCache = new();
// String property cache: guid → (stype → value)
private static readonly Dictionary<uint, Dictionary<uint, string>> _stringCache = new();
// Spell book cache: guid → spell ID array (from AppraisalProfile._spellBook PSmartArray<UInt32> at +0x30)
private static readonly Dictionary<uint, uint[]> _spellIdCache = new();
private static readonly object _cacheLock = new();
public static bool IsInstalled => _hookInstalled;
public static string StatusMessage => _statusMessage;
/// <summary>
/// Returns true if a SendNotice_SetAppraiseInfo has been received for this guid this session.
/// </summary>
public static bool HasAppraisalData(uint guid)
{
lock (_cacheLock)
return _appraisedGuids.Contains(guid);
}
/// <summary>
/// Deep-audit finding #33 (2026-06-18): these seven session-scoped
/// collections were populated per appraised guid and never cleared or
/// bounded — no ClearSession() existed, and this class was conspicuously
/// absent from DispatchPendingLogout's reset pipeline (contrast the peer
/// ObjectQualityCache, which has both MaxEntries and a logout
/// ClearSession()). Guids don't survive a session, so a daily
/// multi-boxer accumulates entries indefinitely across relogs — worth
/// closing given this stack's documented 32-bit VA-exhaustion
/// sensitivity even though growth itself is slow. Call from
/// DispatchPendingLogout alongside the other ResetSession() calls.
/// </summary>
public static void ClearSession()
{
lock (_cacheLock)
{
_appraisedGuids.Clear();
_lastIdTime.Clear();
_intCache.Clear();
_boolCache.Clear();
_stringCache.Clear();
_spellIdCache.Clear();
_failedRollLogged.Clear();
}
}
/// <summary>
/// Returns the Unix timestamp (seconds) of when appraisal data was last received for this guid, or 0 if never.
/// </summary>
public static long GetLastIdTime(uint guid)
{
lock (_cacheLock)
return _lastIdTime.TryGetValue(guid, out long t) ? t : 0L;
}
/// <summary>
/// Returns an int property from the last server appraisal for this object.
/// Only populated after the player has identified the item (RequestId).
/// </summary>
public static bool TryGetCachedIntProperty(uint guid, uint stype, out int value)
{
value = 0;
lock (_cacheLock)
{
if (!_intCache.TryGetValue(guid, out Dictionary<uint, int>? props))
return false;
return props.TryGetValue(stype, out value);
}
}
/// <summary>
/// Returns a bool property from the last server appraisal for this object.
/// Only populated after the player has identified the item (RequestId).
/// </summary>
public static bool TryGetCachedBoolProperty(uint guid, uint stype, out bool value)
{
value = false;
lock (_cacheLock)
{
if (!_boolCache.TryGetValue(guid, out Dictionary<uint, bool>? props))
return false;
return props.TryGetValue(stype, out value);
}
}
/// <summary>
/// Returns a string property from the last server appraisal for this object.
/// Only populated after the player has identified the item (RequestId).
/// </summary>
public static bool TryGetCachedStringProperty(uint guid, uint stype, out string value)
{
value = string.Empty;
lock (_cacheLock)
{
if (!_stringCache.TryGetValue(guid, out Dictionary<uint, string>? props))
return false;
return props.TryGetValue(stype, out value!);
}
}
public static void Initialize()
{
if (_hookInstalled)
return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
{
_statusMessage = "acclient.exe not available.";
return;
}
int funcOff = SendNoticeSetAppraiseInfoVa - textSection.TextBaseVa;
if (funcOff < 0 || funcOff >= textSection.Bytes.Length)
{
_statusMessage = $"CM_Examine::SendNotice_SetAppraiseInfo VA out of range @ 0x{SendNoticeSetAppraiseInfoVa:X8}.";
RynthLog.Compat($"Compat: appraisal hook failed - {_statusMessage}");
return;
}
byte firstByte = textSection.Bytes[funcOff];
if (firstByte is 0x00 or 0xCC or 0xC3)
{
_statusMessage = $"CM_Examine::SendNotice_SetAppraiseInfo looks invalid @ 0x{SendNoticeSetAppraiseInfoVa:X8} (opcode 0x{firstByte:X2}).";
RynthLog.Compat($"Compat: appraisal hook failed - {_statusMessage}");
return;
}
try
{
IntPtr targetAddress = new IntPtr(textSection.TextBaseVa + funcOff);
_sendNoticeDetour = SendNoticeDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_sendNoticeDetour);
_originalSendNotice = Marshal.GetDelegateForFunctionPointer<SendNoticeSetAppraiseInfoDelegate>(
MinHook.HookCreate(targetAddress, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(targetAddress);
_hookInstalled = true;
_statusMessage = $"Hooked CM_Examine::SendNotice_SetAppraiseInfo @ 0x{targetAddress.ToInt32():X8}.";
RynthLog.Verbose($"Compat: appraisal hook ready @ 0x{targetAddress.ToInt32():X8}, firstByte=0x{firstByte:X2}");
}
catch (Exception ex)
{
_statusMessage = ex.Message;
RynthLog.Compat($"Compat: appraisal hook failed - {ex.Message}");
}
}
private static int SendNoticeDetour(uint guid, IntPtr profilePtr)
{
// Call original first — notification fires, profile is still live in our frame
int result = _originalSendNotice!(guid, profilePtr);
lock (_cacheLock)
{
_appraisedGuids.Add(guid);
_lastIdTime[guid] = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
}
try
{
CacheIntProps(guid, profilePtr);
}
catch (Exception ex)
{
try { RynthLog.Compat($"Compat: appraisal int cache error guid=0x{guid:X8} - {ex.GetType().Name}: {ex.Message}"); } catch { }
}
try
{
CacheBoolProps(guid, profilePtr);
}
catch (Exception ex)
{
try { RynthLog.Compat($"Compat: appraisal bool cache error guid=0x{guid:X8} - {ex.GetType().Name}: {ex.Message}"); } catch { }
}
try
{
CacheStringProps(guid, profilePtr);
}
catch (Exception ex)
{
try { RynthLog.Compat($"Compat: appraisal string cache error guid=0x{guid:X8} - {ex.GetType().Name}: {ex.Message}"); } catch { }
}
try
{
CacheSpellIds(guid, profilePtr);
}
catch (Exception ex)
{
try { RynthLog.Compat($"Compat: appraisal spell cache error guid=0x{guid:X8} - {ex.GetType().Name}: {ex.Message}"); } catch { }
}
try
{
CacheCreatureVitals(guid, profilePtr);
}
catch (Exception ex)
{
try { RynthLog.Compat($"Compat: appraisal creature-vitals error guid=0x{guid:X8} - {ex.GetType().Name}: {ex.Message}"); } catch { }
}
return result;
}
private static void CacheIntProps(uint guid, IntPtr profilePtr)
{
if (profilePtr == IntPtr.Zero || !ClientObjectHooks.IsReadablePointer(profilePtr))
return;
// AppraisalProfile._intStatsTable* is at offset +0x18
IntPtr intTableFieldAddr = profilePtr + 0x18;
if (!ClientObjectHooks.IsReadablePointer(intTableFieldAddr))
return;
IntPtr intTablePtr = Marshal.ReadIntPtr(intTableFieldAddr);
if (intTablePtr == IntPtr.Zero || !ClientObjectHooks.IsReadablePointer(intTablePtr))
return;
// PackableHashTable<uint,int>: bucket_array at +0x8, bucket_count at +0xC
IntPtr bucketArrayFieldAddr = intTablePtr + 0x08;
IntPtr bucketCountFieldAddr = intTablePtr + 0x0C;
if (!ClientObjectHooks.IsReadablePointer(bucketArrayFieldAddr) || !ClientObjectHooks.IsReadablePointer(bucketCountFieldAddr))
return;
IntPtr bucketArray = Marshal.ReadIntPtr(bucketArrayFieldAddr);
int bucketCount = Marshal.ReadInt32(bucketCountFieldAddr);
if (bucketArray == IntPtr.Zero || bucketCount <= 0 || bucketCount > 65536 || !ClientObjectHooks.IsReadablePointer(bucketArray))
return;
var props = new Dictionary<uint, int>(8);
int totalGuard = 0;
for (int i = 0; i < bucketCount; i++)
{
IntPtr bucketSlotAddr = bucketArray + i * 4;
if (!ClientObjectHooks.IsReadablePointer(bucketSlotAddr)) continue;
IntPtr node = Marshal.ReadIntPtr(bucketSlotAddr);
int chainGuard = 0;
while (node != IntPtr.Zero && chainGuard++ < 4096 && totalGuard++ < 65536)
{
if (!ClientObjectHooks.IsReadablePointer(node)) break;
uint key = (uint)Marshal.ReadInt32(node);
int val = Marshal.ReadInt32(node + 4);
props[key] = val;
IntPtr nextAddr = node + 8;
if (!ClientObjectHooks.IsReadablePointer(nextAddr)) break;
node = Marshal.ReadIntPtr(nextAddr);
}
}
if (props.Count == 0)
return;
lock (_cacheLock)
{
_intCache[guid] = props;
}
RynthLog.Verbose($"Compat: cached {props.Count} int prop(s) for guid=0x{guid:X8}");
}
private static void CacheBoolProps(uint guid, IntPtr profilePtr)
{
if (profilePtr == IntPtr.Zero || !ClientObjectHooks.IsReadablePointer(profilePtr))
return;
// AppraisalProfile._boolStatsTable* is at offset +0x20
IntPtr boolTableFieldAddr = profilePtr + 0x20;
if (!ClientObjectHooks.IsReadablePointer(boolTableFieldAddr))
return;
IntPtr boolTablePtr = Marshal.ReadIntPtr(boolTableFieldAddr);
if (boolTablePtr == IntPtr.Zero || !ClientObjectHooks.IsReadablePointer(boolTablePtr))
return;
// PackableHashTable: bucket_array at +0x8, bucket_count at +0xC
IntPtr bucketArrayFieldAddr = boolTablePtr + 0x08;
IntPtr bucketCountFieldAddr = boolTablePtr + 0x0C;
if (!ClientObjectHooks.IsReadablePointer(bucketArrayFieldAddr) || !ClientObjectHooks.IsReadablePointer(bucketCountFieldAddr))
return;
IntPtr bucketArray = Marshal.ReadIntPtr(bucketArrayFieldAddr);
int bucketCount = Marshal.ReadInt32(bucketCountFieldAddr);
if (bucketArray == IntPtr.Zero || bucketCount <= 0 || bucketCount > 65536 || !ClientObjectHooks.IsReadablePointer(bucketArray))
return;
var props = new Dictionary<uint, bool>(4);
int totalGuard = 0;
for (int i = 0; i < bucketCount; i++)
{
IntPtr bucketSlotAddr = bucketArray + i * 4;
if (!ClientObjectHooks.IsReadablePointer(bucketSlotAddr)) continue;
IntPtr node = Marshal.ReadIntPtr(bucketSlotAddr);
int chainGuard = 0;
while (node != IntPtr.Zero && chainGuard++ < 4096 && totalGuard++ < 65536)
{
if (!ClientObjectHooks.IsReadablePointer(node)) break;
uint key = (uint)Marshal.ReadInt32(node);
int val = Marshal.ReadInt32(node + 4);
props[key] = val != 0;
IntPtr nextAddr = node + 8;
if (!ClientObjectHooks.IsReadablePointer(nextAddr)) break;
node = Marshal.ReadIntPtr(nextAddr);
}
}
if (props.Count == 0)
return;
lock (_cacheLock)
{
_boolCache[guid] = props;
}
RynthLog.Verbose($"Compat: cached {props.Count} bool prop(s) for guid=0x{guid:X8}");
}
private static void CacheStringProps(uint guid, IntPtr profilePtr)
{
if (profilePtr == IntPtr.Zero || !ClientObjectHooks.IsReadablePointer(profilePtr))
return;
// AppraisalProfile._strStatsTable* is at offset +0x28
IntPtr strTableFieldAddr = profilePtr + 0x28;
if (!ClientObjectHooks.IsReadablePointer(strTableFieldAddr))
return;
IntPtr strTablePtr = Marshal.ReadIntPtr(strTableFieldAddr);
if (strTablePtr == IntPtr.Zero || !ClientObjectHooks.IsReadablePointer(strTablePtr))
return;
// PackableHashTable<uint, PStringBase<char>>: bucket_array at +0x8, bucket_count at +0xC
IntPtr bucketArrayFieldAddr = strTablePtr + 0x08;
IntPtr bucketCountFieldAddr = strTablePtr + 0x0C;
if (!ClientObjectHooks.IsReadablePointer(bucketArrayFieldAddr) || !ClientObjectHooks.IsReadablePointer(bucketCountFieldAddr))
return;
IntPtr bucketArray = Marshal.ReadIntPtr(bucketArrayFieldAddr);
int bucketCount = Marshal.ReadInt32(bucketCountFieldAddr);
if (bucketArray == IntPtr.Zero || bucketCount <= 0 || bucketCount > 65536 || !ClientObjectHooks.IsReadablePointer(bucketArray))
return;
var props = new Dictionary<uint, string>(4);
int totalGuard = 0;
for (int i = 0; i < bucketCount; i++)
{
IntPtr bucketSlotAddr = bucketArray + i * 4;
if (!ClientObjectHooks.IsReadablePointer(bucketSlotAddr)) continue;
IntPtr node = Marshal.ReadIntPtr(bucketSlotAddr);
int chainGuard = 0;
while (node != IntPtr.Zero && chainGuard++ < 4096 && totalGuard++ < 65536)
{
if (!ClientObjectHooks.IsReadablePointer(node)) break;
uint key = (uint)Marshal.ReadInt32(node);
// Node value at +4: PStringBase<char>.m_buffer (PSRefBuffer<char>*)
// PSRefBuffer<char> layout: vtable(4) + m_cRef(4) + m_len(4) + m_size(4) + m_hash(4) + m_data[]
IntPtr bufferPtr = Marshal.ReadIntPtr(node + 4);
if (bufferPtr != IntPtr.Zero && ClientObjectHooks.IsReadablePointer(bufferPtr))
{
IntPtr lenFieldAddr = bufferPtr + 8;
if (ClientObjectHooks.IsReadablePointer(lenFieldAddr))
{
int len = Marshal.ReadInt32(lenFieldAddr);
IntPtr strDataAddr = bufferPtr + 20;
if (len > 1 && len < 4096 && ClientObjectHooks.IsReadablePointer(strDataAddr))
{
string? str = Marshal.PtrToStringAnsi(strDataAddr, len - 1);
if (!string.IsNullOrEmpty(str))
props[key] = str;
}
}
}
IntPtr nextAddr = node + 8;
if (!ClientObjectHooks.IsReadablePointer(nextAddr)) break;
node = Marshal.ReadIntPtr(nextAddr);
}
}
if (props.Count == 0)
return;
lock (_cacheLock)
{
_stringCache[guid] = props;
}
RynthLog.Verbose($"Compat: cached {props.Count} string prop(s) for guid=0x{guid:X8}");
}
private static void CacheSpellIds(uint guid, IntPtr profilePtr)
{
if (profilePtr == IntPtr.Zero)
return;
// AppraisalProfile._spellBook (PSmartArray<UInt32>*) is at offset +0x30
// PSmartArray layout: +0x00 vtable, +0x04 m_data*, +0x08 m_sizeAndDeallocate, +0x0C m_num
IntPtr spellBookPtr = Marshal.ReadIntPtr(profilePtr + 0x30);
if (spellBookPtr == IntPtr.Zero)
return;
IntPtr mData = Marshal.ReadIntPtr(spellBookPtr + 0x04);
int mNum = Marshal.ReadInt32(spellBookPtr + 0x0C);
if (mNum == 0)
{
RynthLog.Verbose($"Compat: guid=0x{guid:X8} spell book present but empty (mNum=0)");
return;
}
if (mData == IntPtr.Zero || mNum < 0 || mNum > 512)
{
RynthLog.Compat($"Compat: guid=0x{guid:X8} spell book invalid (mData=0x{mData.ToInt32():X8} mNum={mNum})");
return;
}
var ids = new uint[mNum];
for (int i = 0; i < mNum; i++)
ids[i] = (uint)Marshal.ReadInt32(mData + i * 4);
lock (_cacheLock)
_spellIdCache[guid] = ids;
RynthLog.Verbose($"Compat: cached {mNum} spell ID(s) for guid=0x{guid:X8}");
}
// Rate-limit counter for the creature-vitals diagnostic log line.
private static int _creatureVitalsLogCount;
// Guids already logged with a [FAILED-ROLL] line (dedupe; guarded by _cacheLock).
private static readonly HashSet<uint> _failedRollLogged = new();
/// <summary>
/// Reads the creature sub-profile (AppraisalProfile+0x08 → CreatureAppraisalProfile) for
/// absolute Health/MaxHealth/Stamina/Mana and publishes them to ObjectQualityCache (polled
/// via RynthCoreHost.TryGetTargetVitals) and to plugins (OnUpdateHealth push, e.g. RynthAi's
/// CreatureProfileStore / RynthJuice numbers).
///
/// This is the ONLY opcode that carries a monster's *absolute* max HP — the 0xC9 appraisal
/// CreatureProfile. The 0x01C0 combat stream is ratio-only (ACE divides Current/MaxValue
/// server-side). This hook (CM_Examine::SendNotice_SetAppraiseInfo @ 0x006B05B0) is the live
/// appraisal seam on ACE; the older wire-parse in CombatActionHooks.TryParseIdentifyResponse
/// is dead (its InnerDispatcher caller is disabled and the SmartBox caller was removed).
///
/// Offsets verified from CreatureAppraisalProfile::InqAttribute2nd (decompile 0x005B6ED0):
/// MaxHealth=+0x28 Health=+0x1C MaxStamina=+0x2C Stamina=+0x20 MaxMana=+0x30 Mana=+0x24.
/// The +0x08 pointer is non-null only when the appraisal carried a CreatureProfile (creatures
/// that are not NPCLooksLikeObject); items/hooks leave it 0 (AppraisalProfile::Clear layout).
/// It is the engine's own live struct for this dispatch frame, so the read is safe under the
/// same try/catch the sibling Cache* helpers use — no native call, no AC mutation.
///
/// Crucially this captures max even on a FAILED assess roll: ACE assigns Health/HealthMax
/// before the success gate (CreatureProfile.cs), so no AssessCreature skill is required.
/// </summary>
private static void CacheCreatureVitals(uint guid, IntPtr profilePtr)
{
if (profilePtr == IntPtr.Zero)
return;
// AppraisalProfile._creatureProfile* is at offset +0x08.
IntPtr creaturePtr = Marshal.ReadIntPtr(profilePtr + 0x08);
if (creaturePtr == IntPtr.Zero)
return; // non-creature appraisal (item / hook) — no vitals present
uint maxHealth = unchecked((uint)Marshal.ReadInt32(creaturePtr + 0x28));
if (maxHealth == 0 || maxHealth >= 1_000_000)
return; // unset / implausible — don't poison the cache
uint health = unchecked((uint)Marshal.ReadInt32(creaturePtr + 0x1C));
uint stamina = unchecked((uint)Marshal.ReadInt32(creaturePtr + 0x20));
uint maxStamina = unchecked((uint)Marshal.ReadInt32(creaturePtr + 0x2C));
uint mana = unchecked((uint)Marshal.ReadInt32(creaturePtr + 0x24));
uint maxMana = unchecked((uint)Marshal.ReadInt32(creaturePtr + 0x30));
if (health > maxHealth)
health = maxHealth; // clamp a transient over-read
ObjectQualityCache.SetCreatureVitals(guid,
new CreatureVitals(health, maxHealth, stamina, maxStamina, mana, maxMana));
float ratio = (float)health / maxHealth;
Plugins.PluginManager.QueueUpdateHealth(guid, ratio, health, maxHealth);
// ShowAttributes (wire flag 0x8) is CLEAR on a FAILED assess roll; CreatureAppraisalProfile::UnPack
// (decompile 0x005B7240, lines 31-42) then EXPLICITLY zeroes stamina/mana/attributes — so
// (maxStamina==0 && maxMana==0) is a reliable failed-roll signal, while Health/MaxHealth are written
// unconditionally. A failed-roll line therefore PROVES the un-gated capture (max obtained with no
// attributes). Failed rolls are rare (most mobs have Deception==0 → success forced) and are the whole
// point of this hook, so log them ALWAYS (greppable [FAILED-ROLL] tag); rate-limit the common success case.
if (maxStamina == 0 && maxMana == 0)
{
// Failed roll. Dedupe per guid — the combat target gets re-appraised ~1/0.75s, which would
// otherwise spam the log (and bloat it over a grind). Log the first capture per mob only.
bool firstForGuid;
lock (_cacheLock)
firstForGuid = _failedRollLogged.Add(guid);
if (firstForGuid)
RynthLog.Compat($"Compat: appraisal creature vitals [FAILED-ROLL] guid=0x{guid:X8} hp={health}/{maxHealth} (stam/mana withheld — max captured anyway)");
}
else
{
int log = Interlocked.Increment(ref _creatureVitalsLogCount);
if (log <= 50)
RynthLog.Compat($"Compat: appraisal creature vitals guid=0x{guid:X8} hp={health}/{maxHealth} stam={stamina}/{maxStamina} mana={mana}/{maxMana}");
}
}
/// <summary>
/// Fills <paramref name="output"/> with spell IDs from the last appraisal spell book.
/// Returns the total number of spell IDs (may exceed <paramref name="maxCount"/>), or -1 if no data.
/// </summary>
public static int GetObjectSpellIds(uint guid, uint[] output, int maxCount)
{
lock (_cacheLock)
{
if (!_spellIdCache.TryGetValue(guid, out uint[]? cached))
return -1;
int count = Math.Min(cached.Length, Math.Min(maxCount, output.Length));
Array.Copy(cached, output, count);
return cached.Length;
}
}
}

View file

@ -0,0 +1,126 @@
// ============================================================================
// RynthCore.Engine - Compatibility/AutoIdService.cs
//
// Automatically sends RequestId (appraisal) for newly-created world objects
// so that property caches (AppraisalHooks int/bool/string) are populated
// without requiring the player to manually select each object.
//
// Objects are queued from CreateObjectHooks and drained by a background timer
// with rate-limiting to avoid flooding the server.
// ============================================================================
using System;
using System.Collections.Concurrent;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
internal static class AutoIdService
{
// How often the drain timer fires (ms)
private const int DrainIntervalMs = 100;
// Max RequestId calls per drain tick
private const int MaxPerTick = 3;
// Skip objects already appraised this session
private static readonly ConcurrentDictionary<uint, byte> _sent = new();
// Pending queue
private static readonly ConcurrentQueue<uint> _queue = new();
private static Timer? _drainTimer;
private static bool _started;
public static void Start()
{
if (_started)
return;
_started = true;
_drainTimer = new Timer(DrainTick, null, DrainIntervalMs, DrainIntervalMs);
RynthLog.Verbose("Compat: AutoIdService started.");
}
/// <summary>
/// Dispose the drain timer at engine shutdown so it doesn't keep firing in
/// the old generation's (intentionally still-mapped) module across hot-reloads.
/// </summary>
public static void Stop()
{
if (!_started)
return;
_started = false;
_drainTimer?.Dispose();
_drainTimer = null;
RynthLog.Verbose("Compat: AutoIdService stopped.");
}
/// <summary>
/// Enqueue an object for automatic appraisal. Called from CreateObjectHooks detour.
/// </summary>
public static void Enqueue(uint objectId)
{
if (objectId == 0)
return;
// Skip the player character
uint playerId = ClientHelperHooks.GetPlayerId();
if (playerId != 0 && objectId == playerId)
return;
// Skip if already sent this session
if (!_sent.TryAdd(objectId, 0))
return;
_queue.Enqueue(objectId);
}
/// <summary>
/// Remove an object from the sent set (e.g. when it's destroyed and may be recreated).
/// </summary>
public static void Evict(uint objectId)
{
_sent.TryRemove(objectId, out _);
}
// Last target we issued a priority appraisal for (fires once per target change).
private static uint _lastPriorityTarget;
private static void DrainTick(object? state)
{
try
{
if (!CombatActionHooks.HasRequestId)
return;
int sent = 0;
// Combat-target priority: when the selected target CHANGES, appraise it
// immediately — enqueued ahead of the create-order backlog so a fast kill
// still gets its max-HP appraisal out first instead of waiting behind the
// whole spawn. Fires once per change (guarded), so no per-tick re-appraisal.
uint target = SelectedTargetHooks.ReadCurrentSelectedId();
if (target != 0 && target != _lastPriorityTarget)
{
_lastPriorityTarget = target;
uint playerId = ClientHelperHooks.GetPlayerId();
if (target != playerId && AcMainThreadQueue.EnqueueRequestId(target))
sent++;
}
while (sent < MaxPerTick && _queue.TryDequeue(out uint objectId))
{
// Object may have been destroyed between enqueue and drain
if (objectId == 0)
continue;
// Marshal onto AC's main thread (EndScene drain) — the Timer thread must
// not call the native 0xC8 send directly (off-thread heap alloc + non-atomic
// UI-counter increment). EnqueueRequestId is the marshalled path.
AcMainThreadQueue.EnqueueRequestId(objectId);
sent++;
}
}
catch { }
}
}

View file

@ -0,0 +1,502 @@
using System;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.Compatibility;
internal static class BusyCountHooks
{
// Fallback VAs (4,841,472-byte client). Pattern-scan is now the source of truth.
private const int IncrementBusyCountFallbackVa = 0x00565610;
private const int DecrementBusyCountFallbackVa = 0x00565630;
private const int UpdateCursorStateFallbackVa = 0x005653D0;
// ClientUISystem struct field offset for m_cBusy (confirmed via runtime dump)
private const int OffsetMCBusy = 0x14;
// ClientUISystem::IncrementBusyCount — entire function is short:
// mov edx,[ecx+14]; inc edx; mov eax,edx; cmp eax,1; mov [ecx+14],edx;
// jne +5; jmp UpdateCursorState; ret
private static readonly byte?[] IncrementBusyCountPattern =
[
0x8B, 0x51, 0x14, 0x42, 0x8B, 0xC2, 0x83, 0xF8,
0x01, 0x89, 0x51, 0x14, 0x75, 0x05,
0xE9, null, null, null, null, // jmp rel32 -> UpdateCursorState
0xC3
];
// ClientUISystem::DecrementBusyCount — also short:
// dec [ecx+14]; jne +5; jmp UpdateCursorState; ret
private static readonly byte?[] DecrementBusyCountPattern =
[
0xFF, 0x49, 0x14, 0x75, 0x05,
0xE9, null, null, null, null, // jmp rel32 -> UpdateCursorState
0xC3
];
// ClientUISystem::UpdateCursorState — large prologue with cmp/setcc pair.
private static readonly byte?[] UpdateCursorStatePattern =
[
0x83, 0xEC, 0x08, 0x53, 0x55, 0x56, 0x57, 0x89,
0x4C, 0x24, 0x10,
0xE8, null, null, null, null, // call rel32
0x85, 0xC0, 0x0F, 0x95, 0xC3, 0x33, 0xC0, 0x84,
0xDB
];
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void BusyCountDelegate(IntPtr thisPtr);
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void UpdateCursorStateDelegate(IntPtr thisPtr);
private static BusyCountDelegate? _originalIncrementBusyCount;
private static BusyCountDelegate? _incrementBusyCountDetour;
private static BusyCountDelegate? _originalDecrementBusyCount;
private static BusyCountDelegate? _decrementBusyCountDetour;
private static IntPtr _incrementTargetAddress;
private static IntPtr _decrementTargetAddress;
private static IntPtr _updateCursorStateAddress;
private static string _statusMessage = "Not probed yet.";
private static int _incrementDispatchCount;
private static int _decrementDispatchCount;
private static int _netBusyCount;
private static IntPtr _lastThisPtr;
public static bool IsInstalled { get; private set; }
public static string StatusMessage => _statusMessage;
/// <summary>Returns 0 if the character is idle, positive if a UI action is in progress.</summary>
public static int GetBusyState() => Math.Max(0, _netBusyCount);
/// <summary>
/// Force-reset the client's busy count to zero and re-evaluate the cursor.
/// <paramref name="clearMotion"/> additionally flushes the command
/// interpreter (ClearAllCommands/TakeControlFromServer/PlayerTeleported) —
/// ⚠ DANGEROUS and OFF by default: AC only runs that triplet inside full
/// teleport flows that also reset the physics sequence. Fired standalone
/// around a live gesture it can leave the player's CSequence with a null
/// current anim node → AC's next animation tick AVs at acclient 0x5264A9
/// reading null+0xC (CSequence::update_internal). Diagnosed live
/// 2026-06-11: the loot busy-watchdog called this every ~2s for an hour
/// (every corpse open leaks +1 m_cBusy) and one clear landed in the
/// gesture window. The busy UNSTICK itself only needs the decrement loop +
/// cursor refresh below. Even when requested, the motion flush is skipped
/// while a cast/action gesture is animating.
/// </summary>
// Session counters surfaced in the heartbeat so a soak shows the busy-fix
// machinery working: fcl = force-clears performed, rec = cast/item-action
// reconciles performed. A healthy post-fix soak should see rec climb during
// combat/looting and fcl stay near-flat (force-clear is now just a backstop).
private static long _forceClearCount;
private static long _reconcileCount;
public static long ForceClearCount => Interlocked.Read(ref _forceClearCount);
public static long ReconcileCount => Interlocked.Read(ref _reconcileCount);
// Off-thread force-reset requests latch here and are consumed by
// CheckWatchdog on the main thread (post-tick). ≤1 tick latency —
// irrelevant for a 2-5s watchdog; coalesces bursts for free.
private static int _forceResetRequested;
public static void ForceResetBusyCount(bool clearMotion = false)
{
// ⚠ MAIN THREAD ONLY (2026-06-12 cross-incident forensics, top-ranked
// corruption writer): the plugin host API called this raw from the
// pump thread 284-471×/session — up to 20 native DecrementBusyCount
// calls (each falling through into UpdateCursorState's UI/object-graph
// walk) plus a raw m_cBusy write, concurrent with AC's main thread.
// Leading suspect for the LFH heap detonation (ntdll+0x87D99, free()
// during object teardown, last off-thread clear ≤1s before the AV).
// Off-thread callers latch a request consumed post-tick instead.
if (!MainThreadGuard.IsOnMainThread())
{
Interlocked.Exchange(ref _forceResetRequested, 1);
return;
}
if (!IsInstalled || _lastThisPtr == IntPtr.Zero)
return;
Interlocked.Increment(ref _forceClearCount);
// Never mutate through a stale pointer: after logout/close AC frees the
// ClientUISystem singleton, and the decrement/cursor calls below would
// run native code against freed memory (uncatchable under NativeAOT).
if (!ClientObjectHooks.IsReadablePointer(_lastThisPtr + OffsetMCBusy))
{
RynthLog.Compat("BusyCountHooks: ForceResetBusyCount skipped — cached ClientUISystem pointer is no longer readable.");
_lastThisPtr = IntPtr.Zero;
return;
}
int was = _netBusyCount;
if (_originalDecrementBusyCount != null)
{
int calls = Math.Max(was, 3);
for (int i = 0; i < calls && i < 20; i++)
_originalDecrementBusyCount(_lastThisPtr);
}
Interlocked.Exchange(ref _netBusyCount, 0);
try { Marshal.WriteInt32(_lastThisPtr + OffsetMCBusy, 0); }
catch { /* non-fatal */ }
if (clearMotion)
{
bool gesture = false;
try { if (!PlayerPhysicsHooks.TryGetCastGestureInProgress(out gesture)) gesture = false; }
catch { gesture = false; }
if (gesture)
{
RynthLog.Compat("BusyCountHooks: motion flush SKIPPED — a gesture is animating (the CSequence-corruption window).");
}
else
{
CommandInterpreterHooks.ClearAllCommands();
CommandInterpreterHooks.TakeControlFromServer();
CommandInterpreterHooks.PlayerTeleported();
}
}
if (_updateCursorStateAddress != IntPtr.Zero)
{
try
{
var updateCursor = Marshal.GetDelegateForFunctionPointer<UpdateCursorStateDelegate>(_updateCursorStateAddress);
updateCursor(_lastThisPtr);
}
catch { /* non-fatal */ }
}
RynthLog.Verbose($"Compat: force-reset busy count (was {was})");
}
public static void Initialize()
{
if (IsInstalled)
return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
{
_statusMessage = "acclient.exe not available.";
return;
}
var inc = HookResolver.Resolve(textSection, "BusyCountHooks.IncrementBusyCount",
IncrementBusyCountPattern, IncrementBusyCountFallbackVa);
var dec = HookResolver.Resolve(textSection, "BusyCountHooks.DecrementBusyCount",
DecrementBusyCountPattern, DecrementBusyCountFallbackVa);
var cursor = HookResolver.Resolve(textSection, "BusyCountHooks.UpdateCursorState",
UpdateCursorStatePattern, UpdateCursorStateFallbackVa);
if (cursor.Success) _updateCursorStateAddress = cursor.Address;
if (!inc.Success || !dec.Success)
{
_statusMessage = $"Resolve failed — increment={inc.Detail}, decrement={dec.Detail}.";
RynthLog.Compat($"BusyCountHooks: {_statusMessage}");
return;
}
try
{
_incrementTargetAddress = inc.Address;
_incrementBusyCountDetour = IncrementBusyCountDetour;
IntPtr incrementDetourPtr = Marshal.GetFunctionPointerForDelegate(_incrementBusyCountDetour);
_originalIncrementBusyCount = Marshal.GetDelegateForFunctionPointer<BusyCountDelegate>(
MinHook.HookCreate(_incrementTargetAddress, incrementDetourPtr));
_decrementTargetAddress = dec.Address;
_decrementBusyCountDetour = DecrementBusyCountDetour;
IntPtr decrementDetourPtr = Marshal.GetFunctionPointerForDelegate(_decrementBusyCountDetour);
_originalDecrementBusyCount = Marshal.GetDelegateForFunctionPointer<BusyCountDelegate>(
MinHook.HookCreate(_decrementTargetAddress, decrementDetourPtr));
Thread.MemoryBarrier();
MinHook.Enable(_incrementTargetAddress);
MinHook.Enable(_decrementTargetAddress);
IsInstalled = true;
_statusMessage = $"Hooked busy-count seams (inc=0x{_incrementTargetAddress.ToInt32():X8}, dec=0x{_decrementTargetAddress.ToInt32():X8}).";
RynthLog.Compat($"BusyCountHooks: hooks installed.");
}
catch (Exception ex)
{
_statusMessage = ex.Message;
RynthLog.Compat($"BusyCountHooks: install threw {ex.GetType().Name}: {ex.Message}");
}
}
private static int _incFires, _decFires;
// ── Auto-watchdog: force-clear busy if it stays >0 too long ──────────
// Engine-side safety net so the bot self-heals when its busy tracking
// desyncs from AC's m_cBusy (e.g., a hook miss, RDP-eaten chat input
// preventing the user from running /ra clearbusy manually, or AC's
// own busy state going stuck after a server-rejected action).
//
// Trigger: any of our main-thread detours can call CheckWatchdog().
// SmartBoxHooks.DispatchGameEventDetour wires this in — it fires
// frequently on AC's main thread while in-world, so the watchdog
// gets a tick at least every server event.
//
// Heuristic: if busy has been positive for > BusyWatchdogTimeoutMs
// with no transitions back to zero, fire ForceResetBusyCount. We
// do this regardless of why it got stuck — combat-urgent or not —
// because the alternative is an inert bot.
private static long _busyBecamePositiveTickMs;
private static long _lastWatchdogFireTickMs;
private const long BusyWatchdogTimeoutMs = 5_000;
private const long BusyWatchdogCooldownMs = 2_000;
// Real-field watchdog. The shadow counter (_netBusyCount) DESYNCS from AC's
// real m_cBusy whenever AC mutates the field through a path we don't hook (or
// a detour is missed): the counter drifts to ~0 while the real field stays
// pinned > 0. A pinned real m_cBusy makes AC LOCALLY refuse combat-mode
// changes (its SetCombatMode never even fires) and casts ("You're too
// busy!") — wedging the bot in NonCombat (can't re-enter Magic to buff/fight)
// with NEITHER counter-based watchdog firing, because the counter says idle.
// So the watchdog must also trust the REAL field, read straight from
// [ClientUISystem + OffsetMCBusy]. (Diagnosed 2026-06-09: SetCombatMode
// stopped firing for 30+ min while ChangeCombatMode was re-sent and 191
// "too busy" refusals piled up, yet zero force-clears — classic desync.)
private static long _realBusyPositiveTickMs;
private const long RealBusyWatchdogTimeoutMs = 4_000;
private static int ReadRealBusy()
{
IntPtr p = _lastThisPtr;
if (p == IntPtr.Zero) return -1;
// The try/catch below cannot catch a non-null-page AV under NativeAOT
// (only null-page faults map to NullReferenceException). If AC freed
// the ClientUISystem singleton (logout/close teardown) a stale pointer
// read is fail-fast — probe the page first. TOCTOU-narrow but this is
// a watchdog: skipping one beat is free.
if (!ClientObjectHooks.IsReadablePointer(p + OffsetMCBusy)) return -1;
try { return Marshal.ReadInt32(p + OffsetMCBusy); }
catch { return -1; }
}
/// <summary>
/// Drop the cached ClientUISystem pointer at logout / client-close so the
/// watchdog and ForceResetBusyCount can't touch a freed singleton (the
/// 0x0056547B close-AV class). The increment/decrement detours re-capture
/// it on the next legit AC call.
/// </summary>
public static void ResetSession()
{
_lastThisPtr = IntPtr.Zero;
Volatile.Write(ref _realBusyPositiveTickMs, 0);
_pendingCastBusyDelta = 0;
_pendingCastGestureSeen = false;
}
// ── Direct-action busy reconciliation (source fix for the per-action leak) ──
// The engine's direct AC calls — casts (FreeHandsAndCastSpell / CastSpell)
// AND item actions (UseObject corpse-open / equip / item-use, UseObjectOn) —
// make AC increment m_cBusy synchronously, but they never register the queued
// action whose completion handler performs the matching decrements (that
// lives in the player-initiated flow we bypass). Result: EVERY such call
// leaked busy, caught only downstream by watchdogs (casts: 4322 plugin-side
// clears in one 10h soak; corpse opens: a force-clear every ~2s during loot
// grinds). Source fix: measure the real m_cBusy delta synchronously around
// the call (both run on AC's main thread, nothing interleaves, so the delta
// is exactly ours), then once the action GESTURE has completed
// ([CMI+0x80] empties — a use-reach is a sequenced motion just like a cast
// wind-up) — or after a timeout if it never starts (server refusal) — invoke
// the REAL DecrementBusyCount exactly delta times through the HOOKED entry,
// so the shadow counter and plugin busy events stay in sync. Deterministic,
// no ClearAllCommands side effects, never touches counts owned by others.
// A single accumulator serves both casts and item actions (all are
// engine-issued busy that should clear at the next gesture-end).
private static int _pendingCastBusyDelta;
private static long _pendingCastIssuedAtMs;
private static bool _pendingCastGestureSeen;
private static int _reconcileLogCount;
private const long CastBusyReconcileTimeoutMs = 4_000;
/// <summary>Snapshot the real m_cBusy immediately before a direct cast/item-action call (-1 = unreadable).</summary>
public static int CaptureRealBusyForCast() => ReadRealBusy();
/// <summary>
/// Arm reconciliation right after a direct cast/item-action call, given the
/// pre-call snapshot. Main thread only (these calls already run there).
/// </summary>
public static void NoteDirectCastIssued(int busyBefore)
{
if (busyBefore < 0) return;
int after = ReadRealBusy();
if (after < 0) return;
int delta = after - busyBefore;
if (delta <= 0) return;
_pendingCastBusyDelta += delta;
_pendingCastIssuedAtMs = Environment.TickCount64;
_pendingCastGestureSeen = false;
}
private static void ReconcileCastBusy(long now)
{
int pending = _pendingCastBusyDelta;
if (pending <= 0) return;
bool gesture = false;
try { if (!PlayerPhysicsHooks.TryGetCastGestureInProgress(out gesture)) gesture = false; }
catch { gesture = false; }
if (gesture)
{
// Cast animation running — completion is the decrement point.
_pendingCastGestureSeen = true;
return;
}
// Decrement once the observed gesture has ENDED, or after the timeout
// when no gesture was ever seen (refused cast / instant failure). The
// timeout matches the real-field watchdog window, so worst case this
// path is no slower than the old crutch.
if (!_pendingCastGestureSeen && now - _pendingCastIssuedAtMs <= CastBusyReconcileTimeoutMs)
return;
_pendingCastBusyDelta = 0;
_pendingCastGestureSeen = false;
IntPtr p = _lastThisPtr;
if (p == IntPtr.Zero || _decrementTargetAddress == IntPtr.Zero) return;
if (!ClientObjectHooks.IsReadablePointer(p + OffsetMCBusy)) return;
// Clamp to the live field — if AC (or a watchdog) already cleared part
// of it, never push m_cBusy negative.
int real = ReadRealBusy();
int n = Math.Min(pending, real);
if (n <= 0) return;
try
{
// Call the HOOKED decrement entry (not the trampoline): our detour
// fires, so _netBusyCount and the plugin busy-decremented events
// stay consistent for free.
var dec = Marshal.GetDelegateForFunctionPointer<BusyCountDelegate>(_decrementTargetAddress);
for (int i = 0; i < n; i++) dec(p);
Interlocked.Increment(ref _reconcileCount);
if (_reconcileLogCount < 50 || _reconcileLogCount % 100 == 0)
RynthLog.Compat($"BusyCountHooks: direct-action busy reconciled — decremented {n} (real now {ReadRealBusy()}, total reconciles {_reconcileLogCount + 1}).");
_reconcileLogCount++;
}
catch { }
}
/// <summary>
/// Auto-clear busy state if it has been positive for too long.
/// Safe to call from any thread; only performs work on AC's main
/// thread (via MainThreadGuard) since ForceResetBusyCount writes
/// AC memory and calls AC functions that aren't thread-safe.
/// </summary>
public static void CheckWatchdog()
{
long now = Environment.TickCount64;
// ── Real-field watchdog (catches counter desync) ─────────────────────
// Trust AC's REAL m_cBusy over our shadow counter: when they diverge a
// pinned real field is what actually wedges the client (mode-change /
// cast refusal) while _netBusyCount reads ~0 and the counter watchdog
// below never fires. A legit action returns the field to 0 within ~2-3s
// (resetting the timer); only a genuinely stuck field reaches the 4s
// timeout. Field read is harmless off-thread, but ForceResetBusyCount
// mutates AC, so only clear on the main thread.
if (MainThreadGuard.IsOnMainThread())
{
// Reconcile our own cast increments FIRST — a clean deterministic
// decrement here means the stuck-field watchdog below (and the
// plugin-side clears) have nothing left to catch.
ReconcileCastBusy(now);
// Consume any off-thread force-reset request (plugin watchdogs):
// the actual clear runs HERE, on the main thread.
if (Interlocked.Exchange(ref _forceResetRequested, 0) == 1)
ForceResetBusyCount();
int realBusy = ReadRealBusy();
if (realBusy > 0)
{
long sinceR = Volatile.Read(ref _realBusyPositiveTickMs);
if (sinceR == 0)
{
Volatile.Write(ref _realBusyPositiveTickMs, now);
}
else if (now - sinceR > RealBusyWatchdogTimeoutMs
&& now - Volatile.Read(ref _lastWatchdogFireTickMs) > BusyWatchdogCooldownMs)
{
Volatile.Write(ref _lastWatchdogFireTickMs, now);
RynthLog.Compat($"BusyCountHooks: REAL m_cBusy stuck at {realBusy} for {now - sinceR}ms (counter={_netBusyCount}) — force-clearing desync.");
ForceResetBusyCount();
Volatile.Write(ref _realBusyPositiveTickMs, 0);
Volatile.Write(ref _busyBecamePositiveTickMs, 0);
return;
}
}
else
{
// 0 = idle; -1 = unreadable (no pointer / freed page). Either
// way disarm the timer — leaving it armed across an unreadable
// stretch caused an instant force-clear when reads resumed
// (e.g. first beat after the next login).
Volatile.Write(ref _realBusyPositiveTickMs, 0);
}
}
// ── Counter-based watchdog (original) ────────────────────────────────
long stuckSince = Volatile.Read(ref _busyBecamePositiveTickMs);
if (stuckSince == 0)
return;
long elapsed = now - stuckSince;
if (elapsed < BusyWatchdogTimeoutMs)
return;
if (!MainThreadGuard.IsOnMainThread())
return;
long lastFire = Volatile.Read(ref _lastWatchdogFireTickMs);
if (now - lastFire < BusyWatchdogCooldownMs)
return;
Volatile.Write(ref _lastWatchdogFireTickMs, now);
RynthLog.Compat($"BusyCountHooks: watchdog auto-resetting — busy stuck at {_netBusyCount} for {elapsed}ms.");
ForceResetBusyCount();
Volatile.Write(ref _busyBecamePositiveTickMs, 0);
}
private static void IncrementBusyCountDetour(IntPtr thisPtr)
{
RecursionGuard.Tick("BusyCountHooks.Increment");
_lastThisPtr = thisPtr;
if (++_incFires <= 3)
RynthLog.Compat($"BusyCountHooks: Increment fired #{_incFires} this=0x{thisPtr.ToInt32():X8}");
try { _originalIncrementBusyCount!(thisPtr); }
catch (Exception ex) { try { RynthLog.Compat($"BusyCountHooks: Increment original threw {ex.GetType().Name}: {ex.Message}"); } catch { } throw; }
Interlocked.Increment(ref _incrementDispatchCount);
int after = Interlocked.Increment(ref _netBusyCount);
if (after == 1)
Volatile.Write(ref _busyBecamePositiveTickMs, Environment.TickCount64);
PluginManager.QueueBusyCountIncremented();
}
private static void DecrementBusyCountDetour(IntPtr thisPtr)
{
RecursionGuard.Tick("BusyCountHooks.Decrement");
if (_lastThisPtr == IntPtr.Zero)
_lastThisPtr = thisPtr;
if (++_decFires <= 3)
RynthLog.Compat($"BusyCountHooks: Decrement fired #{_decFires} this=0x{thisPtr.ToInt32():X8}");
try { _originalDecrementBusyCount!(thisPtr); }
catch (Exception ex) { try { RynthLog.Compat($"BusyCountHooks: Decrement original threw {ex.GetType().Name}: {ex.Message}"); } catch { } throw; }
Interlocked.Increment(ref _decrementDispatchCount);
int after = Interlocked.Decrement(ref _netBusyCount);
if (after <= 0)
Volatile.Write(ref _busyBecamePositiveTickMs, 0);
PluginManager.QueueBusyCountDecremented();
}
}

View file

@ -0,0 +1,220 @@
using System;
using System.Runtime.InteropServices;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Enumerates AC's authoritative world-object table via CObjectMaint.
///
/// Primary use: seed PluginManager._liveObjects on hot-reload, since the new
/// engine module's static state starts empty after a reload. Walking the
/// maintainer gives an immediate snapshot of every weenie the client knows
/// about so we can replay create-object events to a freshly loaded plugin
/// without waiting for new spawn/visibility events.
///
/// Secondary use: reconciliation / drift detection — even on cold start, if
/// any CreateObject hook fires miss the live-object set the maintainer is
/// authoritative and catches the omission.
///
/// Singleton: CObjectMaint::s_pcInstance @ 0x00842ADC (CObjectMaint**)
///
/// CObjectMaint layout (from Chorizite acclient.map + struct defs):
/// +0x00 Interface a0 (vtable*, 4)
/// +0x04 NoticeHandler a1 (vtable*, 4)
/// +0x08 Turbine_RefCount (vtable + m_cRef, 8)
/// +0x10 is_active (Int32, 4)
/// +0x14 lost_cell_table (IntrusiveHashTable, 112)
/// +0x84 object_table (LongHash&lt;CPhysicsObj&gt;, 24)
/// +0x9C null_object_table (LongHash&lt;CPhysicsObj&gt;, 24)
/// +0xB4 weenie_object_table (LongHash&lt;CWeenieObject&gt;, 24)
///
/// HashBase&lt;UInt32&gt; layout (LongHash wraps this):
/// +0 vfptr
/// +4 table_mask
/// +8 key_shift
/// +12 buckets (HashBaseData&lt;UInt32&gt;**)
/// +16 table_size
/// +20 fPlacementNew_
///
/// HashBaseData&lt;UInt32&gt; layout:
/// +0 vfptr
/// +4 hash_next
/// +8 id (UInt32)
/// </summary>
internal static class CObjectMaintHooks
{
private const int S_PC_INSTANCE_VA = 0x00842ADC;
private const int WEENIE_OBJECT_TABLE_OFFSET = 0xB4;
// DIAGNOSTIC (temporary): the CPhysicsObj table — superset of physics
// objects, including ones whose weenie isn't registered in
// weenie_object_table yet (the suspected missing-monster set).
private const int OBJECT_TABLE_OFFSET = 0x84;
private const int HASHBASE_BUCKETS_OFFSET = 12;
private const int HASHBASE_TABLE_SIZE_OFFSET = 16;
private const int HASHBASEDATA_HASH_NEXT_OFFSET = 4;
private const int HASHBASEDATA_ID_OFFSET = 8;
// Sanity bounds — table_size larger than this almost certainly means
// we're reading garbage (real AC tables are typically 1k-8k buckets).
private const int MaxBuckets = 65536;
private const int MaxChainPerBucket = 1024;
/// <summary>
/// Walks CObjectMaint::weenie_object_table and invokes <paramref name="visit"/> for each
/// known object id. Returns the number of ids visited, or -1 if the maintainer or
/// table layout couldn't be read safely.
/// </summary>
public static int EnumerateLiveWeenieObjectIds(Action<uint> visit)
{
if (visit == null) return -1;
IntPtr maintainer = ReadMaintainer();
if (maintainer == IntPtr.Zero)
return -1;
IntPtr tablePtr = maintainer + WEENIE_OBJECT_TABLE_OFFSET;
if (!SmartBoxLocator.IsMemoryReadable(tablePtr + HASHBASE_BUCKETS_OFFSET, 4))
return -1;
IntPtr buckets = Marshal.ReadIntPtr(tablePtr + HASHBASE_BUCKETS_OFFSET);
if (buckets == IntPtr.Zero)
return -1;
if (!SmartBoxLocator.IsMemoryReadable(tablePtr + HASHBASE_TABLE_SIZE_OFFSET, 4))
return -1;
uint tableSize = (uint)Marshal.ReadInt32(tablePtr + HASHBASE_TABLE_SIZE_OFFSET);
if (tableSize == 0 || tableSize > MaxBuckets)
return -1;
int count = 0;
try
{
for (uint i = 0; i < tableSize; i++)
{
IntPtr bucketSlot = buckets + (int)(i * 4);
if (!SmartBoxLocator.IsMemoryReadable(bucketSlot, 4))
break;
IntPtr node = Marshal.ReadIntPtr(bucketSlot);
int chainGuard = 0;
while (node != IntPtr.Zero && chainGuard++ < MaxChainPerBucket)
{
if (!SmartBoxLocator.IsMemoryReadable(node + HASHBASEDATA_ID_OFFSET, 4))
break;
uint id = (uint)Marshal.ReadInt32(node + HASHBASEDATA_ID_OFFSET);
if (id != 0)
{
visit(id);
count++;
}
if (!SmartBoxLocator.IsMemoryReadable(node + HASHBASEDATA_HASH_NEXT_OFFSET, 4))
break;
node = Marshal.ReadIntPtr(node + HASHBASEDATA_HASH_NEXT_OFFSET);
}
}
}
catch (Exception ex)
{
RynthLog.Compat($"CObjectMaint enumerate threw {ex.GetType().Name}: {ex.Message}");
return count > 0 ? count : -1;
}
return count;
}
// DIAGNOSTIC (temporary): same walk as EnumerateLiveWeenieObjectIds but over
// an arbitrary CObjectMaint table (object_table +0x84 / null_object_table
// +0x9C / weenie_object_table +0xB4). Duplicated rather than refactoring the
// tested enumerator. Remove with the diagnostic.
public static int EnumerateTableIds(int tableOffset, Action<uint> visit)
{
if (visit == null) return -1;
IntPtr maintainer = ReadMaintainer();
if (maintainer == IntPtr.Zero)
return -1;
IntPtr tablePtr = maintainer + tableOffset;
if (!SmartBoxLocator.IsMemoryReadable(tablePtr + HASHBASE_BUCKETS_OFFSET, 4))
return -1;
IntPtr buckets = Marshal.ReadIntPtr(tablePtr + HASHBASE_BUCKETS_OFFSET);
if (buckets == IntPtr.Zero)
return -1;
if (!SmartBoxLocator.IsMemoryReadable(tablePtr + HASHBASE_TABLE_SIZE_OFFSET, 4))
return -1;
uint tableSize = (uint)Marshal.ReadInt32(tablePtr + HASHBASE_TABLE_SIZE_OFFSET);
if (tableSize == 0 || tableSize > MaxBuckets)
return -1;
int count = 0;
try
{
for (uint i = 0; i < tableSize; i++)
{
IntPtr bucketSlot = buckets + (int)(i * 4);
if (!SmartBoxLocator.IsMemoryReadable(bucketSlot, 4))
break;
IntPtr node = Marshal.ReadIntPtr(bucketSlot);
int chainGuard = 0;
while (node != IntPtr.Zero && chainGuard++ < MaxChainPerBucket)
{
if (!SmartBoxLocator.IsMemoryReadable(node + HASHBASEDATA_ID_OFFSET, 4))
break;
uint id = (uint)Marshal.ReadInt32(node + HASHBASEDATA_ID_OFFSET);
if (id != 0)
{
visit(id);
count++;
}
if (!SmartBoxLocator.IsMemoryReadable(node + HASHBASEDATA_HASH_NEXT_OFFSET, 4))
break;
node = Marshal.ReadIntPtr(node + HASHBASEDATA_HASH_NEXT_OFFSET);
}
}
}
catch (Exception ex)
{
RynthLog.Compat($"CObjectMaint object-table enumerate threw {ex.GetType().Name}: {ex.Message}");
return count > 0 ? count : -1;
}
return count;
}
// Phase B: resolve s_pcInstance's address by code-xref ("mov ecx,[s_pcInstance]" =
// 8B 0D <addr>), operand at offset 2; the VA stays as fallback. Resolved lazily once.
private static readonly byte?[] PatXrefInstancePP = [ 0x8B, 0x0D, null, null, null, null, 0x55, 0xE8 ];
private static int _instancePPAddr;
private static int InstancePPAddr()
{
if (_instancePPAddr == 0)
{
_instancePPAddr = S_PC_INSTANCE_VA;
if (AcClientModule.TryReadTextSection(out AcClientTextSection text))
_instancePPAddr = HookResolver.ResolveData(text, "CObjectMaint.s_pcInstance", PatXrefInstancePP, 2, S_PC_INSTANCE_VA).Address.ToInt32();
}
return _instancePPAddr;
}
private static IntPtr ReadMaintainer()
{
IntPtr instancePP = new IntPtr(InstancePPAddr());
if (!SmartBoxLocator.IsMemoryReadable(instancePP, 4))
return IntPtr.Zero;
IntPtr maintainer = Marshal.ReadIntPtr(instancePP);
if (maintainer == IntPtr.Zero)
return IntPtr.Zero;
if (!SmartBoxLocator.IsMemoryReadable(maintainer, 4))
return IntPtr.Zero;
IntPtr vtable = Marshal.ReadIntPtr(maintainer);
if (!SmartBoxLocator.IsPointerInModule(vtable))
return IntPtr.Zero;
return maintainer;
}
}

View file

@ -0,0 +1,89 @@
using System;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// The real spell-cast gate for RynthAi buff/combat recasts.
///
/// Problem: AC refuses a cast issued while the player is mid cast-gesture
/// animation with a server-driven "You're too busy!" text notice. A tight
/// clear-and-recast retry loop on that refusal re-enters AC's AddTextToScroll
/// and produces the visible 0x00460D1D write-AV after long uptime.
///
/// AC's ClientUISystem busy-count (<see cref="BusyCountHooks"/>) is the
/// hourglass/cursor state, NOT the cast gate — it reads 0 while AC still says
/// "too busy". The true LOCAL gate is the cast GESTURE: CMotionInterp's
/// sequenced/one-shot motion queue is non-empty while the wind-up/release
/// animates and empties when it completes (offline RE of acclient.exe; see
/// <see cref="PlayerPhysicsHooks.TryGetCastGestureInProgress"/>).
///
/// This is a SAMPLED gate — no acclient.exe hook is installed. <see cref="Sample"/>
/// runs on the existing 30 Hz NormalPluginPump heartbeat (PluginManager.TickAll)
/// and reads a single CMotionInterp scalar through the already-proven
/// PlayerPhysicsHooks accessor. No new detour, no pattern-scan-and-call (the
/// ACE crash class), no list walk (UAF-safe). The consumer polls the gate at
/// the same tick rate, so the busy→idle edge is observed without any new
/// engine→plugin callback (avoids the NativeAOT reverse-P/Invoke crash class).
/// </summary>
internal static class CastGate
{
private static int _castBusy; // 0 = clear to cast, 1 = gesture in progress
private static int _reachable; // 1 once CMotionInterp has ever been read
private static long _gestureCount;
private static string _statusMessage = "Not sampled yet.";
public static bool IsInitialized => Volatile.Read(ref _reachable) == 1;
public static string StatusMessage => _statusMessage;
/// <summary>Number of cast/action gestures observed completing this session.</summary>
public static long GestureCount => Interlocked.Read(ref _gestureCount);
/// <summary>
/// 0 = clear to cast, 1 = a cast/action gesture is in progress. Mirrors
/// <see cref="BusyCountHooks.GetBusyState"/> for the host-API pull path.
/// </summary>
public static int GetCastBusyState() => Volatile.Read(ref _castBusy);
/// <summary>
/// Sampled from the 30 Hz plugin pump (PluginManager.TickAll). Cheap, fully
/// guarded, never throws. If CMotionInterp isn't reachable (pre-login /
/// between worlds) the gate reports "clear to cast" so the consumer falls
/// back to its own throttle/park, which is the hard anti-spam guarantee.
/// </summary>
public static void Sample()
{
try
{
if (!PlayerPhysicsHooks.TryGetCastGestureInProgress(out bool inProgress))
{
Volatile.Write(ref _castBusy, 0);
return;
}
Volatile.Write(ref _reachable, 1);
int was = Volatile.Read(ref _castBusy);
int now = inProgress ? 1 : 0;
if (now == was)
return;
Volatile.Write(ref _castBusy, now);
if (now == 1)
{
_statusMessage = "Cast gesture in progress.";
}
else
{
Interlocked.Increment(ref _gestureCount);
_statusMessage = "Ready (gate open).";
}
}
catch
{
// The gate must never destabilise the pump. Default to clear-to-cast;
// the consumer's throttle still bounds retries.
Volatile.Write(ref _castBusy, 0);
}
}
}

View file

@ -0,0 +1,710 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Globalization;
using System.Text.Json;
using System.Threading;
using RynthCore.App;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Captures the character list from the 0xF658 server packet, persists it per-account,
/// and optionally performs a native auto-login sequence with click fallback.
/// </summary>
internal static class CharacterCaptureHooks
{
private const uint PostConnectReadyOpcode = 0x0000F7EA;
private const uint CharacterListOpcode = 0x0000F658;
private const int NetBlobBufPtrOffset = 0x2C;
private const int NetBlobBufSizeOffset = 0x30;
// Auto-login click geometry (matches ThwargFilter LoginCharacterTools)
private const uint WM_LBUTTONDOWN = 0x0201;
private const uint WM_LBUTTONUP = 0x0202;
private const uint WM_MOUSEMOVE = 0x0200;
private const int XCharList = 121;
private const int YTopOfBox = 209;
private const int YBottomOfBox = 532;
private const int AutoLoginDelayMs = 2000;
private const int AutoLoginWindowWaitMs = 10000;
private const int AutoLoginWindowPollMs = 250;
private const int AutoLoginAttempts = 15;
private const int AutoLoginAttemptDelayMs = 600;
private const int AutoLoginDoubleClickGapMs = 100;
private const int DirectAutoLoginAttempts = 40;
private const int DirectAutoLoginAttemptDelayMs = 250;
private const int CharacterManagementUIMode = 0x1000000A;
private const int GamePlayUIMode = 0x10000008;
// Poll-driven auto-login. The packet-driven path (ScheduleAutoLoginIfRequested,
// fed by InnerDispatcherDetour) is dead on this client: InnerDispatcherHook was
// disabled 2026-05-14 because its pattern walk-back stalls ACE in "Entering
// World", and SmartBox does not carry the pre-login 0xF658 char-list packet.
// Result: zero CharacterCapture activity, auto-login never fired. This poll
// drives login off the native CharacterSet directly (CharacterManagementHooks),
// which needs no packet — it just watches the UIFlow mode and retries until
// login completes. Replaces the dead trigger; the packet path is left intact
// (harmless, never invoked) in case InnerDispatcher is ever re-enabled.
private const int AutoLoginPollIntervalMs = 600;
private const int AutoLoginPollHardTimeoutMs = 120_000;
private const int AutoLoginDirectFailsBeforeClick = 4;
private static int _autoLoginPollStarted;
private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
[DllImport("user32.dll")]
private static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
[DllImport("kernel32.dll")]
private static extern uint GetCurrentProcessId();
[DllImport("user32.dll")]
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsWindowVisible(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
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;
/// <summary>
/// Starts the poll-driven auto-login worker. Call once from InitWorker.
/// No-ops if no TargetCharacter is configured in the launch context, or if
/// the worker is already running. Safe to call before the client window or
/// char-select UI exists — the worker waits for them.
/// </summary>
public static void Initialize()
{
(_, _, string targetCharacter) = ReadLaunchContext();
if (string.IsNullOrWhiteSpace(targetCharacter))
{
RynthLog.Verbose("CharacterCapture: Initialize - no TargetCharacter in launch context; auto-login disabled.");
return;
}
if (Interlocked.Exchange(ref _autoLoginPollStarted, 1) != 0)
return;
var thread = new Thread(AutoLoginPollLoop)
{
Name = "RynthCore.AutoLoginPoll",
IsBackground = true
};
thread.Start();
RynthLog.Info($"CharacterCapture: Poll-driven auto-login armed for '{targetCharacter}'.");
}
/// <summary>
/// Watches the native UIFlow mode and drives LogOnCharacter directly off
/// AC's native CharacterSet. Retries every tick while char-select is up,
/// so a too-early attempt or a missed click just gets re-tried — until
/// login completes, the client enters the world, or the hard timeout hits.
/// Hard-stops the instant mode==GamePlayUI or LoginComplete is observed:
/// poking LogOn pointers while in-game has been correlated with AC self-
/// exiting (see ScheduleAutoLoginIfRequested's notes).
/// </summary>
private static void AutoLoginPollLoop()
{
(_, _, string targetCharacter) = ReadLaunchContext();
if (string.IsNullOrWhiteSpace(targetCharacter))
return;
long charSelectFirstSeenTick = 0;
int directFailCount = 0;
bool issuedDirect = false;
try
{
while (true)
{
Thread.Sleep(AutoLoginPollIntervalMs);
if (LoginLifecycleHooks.HasObservedLoginComplete)
{
RynthLog.Info($"CharacterCapture: Auto-login complete for '{targetCharacter}' (LoginComplete observed).");
Interlocked.Exchange(ref _autoLoginEverFired, 1);
return;
}
// One-shot: if the (currently dead) packet path ever fires and
// latches, stand down so we don't double-drive.
if (Volatile.Read(ref _autoLoginEverFired) != 0)
{
RynthLog.Verbose($"CharacterCapture: Poll standing down for '{targetCharacter}' - auto-login already fired elsewhere.");
return;
}
if (!CharacterManagementHooks.TryGetCurrentMode(out int mode))
continue; // UIFlow not ready yet — keep waiting.
if (mode == GamePlayUIMode)
{
RynthLog.Compat($"CharacterCapture: Poll stopping for '{targetCharacter}' - client already in GamePlayUI.");
Interlocked.Exchange(ref _autoLoginEverFired, 1);
return;
}
if (mode != CharacterManagementUIMode)
{
// Still in connect/logo/transition — don't start the timeout
// clock until char-select has actually appeared.
continue;
}
if (charSelectFirstSeenTick == 0)
{
charSelectFirstSeenTick = Environment.TickCount64;
RynthLog.Info($"CharacterCapture: Char-select up — driving direct auto-login for '{targetCharacter}'.");
}
// Direct path: read AC's native CharacterSet and call LogOnCharacter.
// No packet required. Retries every tick if it didn't take.
if (CharacterManagementHooks.TryLogOnCharacter(
targetCharacter, out string matched, out uint avatarId, out int slotIndex, out string status))
{
if (!issuedDirect)
{
issuedDirect = true;
RynthLog.Info($"CharacterCapture: Issued LogOnCharacter for '{matched}' (target '{targetCharacter}', avatar 0x{avatarId:X8}). Awaiting world entry.");
}
directFailCount = 0;
// Keep looping — watch for LoginComplete/GamePlayUI. If the
// issue didn't take, next ticks will re-issue.
}
else
{
directFailCount++;
RynthLog.Verbose($"CharacterCapture: Direct auto-login attempt {directFailCount} for '{targetCharacter}' - {status}");
// Direct keeps failing (native set not readable / name not
// matched yet). Fall back to a char-list double-click, but
// only when we know the slot — slotIndex is set when the
// name matched in the native set; otherwise use the packet-
// cached index is unavailable here so skip until known.
if (directFailCount >= AutoLoginDirectFailsBeforeClick && slotIndex >= 0)
{
int slotCount = CharacterManagementHooks.GetNativeCharacterSetSlotCount();
if (slotCount > 0)
TryClickCharacterSlot(targetCharacter, slotIndex, slotCount);
directFailCount = 0;
}
}
if (charSelectFirstSeenTick != 0 &&
Environment.TickCount64 - charSelectFirstSeenTick > AutoLoginPollHardTimeoutMs)
{
RynthLog.Compat($"CharacterCapture: Auto-login for '{targetCharacter}' gave up after {AutoLoginPollHardTimeoutMs / 1000}s at char-select. Last status: {status}");
return;
}
}
}
catch (Exception ex)
{
RynthLog.Compat($"CharacterCapture: Auto-login poll loop crashed - {ex.Message}");
}
finally
{
Interlocked.Exchange(ref _autoLoginPollStarted, 0);
}
}
/// <summary>
/// Single char-list double-click at the slot for <paramref name="slotIndex"/>.
/// Fallback for when the direct native LogOnCharacter path isn't taking.
/// </summary>
private static void TryClickCharacterSlot(string targetCharacter, int slotIndex, int slotCount)
{
try
{
if (CharacterManagementHooks.TryGetCurrentMode(out int m) && m == GamePlayUIMode)
return;
IntPtr hwnd = WaitForGameWindow();
if (hwnd == IntPtr.Zero)
return;
SetForegroundWindow(hwnd);
float nameSize = (YBottomOfBox - YTopOfBox) / (float)slotCount;
int yOffset = (int)(YTopOfBox + (nameSize / 2.0f) + (nameSize * slotIndex));
RynthLog.Verbose($"CharacterCapture: Click fallback for '{targetCharacter}' at slot {slotIndex}/{slotCount} ({XCharList},{yOffset}).");
PostMouseClick(hwnd, XCharList, yOffset);
Thread.Sleep(AutoLoginDoubleClickGapMs);
PostMouseClick(hwnd, XCharList, yOffset);
}
catch (Exception ex)
{
RynthLog.Compat($"CharacterCapture: Click fallback threw - {ex.Message}");
}
}
public static void ProcessPotentialCharacterMessage(IntPtr blob, bool isGameEvent = false)
{
if (blob == IntPtr.Zero)
return;
try
{
uint blobSize = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(blob, NetBlobBufSizeOffset)));
if (blobSize < 4)
return;
IntPtr payloadPtr = Marshal.ReadIntPtr(IntPtr.Add(blob, NetBlobBufPtrOffset));
if (payloadPtr == IntPtr.Zero)
return;
uint opcode = unchecked((uint)Marshal.ReadInt32(payloadPtr));
if (opcode == PostConnectReadyOpcode)
{
RynthLog.Verbose($"CharacterCapture: [{(isGameEvent ? "GameEvent" : "SmartBox")}] Observed post-connect packet (0xF7EA).");
LogoBypassHooks.NotifyPostConnectObserved();
return;
}
if (opcode != CharacterListOpcode)
return;
RynthLog.Verbose($"CharacterCapture: [{(isGameEvent ? "GameEvent" : "SmartBox")}] Found CharacterList (0xF658)!");
LogoBypassHooks.NotifyCharacterListObserved();
(List<string> characters, int slotCount) = ParseAndSaveCharacterList(payloadPtr, blobSize);
ScheduleAutoLoginIfRequested(characters, slotCount);
}
catch (Exception ex)
{
RynthLog.Compat($"CharacterCapture: Error: {ex.Message}");
}
}
/// <summary>
/// Called from InnerDispatcherDetour where the buffer is a raw pre-login message (no blob wrapper).
/// The first 4 bytes are the opcode.
/// </summary>
public static void ProcessRawCharacterMessage(IntPtr buffer, uint size)
{
if (buffer == IntPtr.Zero || size < 4)
return;
try
{
uint opcode = unchecked((uint)Marshal.ReadInt32(buffer));
if (opcode == PostConnectReadyOpcode)
{
RynthLog.Verbose("CharacterCapture: [InnerDispatcher] Observed post-connect packet (0xF7EA).");
LogoBypassHooks.NotifyPostConnectObserved();
return;
}
if (opcode != CharacterListOpcode)
return;
RynthLog.Verbose("CharacterCapture: [InnerDispatcher] Processing 0xF658 raw buffer.");
LogoBypassHooks.NotifyCharacterListObserved();
(List<string> characters, int slotCount) = size >= 12
? ParseAndSaveCharacterList(buffer, size)
: (new List<string>(), 0);
ScheduleAutoLoginIfRequested(characters, slotCount);
}
catch (Exception ex)
{
RynthLog.Compat($"CharacterCapture: Raw error: {ex.Message}");
}
}
private static (List<string> characters, int slotCount) ParseAndSaveCharacterList(IntPtr payloadPtr, uint blobSize)
{
var characters = new List<string>();
int slotCount = 0;
try
{
int offset = 4; // Skip opcode
int characterCount = Marshal.ReadInt32(IntPtr.Add(payloadPtr, offset));
offset += 4;
if (characterCount < 0 || characterCount > 20)
{
RynthLog.Compat($"CharacterCapture: Implausible character count {characterCount} - skipping.");
return (characters, slotCount);
}
characters = new List<string>(characterCount);
// Deep-audit finding #28 (2026-06-18): this loop advanced offset
// (GUID, nameLen, name bytes, padding, timeout) and never compared
// it against blobSize — only nameLen itself was range-checked
// (1..127). A short/malformed blob (this server's own login
// response, so not adversarial, but still worth bounding) would
// walk past the buffer into whatever heap memory follows it.
// Bound every read against blobSize; break (not continue) on any
// overrun since offset is no longer trustworthy past that point.
for (int i = 0; i < characterCount; i++)
{
if (offset + 4 > blobSize) break; // GUID
offset += 4; // Skip Character GUID
if (offset + 2 > blobSize) break; // nameLen
short nameLen = Marshal.ReadInt16(IntPtr.Add(payloadPtr, offset));
offset += 2;
if (nameLen > 0 && nameLen < 128)
{
if (offset + nameLen > blobSize) break; // name bytes
byte[] nameBytes = new byte[nameLen];
Marshal.Copy(IntPtr.Add(payloadPtr, offset), nameBytes, 0, nameLen);
string name = Encoding.Default.GetString(nameBytes);
characters.Add(name);
}
offset += nameLen;
if (offset % 4 != 0)
offset += 4 - (offset % 4);
offset += 4; // Skip Delete Timeout
if (offset > blobSize)
{
offset = (int)blobSize; // cap so the slotCount read below can't overrun either
break;
}
}
characters.Sort(StringComparer.OrdinalIgnoreCase);
slotCount = (int)blobSize > offset + 3
? Marshal.ReadInt32(IntPtr.Add(payloadPtr, offset))
: characters.Count;
RynthLog.Info($"CharacterCapture: Parsed {characters.Count} chars ({slotCount} slots): {string.Join(", ", characters)}");
if (characters.Count > 0)
{
(string accountName, string serverName, _) = ReadLaunchContext();
SaveCharacterList(characters, accountName, serverName);
}
}
catch (Exception ex)
{
RynthLog.Compat($"CharacterCapture: Parse error: {ex.Message}");
}
return (characters, slotCount);
}
private static (string accountName, string serverName, string targetCharacter) ReadLaunchContext()
{
try
{
string rootDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"RynthCore");
string processPath = Path.Combine(rootDir, "launch_contexts", $"launch_context_{Environment.ProcessId}.json");
(string accountName, string serverName, string targetCharacter) processContext = ReadLaunchContextFile(processPath);
if (!string.IsNullOrWhiteSpace(processContext.accountName) ||
!string.IsNullOrWhiteSpace(processContext.serverName) ||
!string.IsNullOrWhiteSpace(processContext.targetCharacter))
{
return processContext;
}
SessionStateRecord? sessionHint = SessionStateStore.TryReadForProcess(Environment.ProcessId);
if (sessionHint != null &&
(!string.IsNullOrWhiteSpace(sessionHint.AccountName) ||
!string.IsNullOrWhiteSpace(sessionHint.ServerName) ||
!string.IsNullOrWhiteSpace(sessionHint.TargetCharacter)))
{
return (sessionHint.AccountName, sessionHint.ServerName, sessionHint.TargetCharacter);
}
return ReadLaunchContextFile(Path.Combine(rootDir, "launch_context.json"));
}
catch
{
return (string.Empty, string.Empty, string.Empty);
}
}
private static (string accountName, string serverName, string targetCharacter) ReadLaunchContextFile(string filePath)
{
if (!File.Exists(filePath))
return (string.Empty, string.Empty, string.Empty);
using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(filePath));
JsonElement root = doc.RootElement;
string accountName = root.TryGetProperty("AccountName", out JsonElement an) ? an.GetString() ?? string.Empty : string.Empty;
string serverName = root.TryGetProperty("ServerName", out JsonElement sn) ? sn.GetString() ?? string.Empty : string.Empty;
string target = root.TryGetProperty("TargetCharacter", out JsonElement tc) ? tc.GetString() ?? string.Empty : string.Empty;
return (accountName, serverName, target);
}
private static void SaveCharacterList(List<string> characters, string accountName, string serverName)
{
try
{
if (!string.IsNullOrWhiteSpace(accountName))
{
CharacterCacheStore.Write(accountName, serverName, characters);
RynthLog.Verbose(
!string.IsNullOrWhiteSpace(serverName)
? $"CharacterCapture: Saved {characters.Count} chars for '{accountName}' on '{serverName}'."
: $"CharacterCapture: Saved {characters.Count} chars for '{accountName}' (no server name in context).");
}
else
{
RynthLog.Info("CharacterCapture: Character list observed but no account name was available; character cache not written.");
}
}
catch (Exception ex)
{
RynthLog.Info($"CharacterCapture: Save error: {ex.Message}");
}
}
private static void ScheduleAutoLoginIfRequested(List<string> characters, int slotCount)
{
(_, _, string targetCharacter) = ReadLaunchContext();
if (string.IsNullOrWhiteSpace(targetCharacter))
return;
// If the client is already past character-select, do NOT schedule any
// auto-login work. The 0xF658 character-list packet can arrive in
// transitional states (logout-to-char-select, hot-reload replay, etc.),
// and starting a 10-second polling loop that pokes at native LogOn
// pointers while the player is in-game has been correlated with AC
// self-exiting via MSVCR70 a few seconds later.
if (LoginLifecycleHooks.HasObservedLoginComplete)
{
RynthLog.Verbose($"CharacterCapture: Skipping auto-login schedule for '{targetCharacter}' - login already complete.");
Interlocked.Exchange(ref _autoLoginEverFired, 1);
return;
}
if (CharacterManagementHooks.TryGetCurrentMode(out int currentMode) && currentMode == 0x10000008 /* GamePlayUI */)
{
RynthLog.Compat($"CharacterCapture: Skipping auto-login schedule for '{targetCharacter}' - client is already in GamePlayUI.");
Interlocked.Exchange(ref _autoLoginEverFired, 1);
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;
List<string> fallbackCharacters = characters.Count > 0
? new List<string>(characters)
: [];
int finalSlots = slotCount > 0 ? slotCount : fallbackCharacters.Count;
int fallbackIndex = fallbackCharacters.FindIndex(c => CharacterManagementHooks.CharacterNamesMatch(c, targetCharacter));
int logoDelayMs = LogoBypassHooks.GetRecommendedAutoLoginDelayMs();
int scheduledDelayMs = Math.Max(AutoLoginDelayMs, logoDelayMs);
var thread = new Thread(() =>
{
try
{
Thread.Sleep(scheduledDelayMs);
PerformAutoLogin(fallbackCharacters, finalSlots, targetCharacter);
}
finally
{
Interlocked.Exchange(ref _autoLoginScheduled, 0);
}
})
{
Name = "RynthCore.AutoLogin",
IsBackground = true
};
thread.Start();
RynthLog.Verbose(
fallbackIndex >= 0
? $"CharacterCapture: Auto-login scheduled for '{targetCharacter}' in {scheduledDelayMs}ms (native direct login first, fallback slot index {fallbackIndex}, logoDelay={logoDelayMs}ms)."
: $"CharacterCapture: Auto-login scheduled for '{targetCharacter}' in {scheduledDelayMs}ms (native direct login only so far, logoDelay={logoDelayMs}ms).");
}
private static void PerformAutoLogin(List<string> fallbackCharacters, int slotCount, string targetCharacter)
{
string lastDirectStatus = "Direct login did not run.";
for (int attempt = 1; attempt <= DirectAutoLoginAttempts; attempt++)
{
if (LoginLifecycleHooks.HasObservedLoginComplete)
{
RynthLog.Verbose($"CharacterCapture: Auto-login for '{targetCharacter}' skipped because login is already complete.");
return;
}
// Hard early-out: if the client has already entered GamePlayUI, the player
// is in the world. Continuing to poll TryLogOnCharacter (which keeps
// dereferencing UIFlow + PlayerSystem pointers) has been correlated with
// AC self-exiting via MSVCR70 ~20s later. Treat this as "done", not a
// failure to be retried.
if (CharacterManagementHooks.TryGetCurrentMode(out int gpMode) && gpMode == 0x10000008 /* GamePlayUI */)
{
RynthLog.Compat($"CharacterCapture: Auto-login for '{targetCharacter}' aborted on attempt {attempt}/{DirectAutoLoginAttempts} - client is already in GamePlayUI. Last direct status: {lastDirectStatus}");
return;
}
if (CharacterManagementHooks.TryLogOnCharacter(targetCharacter, out string matchedCharacter, out uint avatarId, out string directStatus))
{
RynthLog.Verbose(
$"CharacterCapture: Direct auto-login succeeded for '{matchedCharacter}' (target '{targetCharacter}', avatar 0x{avatarId:X8}) on attempt {attempt}/{DirectAutoLoginAttempts}.");
return;
}
lastDirectStatus = directStatus;
// Belt-and-braces: TryLogOnCharacter itself reports "Client is already in
// GamePlayUI" when mode==GamePlayUI. If we somehow raced past the
// pre-call mode check above, still bail on the status.
if (directStatus.IndexOf("already in GamePlayUI", StringComparison.OrdinalIgnoreCase) >= 0)
{
RynthLog.Compat($"CharacterCapture: Auto-login for '{targetCharacter}' aborted on attempt {attempt}/{DirectAutoLoginAttempts} - {directStatus}");
return;
}
if (attempt < DirectAutoLoginAttempts)
Thread.Sleep(DirectAutoLoginAttemptDelayMs);
}
RynthLog.Compat($"CharacterCapture: Direct auto-login did not succeed for '{targetCharacter}' - {lastDirectStatus}");
int index = fallbackCharacters.FindIndex(c => CharacterManagementHooks.CharacterNamesMatch(c, targetCharacter));
if (index < 0 || slotCount <= 0)
{
RynthLog.Compat($"CharacterCapture: No click fallback is available for '{targetCharacter}' after direct login failure.");
return;
}
// Final guard: the click fallback drives a foreground window via PostMessage.
// If, by the time we reach the fallback, the client is in GamePlayUI (eg the
// user clicked through during the retry window), do NOT spam clicks at the
// game viewport.
if (CharacterManagementHooks.TryGetCurrentMode(out int fbMode) && fbMode == 0x10000008 /* GamePlayUI */)
{
RynthLog.Compat($"CharacterCapture: Skipping click fallback for '{targetCharacter}' - client is already in GamePlayUI.");
return;
}
IntPtr hwnd = WaitForGameWindow();
if (hwnd == IntPtr.Zero)
{
RynthLog.Compat($"CharacterCapture: Auto-login for '{targetCharacter}' - no visible game window found, skipping.");
return;
}
SetForegroundWindow(hwnd);
float nameSize = (YBottomOfBox - YTopOfBox) / (float)slotCount;
int yOffset = (int)(YTopOfBox + (nameSize / 2.0f) + (nameSize * index));
for (int attempt = 1; attempt <= AutoLoginAttempts; attempt++)
{
// Login made it through (either by our earlier click or by the user) — stop clicking.
if (LoginLifecycleHooks.HasObservedLoginComplete)
{
RynthLog.Verbose($"CharacterCapture: Click fallback for '{targetCharacter}' aborted on attempt {attempt}/{AutoLoginAttempts} - login complete.");
return;
}
if (CharacterManagementHooks.TryGetCurrentMode(out int clickMode) && clickMode == GamePlayUIMode)
{
RynthLog.Compat($"CharacterCapture: Click fallback for '{targetCharacter}' aborted on attempt {attempt}/{AutoLoginAttempts} - client is already in GamePlayUI.");
return;
}
// Only click while char-select is actually visible. The 0xF658 packet can arrive
// before the UI has transitioned (logos still dismissing, etc.) — wasting clicks
// outside char-select is what made earlier runs "give up too soon."
bool charSelectReady = CharacterManagementHooks.TryGetCurrentMode(out int curMode) && curMode == CharacterManagementUIMode;
if (!charSelectReady)
{
RynthLog.Verbose($"CharacterCapture: Click fallback waiting for char-select UI on attempt {attempt}/{AutoLoginAttempts} (mode=0x{curMode:X8}).");
Thread.Sleep(AutoLoginAttemptDelayMs);
continue;
}
RynthLog.Verbose($"CharacterCapture: Auto-login attempt {attempt}/{AutoLoginAttempts} for '{targetCharacter}' at ({XCharList}, {yOffset}).");
PostMouseClick(hwnd, XCharList, yOffset);
Thread.Sleep(AutoLoginDoubleClickGapMs);
PostMouseClick(hwnd, XCharList, yOffset);
if (attempt < AutoLoginAttempts)
Thread.Sleep(AutoLoginAttemptDelayMs);
}
RynthLog.Verbose($"CharacterCapture: Auto-login double-click sequence complete for '{targetCharacter}'.");
}
private static IntPtr WaitForGameWindow()
{
uint pid = GetCurrentProcessId();
int elapsedMs = 0;
while (elapsedMs < AutoLoginWindowWaitMs)
{
IntPtr hwnd = FindVisibleProcessWindow(pid);
if (hwnd != IntPtr.Zero)
return hwnd;
Thread.Sleep(AutoLoginWindowPollMs);
elapsedMs += AutoLoginWindowPollMs;
}
return IntPtr.Zero;
}
private static IntPtr FindVisibleProcessWindow(uint pid)
{
IntPtr found = IntPtr.Zero;
EnumWindows((hWnd, _) =>
{
GetWindowThreadProcessId(hWnd, out uint windowPid);
if (windowPid == pid && IsWindowVisible(hWnd))
{
found = hWnd;
return false;
}
return true;
}, IntPtr.Zero);
return found;
}
private static IntPtr MakeLParam(int x, int y) =>
(IntPtr)unchecked((uint)((y << 16) | (x & 0xFFFF)));
private static void PostMouseClick(IntPtr hwnd, int x, int y)
{
IntPtr lParam = MakeLParam(x, y);
PostMessage(hwnd, WM_MOUSEMOVE, IntPtr.Zero, lParam);
PostMessage(hwnd, WM_LBUTTONDOWN, (IntPtr)0x0001, lParam);
Thread.Sleep(80);
PostMessage(hwnd, WM_LBUTTONUP, IntPtr.Zero, lParam);
}
}

View file

@ -0,0 +1,355 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace RynthCore.Engine.Compatibility;
internal static class CharacterManagementHooks
{
private const int UIFlowInstanceVa = 0x0083E72C;
private const int PlayerSystemVa = 0x0087119C;
// Phase B: resolve the two data globals by code-xref (operand at offset 2); VAs stay fallback.
private static readonly byte?[] PatXrefUIFlow = [ 0x51, 0xA1, null, null, null, null, 0x8B, 0x4C ];
private static readonly byte?[] PatXrefCPlayerSystem = [ 0xC7, 0x05, null, null, null, null, 0x00, 0x00, 0x00, 0x00, 0x83, 0xC6 ];
private static int _uiFlowAddr = UIFlowInstanceVa;
private static int _playerSystemAddr = PlayerSystemVa;
private const int UIFlowCurModeOffset = 0x8C;
private const int UIFlowDataOffset = 0x98;
private const int UIPersistantDataCharacterSetOffset = 0x04;
private const int CharacterManagementUI = 0x1000000A;
private const int GamePlayUI = 0x10000008;
private const int MaxCharacterSlots = 20;
private const int UIFlowGetPersistantDataVa = 0x0051DFB0;
private const int GetPlayerSystemVa = 0x0055E1D0;
private const int LogOnCharacterVa = 0x00560600;
private const int CharacterSetGetIdentityVa = 0x004E8B20;
private const int CharacterSetGetNameVa = 0x004FE980;
private const int CharacterSetGetGidVa = 0x004FE9B0;
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate IntPtr UIFlowGetPersistantDataDelegate(IntPtr uiFlowPtr);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr GetPlayerSystemDelegate();
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate byte LogOnCharacterDelegate(IntPtr playerSystemPtr, uint avatarId);
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate IntPtr CharacterSetGetIdentityDelegate(IntPtr charSetPtr, int index);
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate IntPtr CharacterSetGetNameDelegate(IntPtr charSetPtr, int index);
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate uint CharacterSetGetGidDelegate(IntPtr charSetPtr, int index);
private static readonly object BindLock = new();
private static bool _bindAttempted;
private static bool _bound;
private static string _statusMessage = "Not bound.";
private static UIFlowGetPersistantDataDelegate? _uiFlowGetPersistantData;
private static GetPlayerSystemDelegate? _getPlayerSystem;
private static LogOnCharacterDelegate? _logOnCharacter;
private static CharacterSetGetIdentityDelegate? _characterSetGetIdentity;
private static CharacterSetGetNameDelegate? _characterSetGetName;
private static CharacterSetGetGidDelegate? _characterSetGetGid;
// ── Pattern-resolved binding (1a hardening, 2026-06-05) ─────────────
// The *Va consts above are FALLBACKs; these signatures (verified unique + landing exactly
// at the VA offline via tools/pe_pattern.py) are the source of truth, surviving AC-patch /
// ACE-rebuild drift. GetName/GetGid are sibling accessors differing only in a trailing
// field offset (0x08 vs 0x04) — pinned literally to stay unique.
private static readonly byte?[] PatUIFlowGetPersistantData = [ 0x8B, 0x81, 0x98, 0x00, 0x00, 0x00, 0xC3, 0x90 ];
private static readonly byte?[] PatGetPlayerSystem = [ 0xA1, 0x9C, 0x11, 0x87, 0x00, 0xC3, 0x90, 0x90 ];
private static readonly byte?[] PatLogOnCharacter = [ 0x56, 0x8B, 0xF1, 0x8A, 0x86, 0x10, 0x02, 0x00 ];
private static readonly byte?[] PatCharacterSetGetIdentity = [ 0x8B, 0x44, 0x24, 0x04, 0x3B, 0x41, 0x14, 0x73, 0x0F ];
private static readonly byte?[] PatCharacterSetGetName = [ 0x8B, 0x44, 0x24, 0x04, 0x3B, 0x41, 0x14, 0x73, 0x13, 0x8B, 0x49, 0x0C, 0xC1, 0xE0, 0x04, 0x03, 0xC1, 0x8B, 0x48, 0x04, 0x85, 0xC9, 0x74, 0x04, 0x85, 0xC0, 0x75, 0x05, 0x33, 0xC0, 0xC2, 0x04, 0x00, 0x8B, 0x40, 0x08 ];
private static readonly byte?[] PatCharacterSetGetGid = [ 0x8B, 0x44, 0x24, 0x04, 0x3B, 0x41, 0x14, 0x73, 0x13, 0x8B, 0x49, 0x0C, 0xC1, 0xE0, 0x04, 0x03, 0xC1, 0x8B, 0x48, 0x04, 0x85, 0xC9, 0x74, 0x04, 0x85, 0xC0, 0x75, 0x05, 0x33, 0xC0, 0xC2, 0x04, 0x00, 0x8B, 0x40, 0x04 ];
private static T? Bind<T>(AcClientTextSection text, string name, byte?[] pattern, int fallbackVa) where T : Delegate
{
HookResolver.ResolveResult r = HookResolver.Resolve(text, name, pattern, fallbackVa);
return r.Success ? Marshal.GetDelegateForFunctionPointer<T>(r.Address) : null;
}
public static string StatusMessage => _statusMessage;
public static bool TryGetCurrentMode(out int mode)
{
mode = 0;
IntPtr uiFlowPtr = GetUiFlowPointer();
if (uiFlowPtr == IntPtr.Zero)
return false;
mode = Marshal.ReadInt32(IntPtr.Add(uiFlowPtr, UIFlowCurModeOffset));
return true;
}
public static bool TryLogOnCharacter(string targetCharacter, out string matchedCharacter, out uint avatarId, out string status)
=> TryLogOnCharacter(targetCharacter, out matchedCharacter, out avatarId, out _, out status);
/// <summary>
/// Same as the 4-arg overload, but also reports the matched character's
/// slot index in AC's native CharacterSet (-1 when no match was found).
/// The slot index is what the click fallback in CharacterCaptureHooks
/// needs to compute the y-offset for the character-list double-click.
/// </summary>
public static bool TryLogOnCharacter(string targetCharacter, out string matchedCharacter, out uint avatarId, out int slotIndex, out string status)
{
matchedCharacter = string.Empty;
avatarId = 0;
slotIndex = -1;
if (string.IsNullOrWhiteSpace(targetCharacter))
{
status = "No target character requested.";
return false;
}
if (!EnsureBound())
{
status = _statusMessage;
return false;
}
bool hasMode = TryGetCurrentMode(out int mode);
if (hasMode && mode == GamePlayUI)
{
status = "Client is already in GamePlayUI.";
return false;
}
IntPtr charSetPtr = GetCharacterSetPointer();
if (charSetPtr == IntPtr.Zero)
{
status = hasMode
? mode == CharacterManagementUI
? "CharacterManagementUI is active, but the character set is not available yet."
: $"Current UI mode is 0x{mode:X8}; character set is not available yet."
: "UIFlow/character set is not available yet.";
return false;
}
var availableCharacters = new List<string>();
for (int index = 0; index < MaxCharacterSlots; index++)
{
IntPtr identityPtr = _characterSetGetIdentity!(charSetPtr, index);
if (identityPtr == IntPtr.Zero)
continue;
IntPtr namePtr = _characterSetGetName!(charSetPtr, index);
string? candidateName = ReadAnsiString(namePtr);
uint candidateAvatarId = _characterSetGetGid!(charSetPtr, index);
if (string.IsNullOrWhiteSpace(candidateName) || candidateAvatarId == 0)
continue;
availableCharacters.Add(candidateName);
// Admin/staff character names render with a leading '+' in the AC
// client UI but the cached/launcher-side name often lacks it (or the
// server packet does). Match prefix-tolerantly so 'Buffi' matches
// '+Buffi' and vice versa.
if (!CharacterNamesMatch(candidateName, targetCharacter))
continue;
slotIndex = index;
IntPtr playerSystemPtr = GetPlayerSystemPointer();
if (playerSystemPtr == IntPtr.Zero)
{
status = "Player system is not available yet.";
return false;
}
byte result = _logOnCharacter!(playerSystemPtr, candidateAvatarId);
if (result == 0)
{
status = hasMode
? $"LogOnCharacter rejected avatar 0x{candidateAvatarId:X8} ('{candidateName}') while mode=0x{mode:X8}."
: $"LogOnCharacter rejected avatar 0x{candidateAvatarId:X8} ('{candidateName}').";
return false;
}
matchedCharacter = candidateName;
avatarId = candidateAvatarId;
status = $"Issued LogOnCharacter for avatar 0x{candidateAvatarId:X8}.";
return true;
}
status = availableCharacters.Count > 0
? $"Target '{targetCharacter}' not found in native character set [{string.Join(", ", availableCharacters)}]."
: "Native character set is empty or not ready yet.";
return false;
}
/// <summary>
/// Returns the count of populated character slots in AC's native
/// CharacterSet (slots where GetIdentity returns non-null). Used by the
/// click fallback in CharacterCaptureHooks when the 0xF658 packet parser
/// produced an empty list — typical on ACE where the packet shape differs
/// from retail.
/// </summary>
public static int GetNativeCharacterSetSlotCount()
{
if (!EnsureBound())
return 0;
IntPtr charSetPtr = GetCharacterSetPointer();
if (charSetPtr == IntPtr.Zero)
return 0;
int count = 0;
for (int index = 0; index < MaxCharacterSlots; index++)
{
IntPtr identityPtr;
try { identityPtr = _characterSetGetIdentity!(charSetPtr, index); }
catch { return count; }
if (identityPtr != IntPtr.Zero)
count++;
}
return count;
}
/// <summary>
/// Compares two AC character names tolerantly of the leading '+' that the
/// client adds to admin/staff names. e.g. 'Buffi' matches '+Buffi'.
/// </summary>
internal static bool CharacterNamesMatch(string? a, string? b)
{
string lhs = (a ?? string.Empty).Trim().TrimStart('+');
string rhs = (b ?? string.Empty).Trim().TrimStart('+');
return lhs.Length > 0 && string.Equals(lhs, rhs, StringComparison.OrdinalIgnoreCase);
}
private static bool EnsureBound()
{
lock (BindLock)
{
if (_bindAttempted)
return _bound;
_bindAttempted = true;
try
{
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
{
_bound = false;
_statusMessage = "acclient .text not readable for pattern resolve.";
RynthLog.Compat($"CharacterManagement: bind failed - {_statusMessage}");
return _bound;
}
_uiFlowGetPersistantData = Bind<UIFlowGetPersistantDataDelegate>(text, "CharMgmt.UIFlowGetPersistantData", PatUIFlowGetPersistantData, UIFlowGetPersistantDataVa);
_getPlayerSystem = Bind<GetPlayerSystemDelegate>(text, "CharMgmt.GetPlayerSystem", PatGetPlayerSystem, GetPlayerSystemVa);
_logOnCharacter = Bind<LogOnCharacterDelegate>(text, "CharMgmt.LogOnCharacter", PatLogOnCharacter, LogOnCharacterVa);
_characterSetGetIdentity = Bind<CharacterSetGetIdentityDelegate>(text, "CharMgmt.CharacterSetGetIdentity", PatCharacterSetGetIdentity, CharacterSetGetIdentityVa);
_characterSetGetName = Bind<CharacterSetGetNameDelegate>(text, "CharMgmt.CharacterSetGetName", PatCharacterSetGetName, CharacterSetGetNameVa);
_characterSetGetGid = Bind<CharacterSetGetGidDelegate>(text, "CharMgmt.CharacterSetGetGid", PatCharacterSetGetGid, CharacterSetGetGidVa);
_uiFlowAddr = HookResolver.ResolveData(text, "CharMgmt.UIFlow", PatXrefUIFlow, 2, UIFlowInstanceVa).Address.ToInt32();
_playerSystemAddr = HookResolver.ResolveData(text, "CharMgmt.CPlayerSystem", PatXrefCPlayerSystem, 2, PlayerSystemVa).Address.ToInt32();
_bound = _uiFlowGetPersistantData != null && _getPlayerSystem != null && _logOnCharacter != null
&& _characterSetGetIdentity != null && _characterSetGetName != null && _characterSetGetGid != null;
_statusMessage = _bound ? "Bound." : "One or more character-management addresses failed to resolve.";
if (_bound)
RynthLog.Verbose("CharacterManagement: Bound UIFlow and direct LogOnCharacter entry points.");
else
RynthLog.Compat($"CharacterManagement: bind incomplete - {_statusMessage}");
}
catch (Exception ex)
{
_bound = false;
_statusMessage = ex.Message;
RynthLog.Compat($"CharacterManagement: Failed to bind native entry points - {ex.Message}");
}
return _bound;
}
}
private static IntPtr GetUiFlowPointer()
{
try
{
return Marshal.ReadIntPtr(new IntPtr(_uiFlowAddr));
}
catch
{
return IntPtr.Zero;
}
}
private static IntPtr GetCharacterSetPointer()
{
IntPtr uiFlowPtr = GetUiFlowPointer();
if (uiFlowPtr == IntPtr.Zero)
return IntPtr.Zero;
IntPtr persistantDataPtr = IntPtr.Zero;
try
{
persistantDataPtr = _uiFlowGetPersistantData!(uiFlowPtr);
}
catch
{
persistantDataPtr = IntPtr.Zero;
}
if (persistantDataPtr == IntPtr.Zero)
{
try
{
persistantDataPtr = Marshal.ReadIntPtr(IntPtr.Add(uiFlowPtr, UIFlowDataOffset));
}
catch
{
persistantDataPtr = IntPtr.Zero;
}
}
return persistantDataPtr != IntPtr.Zero
? IntPtr.Add(persistantDataPtr, UIPersistantDataCharacterSetOffset)
: IntPtr.Zero;
}
private static IntPtr GetPlayerSystemPointer()
{
try
{
IntPtr playerSystemPtr = _getPlayerSystem!();
if (playerSystemPtr != IntPtr.Zero)
return playerSystemPtr;
}
catch
{
// Fall back to the known global if the helper call is unavailable.
}
try
{
return Marshal.ReadIntPtr(new IntPtr(_playerSystemAddr));
}
catch
{
return IntPtr.Zero;
}
}
private static string? ReadAnsiString(IntPtr ptr)
{
if (ptr == IntPtr.Zero)
return null;
try
{
return Marshal.PtrToStringAnsi(ptr);
}
catch
{
return null;
}
}
}

View file

@ -0,0 +1,649 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.Compatibility;
internal static class ChatCallbackHooks
{
private enum IncomingChatMode
{
WrapperQueuedText,
WrapperQueuedTextHostEat,
AddTextToScrollHostEat
}
private const int PsRefBufferWideDataOffset = 20;
private const int MaxIncomingChatChars = 1024;
private const int IncomingChatAddTextToScrollVa = 0x005649F0;
private const int IncomingChatWrapperVa = 0x0058A000;
private const int OutgoingChatVa = 0x005821A0;
private const bool EnableIncomingHook = true;
private const bool EnableOutgoingHook = true;
private static IncomingChatMode CurrentIncomingMode => IncomingChatMode.AddTextToScrollHostEat;
// Verified unique + lands at 0x005649F0 offline (tools/pe_pattern.py).
private static readonly byte?[] IncomingChatAddTextToScrollPattern =
[
0x81, 0xEC, 0x48, 0x09, 0x00, 0x00, 0x8A, 0x84
];
// Verified unique + lands at 0x0058A000 offline (tools/pe_pattern.py).
private static readonly byte?[] IncomingChatWrapperPattern =
[
0xA1, 0xE4, 0x0B, 0x87, 0x00, 0x85, 0xC0, 0x75,
0x06, 0xB8, 0x01, 0x00, 0x00, 0x00, 0xC3, 0x56
];
private static readonly byte?[] OutgoingChatPattern =
[
0x83, 0xEC, 0x0C, 0x53, 0x55, 0x56, 0x57, 0x8B,
0xF9, 0xE8, null, null, null, null, 0x85, 0xC0,
0x8B, 0x74, 0x24, 0x20, 0x74, 0x30, 0x8B, 0x06,
0x50, 0xFF, 0x15, null, null, null, null, 0x8B,
0xD8, 0xC7, 0x44, 0x24, 0x20, 0x00, 0x00, 0x00,
0x00, 0xE8, null, null, null, null, 0x8B, 0x08,
0x8D, 0x54, 0x24, 0x20, 0x52, 0x53, 0x50, 0xFF,
0x51, 0x20, 0x8B, 0x44, 0x24, 0x20, 0x85, 0xC0,
0x0F, 0x85, null, null, null, null, 0x8B, 0x44,
0x24, 0x24, 0x6A, 0x00
];
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate int IncomingChatWrapperDelegate(int flags, IntPtr text, int chatChannel);
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate int OutgoingChatDelegate(IntPtr thisPtr, IntPtr text, uint commandSource);
private static IncomingChatWrapperDelegate? _originalIncomingChatWrapper;
private static IncomingChatWrapperDelegate? _incomingChatWrapperDetour;
private static OutgoingChatDelegate? _originalOutgoingChat;
private static OutgoingChatDelegate? _outgoingChatDetour;
private static IntPtr _incomingAddress;
private static IntPtr _originalIncomingChatAddTextPtr;
private static IntPtr _outgoingAddress;
private static IntPtr _outgoingChatTrampolinePtr;
private static string _statusMessage = "Not probed yet.";
private static int _incomingChatSuppressionEnabled;
private static int _incomingCallCount;
// Captured live from the outgoing-chat detour so we can re-invoke AC's outgoing
// chat function DIRECTLY (deterministic) instead of simulating keystrokes into
// the native chat bar. Keystroke simulation depends on the bar's open/closed
// state, which the first simulated send corrupts — so the second send silently
// fails to submit ("works once, then stops"). Calling the function directly has
// no chat-bar state and is fully repeatable.
private static IntPtr _lastOutgoingThis;
private static uint _lastOutgoingSource = 8;
public static bool IncomingInstalled { get; private set; }
public static bool OutgoingInstalled { get; private set; }
public static bool IsInstalled => (!EnableIncomingHook || IncomingInstalled) && (!EnableOutgoingHook || OutgoingInstalled);
public static string StatusMessage => _statusMessage;
public static bool IsOutgoingHookReady => OutgoingInstalled && _originalOutgoingChat != null;
internal static IntPtr OutgoingAddress => _outgoingAddress;
public static void SetIncomingChatSuppression(bool enabled)
{
Interlocked.Exchange(ref _incomingChatSuppressionEnabled, enabled ? 1 : 0);
}
public static void Initialize()
{
if (IsInstalled)
return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
{
_statusMessage = "acclient.exe not available.";
return;
}
try
{
string incomingMode = GetIncomingModeLabel(CurrentIncomingMode);
string incomingStatus = EnableIncomingHook ? "unavailable" : "disabled";
string outgoingStatus = EnableOutgoingHook ? "unavailable" : "disabled";
bool incomingVerified = !EnableIncomingHook;
if (EnableIncomingHook && !IncomingInstalled)
IncomingInstalled = TryInstallIncomingHook(textSection, out incomingStatus);
if (IncomingInstalled)
{
incomingVerified = true;
incomingStatus = $"0x{_incomingAddress.ToInt32():X8} ({incomingMode})";
}
if (EnableOutgoingHook && !OutgoingInstalled)
{
if (TryResolveOutgoingOffset(textSection, incomingVerified, out int outgoingOff, out string outgoingResolution))
{
try
{
_outgoingAddress = new IntPtr(textSection.TextBaseVa + outgoingOff);
_outgoingChatDetour = OutgoingChatDetour;
IntPtr outgoingPtr = Marshal.GetFunctionPointerForDelegate(_outgoingChatDetour);
_outgoingChatTrampolinePtr = MinHook.HookCreate(_outgoingAddress, outgoingPtr);
_originalOutgoingChat = Marshal.GetDelegateForFunctionPointer<OutgoingChatDelegate>(_outgoingChatTrampolinePtr);
Thread.MemoryBarrier();
MinHook.Enable(_outgoingAddress);
OutgoingInstalled = true;
outgoingStatus = $"0x{_outgoingAddress.ToInt32():X8} ({outgoingResolution})";
}
catch (Exception ex)
{
outgoingStatus = $"hook failed ({ex.Message})";
RynthLog.Compat($"Compat: outgoing chat hook unavailable - {ex.Message}");
}
}
else
{
outgoingStatus = outgoingResolution;
if (!outgoingResolution.StartsWith("skipped", StringComparison.Ordinal))
RynthLog.Compat($"Compat: outgoing chat hook unavailable - {outgoingResolution}");
}
}
if (OutgoingInstalled && !outgoingStatus.StartsWith("0x", StringComparison.Ordinal))
outgoingStatus = $"0x{_outgoingAddress.ToInt32():X8}";
if (!IncomingInstalled && !OutgoingInstalled)
{
_statusMessage = $"No chat hooks installed. incoming={incomingStatus}, outgoing={outgoingStatus}.";
RynthLog.Compat($"Compat: chat callback hook failed - {_statusMessage}");
return;
}
_statusMessage = $"Ready. incoming={incomingStatus}, outgoing={outgoingStatus}.";
RynthLog.Verbose($"Compat: chat callback hooks ready - incoming={incomingStatus}, outgoing={outgoingStatus}");
}
catch (Exception ex)
{
_statusMessage = ex.Message;
RynthLog.Compat($"Compat: chat callback hook failed - {ex.Message}");
}
}
private static bool TryInstallIncomingHook(AcClientTextSection textSection, out string incomingStatus)
{
if (TryInstallPreferredIncomingHook(textSection, out incomingStatus))
return true;
if (CurrentIncomingMode is not IncomingChatMode.WrapperQueuedText and not IncomingChatMode.WrapperQueuedTextHostEat)
{
RynthLog.Verbose("Compat: preferred incoming chat seam unavailable - falling back to wrapper path.");
return TryInstallIncomingWrapperHook(textSection, out incomingStatus);
}
return false;
}
private static bool TryInstallPreferredIncomingHook(AcClientTextSection textSection, out string incomingStatus)
{
return CurrentIncomingMode switch
{
IncomingChatMode.AddTextToScrollHostEat => TryInstallIncomingAddTextHook(textSection, out incomingStatus),
IncomingChatMode.WrapperQueuedText => TryInstallIncomingWrapperHook(textSection, out incomingStatus),
IncomingChatMode.WrapperQueuedTextHostEat => TryInstallIncomingWrapperHook(textSection, out incomingStatus),
_ => TryInstallIncomingWrapperHook(textSection, out incomingStatus)
};
}
private static bool TryInstallIncomingWrapperHook(AcClientTextSection textSection, out string incomingStatus)
{
HookResolver.ResolveResult resolved = HookResolver.Resolve(textSection, "ChatCallback.IncomingChatWrapper", IncomingChatWrapperPattern, IncomingChatWrapperVa);
if (!resolved.Success)
{
incomingStatus = $"unresolved (VA 0x{IncomingChatWrapperVa:X8})";
RynthLog.Compat($"Compat: incoming chat hook unavailable - {incomingStatus}");
return false;
}
try
{
_incomingAddress = resolved.Address;
_incomingChatWrapperDetour = IncomingChatWrapperDetour;
IntPtr incomingPtr = Marshal.GetFunctionPointerForDelegate(_incomingChatWrapperDetour);
_originalIncomingChatWrapper = Marshal.GetDelegateForFunctionPointer<IncomingChatWrapperDelegate>(MinHook.HookCreate(_incomingAddress, incomingPtr));
Thread.MemoryBarrier();
MinHook.Enable(_incomingAddress);
incomingStatus = $"0x{_incomingAddress.ToInt32():X8} ({GetIncomingModeLabel(CurrentIncomingMode)})";
return true;
}
catch (Exception ex)
{
incomingStatus = $"hook failed ({ex.Message})";
RynthLog.Compat($"Compat: incoming chat hook unavailable - {ex.Message}");
return false;
}
}
private static bool TryInstallIncomingAddTextHook(AcClientTextSection textSection, out string incomingStatus)
{
HookResolver.ResolveResult resolved = HookResolver.Resolve(textSection, "ChatCallback.IncomingChatAddTextToScroll", IncomingChatAddTextToScrollPattern, IncomingChatAddTextToScrollVa);
if (!resolved.Success)
{
incomingStatus = $"unresolved (VA 0x{IncomingChatAddTextToScrollVa:X8})";
RynthLog.Compat($"Compat: incoming chat hook unavailable - {incomingStatus}");
return false;
}
try
{
unsafe
{
_incomingAddress = resolved.Address;
delegate* unmanaged[Thiscall]<IntPtr, IntPtr, uint, uint, IntPtr, int> pDetour = &IncomingChatAddTextDetour;
MinHook.Hook(_incomingAddress, (IntPtr)pDetour, out _originalIncomingChatAddTextPtr);
}
incomingStatus = $"0x{_incomingAddress.ToInt32():X8} ({GetIncomingModeLabel(CurrentIncomingMode)})";
return true;
}
catch (Exception ex)
{
incomingStatus = $"hook failed ({ex.Message})";
RynthLog.Compat($"Compat: incoming chat hook unavailable - {ex.Message}");
return false;
}
}
private static int IncomingChatWrapperDetour(int flags, IntPtr text, int chatChannel)
{
RecursionGuard.Tick("ChatCallbackHooks.IncomingChatWrapper");
try
{
return CurrentIncomingMode switch
{
IncomingChatMode.WrapperQueuedText => QueueIncomingAfterOriginal(flags, text, chatChannel),
IncomingChatMode.WrapperQueuedTextHostEat => QueueIncomingWithHostEat(flags, text, chatChannel),
_ => _originalIncomingChatWrapper!(flags, text, chatChannel)
};
}
catch (Exception ex)
{
try { RynthLog.Compat($"Compat: incoming wrapper detour error - {ex.GetType().Name}: {ex.Message}"); } catch { }
try { return _originalIncomingChatWrapper!(flags, text, chatChannel); } catch { return 0; }
}
}
// [UnmanagedCallersOnly] generates a true native thiscall entry point — no
// delegate thunk, no hidden GC-transition overhead that the delegate-based
// approach adds. This mirrors Chorizite's working ChatHooks pattern.
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
private static unsafe int IncomingChatAddTextDetour(IntPtr thisPtr, IntPtr text, uint chatType, uint unknown, IntPtr stringInfo)
{
RecursionGuard.Tick("ChatCallbackHooks.IncomingChatAddText");
// 1. Read string BEFORE original — buffer may be freed after
string? line = (text != IntPtr.Zero) ? ReadIncomingChatLine(text, chatType) : null;
// 2. Call original
var pOriginal = (delegate* unmanaged[Thiscall]<IntPtr, IntPtr, uint, uint, IntPtr, int>)_originalIncomingChatAddTextPtr;
int result = pOriginal(thisPtr, text, chatType, unknown, stringInfo);
// 3. Queue AFTER original returns — game state is consistent
if (line != null)
QueueIncomingChatLine(line, chatType);
return result;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static string? ReadIncomingChatLine(IntPtr pStringBase, uint chatType)
{
try
{
// PStringBase<ushort> is a 4-byte struct: a single pointer to
// PSRefBufferCharData<ushort>. The char data (m_data) starts at
// offset 0 in PSRefBufferCharData — no header fields before it.
IntPtr charData = Marshal.ReadIntPtr(pStringBase);
if (charData == IntPtr.Zero)
return null;
int length = 0;
while (length < MaxIncomingChatChars)
{
short ch = Marshal.ReadInt16(charData, length * 2);
if (ch == 0)
break;
length++;
}
string? line = length > 0
? Marshal.PtrToStringUni(charData, length)?.TrimEnd('\r', '\n')
: null;
int count = Interlocked.Increment(ref _incomingCallCount);
if (count <= 0)
RynthLog.Verbose($"Compat: incoming chat #{count} type={chatType} len={length}");
return line;
}
catch { return null; }
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void QueueIncomingChatLine(string line, uint chatType)
{
try { PluginManager.QueueChatWindowText(line, chatType); }
catch { }
}
private static int OutgoingChatDetour(IntPtr thisPtr, IntPtr text, uint commandSource)
{
RecursionGuard.Tick("ChatCallbackHooks.OutgoingChat");
try
{
string? line = ReadWidePString(text);
// Capture the chat-manager 'this' + command source from the live submit
// so ChatCommandDispatcher can re-invoke this function directly later.
if (thisPtr != IntPtr.Zero)
{
_lastOutgoingThis = thisPtr;
_lastOutgoingSource = commandSource;
}
// RynthCore engine commands (/rc ...) — consume before plugins or
// AC see the line so the user never broadcasts "/rc resetbar" and
// a hidden overlay bar stays recoverable.
if (RynthCoreChatCommands.TryHandle(line))
return 1;
if (PluginManager.DispatchChatBarEnter(line))
return 1;
return _originalOutgoingChat!(thisPtr, text, commandSource);
}
catch (Exception ex)
{
try { RynthLog.Compat($"Compat: outgoing chat detour error - {ex.GetType().Name}: {ex.Message}"); } catch { }
try { return _originalOutgoingChat!(thisPtr, text, commandSource); } catch { return 0; }
}
}
private static string? ReadWidePString(IntPtr pStringBase)
{
if (pStringBase == IntPtr.Zero)
return null;
try
{
IntPtr firstPtr = Marshal.ReadIntPtr(pStringBase);
if (firstPtr == IntPtr.Zero)
return null;
// Some seams hand us a WidePString whose first field already points at
// the wchar_t buffer. Others hand us a PSRefBuffer-backed PStringBase
// that needs the +0x14 data offset. Probe both and keep the more sane one.
string? direct = TryReadUtf16String(firstPtr);
string? buffered = TryReadUtf16String(firstPtr + PsRefBufferWideDataOffset);
return ChooseBestWideString(direct, buffered);
}
catch
{
return null;
}
}
private static string? TryReadUtf16String(IntPtr data)
{
if (data == IntPtr.Zero)
return null;
try
{
int length = 0;
while (length < MaxIncomingChatChars)
{
short ch = Marshal.ReadInt16(data, length * sizeof(char));
if (ch == 0)
break;
if (!IsLikelyWideChar((char)ch))
return null;
length++;
}
return length > 0 ? Marshal.PtrToStringUni(data, length) : string.Empty;
}
catch
{
return null;
}
}
private static string? ChooseBestWideString(string? direct, string? buffered)
{
int directScore = ScoreCandidate(direct);
int bufferedScore = ScoreCandidate(buffered);
if (directScore <= 0 && bufferedScore <= 0)
return direct ?? buffered;
return directScore >= bufferedScore ? direct : buffered;
}
private static int ScoreCandidate(string? value)
{
if (string.IsNullOrEmpty(value))
return 0;
int score = value.Length;
foreach (char ch in value)
{
if (char.IsLetterOrDigit(ch) || char.IsWhiteSpace(ch))
score += 2;
else if (ch is '/' or '-' or '_' or '.' or '\'')
score += 1;
else if (char.IsControl(ch))
score -= 8;
}
return score;
}
private static bool IsLikelyWideChar(char ch)
{
return !char.IsControl(ch) || ch is '\r' or '\n' or '\t';
}
private static int QueueIncomingAfterOriginal(int flags, IntPtr text, int chatChannel)
{
int result = _originalIncomingChatWrapper!(flags, text, chatChannel);
if (result != 0)
PluginManager.QueueChatWindowText(ReadWidePString(text), unchecked((uint)chatChannel));
return result;
}
private static int QueueIncomingWithHostEat(int flags, IntPtr text, int chatChannel)
{
string? line = ReadWidePString(text);
if (Volatile.Read(ref _incomingChatSuppressionEnabled) != 0)
{
PluginManager.QueueChatWindowText(line, unchecked((uint)chatChannel));
return 1;
}
int result = _originalIncomingChatWrapper!(flags, text, chatChannel);
if (result != 0)
PluginManager.QueueChatWindowText(line, unchecked((uint)chatChannel));
return result;
}
private static string GetIncomingModeLabel(IncomingChatMode mode)
{
return mode switch
{
IncomingChatMode.WrapperQueuedText => "wrapper-queued-text",
IncomingChatMode.WrapperQueuedTextHostEat => "wrapper-queued-text-host-eat",
IncomingChatMode.AddTextToScrollHostEat => "add-text-to-scroll-host-eat",
_ => "wrapper-unknown"
};
}
private static bool TryResolveOutgoingOffset(
AcClientTextSection textSection,
bool fixedVaTrusted,
out int outgoingOff,
out string resolution)
{
outgoingOff = -1;
resolution = "unresolved";
if (fixedVaTrusted)
{
int fixedOff = OutgoingChatVa - textSection.TextBaseVa;
if (fixedOff >= 0 && fixedOff < textSection.Bytes.Length)
{
if (PatternScanner.VerifyPattern(textSection.Bytes, fixedOff, OutgoingChatPattern))
{
outgoingOff = fixedOff;
resolution = "fixed-va";
return true;
}
else
{
byte entryByte = textSection.Bytes[fixedOff];
if (IsLikelyExternalHookOpcode(entryByte))
{
resolution = $"skipped (prepatched-0x{entryByte:X2})";
RynthLog.Verbose($"Compat: outgoing chat entry at 0x{OutgoingChatVa:X8} appears prepatched (opcode 0x{entryByte:X2}) - skipping RynthCore outgoing hook to avoid conflicting with another injector.");
return false;
}
}
}
}
int scannedOff = PatternScanner.FindPattern(textSection.Bytes, OutgoingChatPattern);
if (scannedOff >= 0)
{
outgoingOff = scannedOff;
resolution = "pattern-scan";
return true;
}
resolution = "resolution failed";
return false;
}
private static bool IsLikelyExternalHookOpcode(byte opcode)
{
return opcode is 0xE9 or 0xE8 or 0xEB or 0x68 or 0xFF;
}
/// <summary>True once a chat-manager 'this' has been captured from a live submit.</summary>
public static bool CanDispatchDirect =>
OutgoingInstalled && _originalOutgoingChat != null && _lastOutgoingThis != IntPtr.Zero;
/// <summary>
/// Dispatches a chat line by calling AC's outgoing-chat function directly — the
/// same path AC takes when you press Enter on the native chat bar, but with no
/// keystroke simulation and no chat-bar state, so it is repeatable. Uses the
/// 'this' + command source captured by <see cref="OutgoingChatDetour"/> from a
/// prior real submit. Returns false if the hook isn't installed or no 'this' has
/// been captured yet — the caller then falls back to keystroke simulation, whose
/// first successful send seeds the capture for all subsequent calls.
/// Plugin pre-dispatch / engine-command handling is the caller's responsibility
/// (already done in ChatCommandDispatcher.Dispatch), so this goes straight to AC.
/// </summary>
public static unsafe bool TryDispatchDirect(string? text)
{
if (!OutgoingInstalled || _originalOutgoingChat == null)
return false;
IntPtr self = _lastOutgoingThis;
if (self == IntPtr.Zero || string.IsNullOrWhiteSpace(text))
return false;
string line = text!.TrimEnd('\r', '\n');
if (line.Length == 0)
return false;
foreach (char c in line)
if (c < 0x20 && c != '\t')
return false; // never feed AC control chars
try
{
ushort[] chars = new ushort[line.Length + 1]; // +1 null terminator (wcslen)
for (int i = 0; i < line.Length; i++)
chars[i] = line[i];
var wide = OutgoingWidePString.Create(chars);
try
{
// 'wide' is a stack local (unmanaged struct) — its address is stable
// for the synchronous call, so no 'fixed' pin is needed (or allowed).
_originalOutgoingChat(self, (IntPtr)(&wide), _lastOutgoingSource);
return true;
}
finally { wide.Dispose(); }
}
catch (Exception ex)
{
RynthLog.Compat($"OutgoingChat direct failed: {ex.GetType().Name}: {ex.Message}");
return false;
}
}
/// <summary>
/// Clears the cached chat-manager 'this'. Called on logout: AC frees the object
/// during the world→charselect transition, so the stale pointer must not be
/// reused. It is re-captured from the next real submit after the next login.
/// </summary>
public static void ResetOutgoingTarget()
{
_lastOutgoingThis = IntPtr.Zero;
}
// Minimal duplicate of ClientHelperHooks.WidePString (AC1Legacy::PStringBase<wchar_t>).
// Duplicated deliberately so the actively-used WriteToChat path stays untouched.
// Phase B / 1a-dup: resolve the PStringBase<wchar_t> ctor/dtor (fn VAs) by pattern and the
// s_NullBuffer (data VA) by code-xref. These were duplicate raw VAs left by 1a's per-file pass.
private static readonly byte?[] PatWidePStringCtor = [ 0x56, 0x57, 0x8B, 0x7C, 0x24, 0x0C, 0x85, 0xFF, 0x8B, 0xF1, 0x74, 0x2C ];
private static readonly byte?[] PatWidePStringDtor = [ 0x56, 0x8B, 0x31, 0x83, 0xEE, 0x14, 0x8D, 0x46 ];
private static readonly byte?[] PatXrefWideNullBuffer = [ 0x3B, 0x05, null, null, null, null, 0x74, 0xE7 ];
private static unsafe void* ResolveFnVa(string name, byte?[] pattern, int fallbackVa)
{
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text)) return (void*)fallbackVa;
HookResolver.ResolveResult r = HookResolver.Resolve(text, name, pattern, fallbackVa);
return (void*)(r.Success ? r.Address : new IntPtr(fallbackVa));
}
private static IntPtr ResolveDataVa(string name, byte?[] pattern, int operandOffset, int fallbackVa)
{
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text)) return new IntPtr(fallbackVa);
return HookResolver.ResolveData(text, name, pattern, operandOffset, fallbackVa).Address;
}
[StructLayout(LayoutKind.Sequential)]
private unsafe struct OutgoingWidePString
{
private static readonly IntPtr NullWideBufferVa = ResolveDataVa("ChatCallback.PStringW_NullBuffer", PatXrefWideNullBuffer, 2, 0x00818340);
private static readonly delegate* unmanaged[Thiscall]<OutgoingWidePString*, ushort*, void> Ctor =
(delegate* unmanaged[Thiscall]<OutgoingWidePString*, ushort*, void>)ResolveFnVa("ChatCallback.PStringW_ctor", PatWidePStringCtor, 0x00402730);
private static readonly delegate* unmanaged[Thiscall]<OutgoingWidePString*, void> Dtor =
(delegate* unmanaged[Thiscall]<OutgoingWidePString*, void>)ResolveFnVa("ChatCallback.PStringW_dtor", PatWidePStringDtor, 0x004011B0);
public IntPtr CharBuffer;
public static OutgoingWidePString Create(ushort[] chars)
{
var value = new OutgoingWidePString { CharBuffer = Marshal.ReadIntPtr(NullWideBufferVa) };
fixed (ushort* pChars = chars)
Ctor(&value, pChars);
return value;
}
public void Dispose()
{
fixed (OutgoingWidePString* ptr = &this)
Dtor(ptr);
}
}
}

View file

@ -0,0 +1,368 @@
using System;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Dispatches chat commands by calling individual CM_Communication::Event_*
/// functions directly. All are cdecl and use AC1Legacy::PStringBase&lt;char&gt;.
/// Falls back to keyboard simulation for unrecognized slash commands.
/// </summary>
internal static unsafe class ChatCommandDispatcher
{
// ── Pattern-resolved binding (1a hardening, 2026-06-05) ─────────────
// The Event_*/PStringBase VAs below are now FALLBACKs; these signatures (verified unique
// + landing exactly at the VA offline via tools/pe_pattern.py) are the source of truth.
// Declared BEFORE the fn-ptr fields so the static field initializers see them. The Event_*
// senders are near-identical templates, so the patterns run long to reach the distinct tail.
private static readonly byte?[] PatEventTalk = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x8B, 0x5C, 0x24, 0x1C, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8B, 0xCB, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x6A, 0x00, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x8B, 0xF0, 0xE8, null, null, null, null, 0x8D, 0x74, 0x06, 0x04, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x54, 0x24, 0x10, 0x52, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x44, 0x24, 0x0C, 0xC7, 0x00, 0x15 ];
private static readonly byte?[] PatEventEmote = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x8B, 0x5C, 0x24, 0x1C, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8B, 0xCB, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x6A, 0x00, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x8B, 0xF0, 0xE8, null, null, null, null, 0x8D, 0x74, 0x06, 0x04, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x54, 0x24, 0x10, 0x52, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x44, 0x24, 0x0C, 0xC7, 0x00, 0xDF ];
private static readonly byte?[] PatEventSoulEmote = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x8B, 0x5C, 0x24, 0x1C, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8B, 0xCB, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x6A, 0x00, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x8B, 0xF0, 0xE8, null, null, null, null, 0x8D, 0x74, 0x06, 0x04, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x54, 0x24, 0x10, 0x52, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x44, 0x24, 0x0C, 0xC7, 0x00, 0xE1 ];
private static readonly byte?[] PatEventTalkDirectByName = [ 0x83, 0xEC, 0x0C, 0x53, 0x55, 0x56, 0x57, 0xE8, null, null, null, null, 0x8B, 0x5C, 0x24, 0x20, 0x89, 0x44, 0x24, 0x18, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x14, 0x50, 0x8B, 0xCB, 0xC7, 0x44, 0x24, 0x1C, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x18, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0x6C, 0x24, 0x24, 0x6A, 0x00, 0x8D, 0x4C, 0x24, 0x14, 0x51, 0x8B, 0xCD, 0x8B, 0xF0, 0xE8, null, null, null, null, 0x6A, 0x00, 0x8D, 0x54, 0x24, 0x14, 0x52, 0x8D, 0x4C, 0x24, 0x1C, 0x03, 0xF0, 0xE8, null, null, null, null, 0x8D, 0x74, 0x06, 0x04, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x89, 0x44, 0x24, 0x10, 0x8B, 0xF8, 0x56, 0x8D, 0x44, 0x24, 0x14, 0x50, 0x8D, 0x4C, 0x24, 0x1C, 0xE8, null, null, null, null, 0x8B, 0x4C, 0x24, 0x10, 0xC7, 0x01, 0x5D ];
private static readonly byte?[] PatEventChannelBroadcast = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x8B, 0x5C, 0x24, 0x20, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8B, 0xCB, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x6A, 0x00, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x8B, 0xF0, 0xE8, null, null, null, null, 0x8D, 0x74, 0x06, 0x08, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x54, 0x24, 0x10, 0x52, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x44, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x00, 0x47 ];
private static readonly byte?[] PatPStringBaseCtor = [ 0x56, 0x8B, 0x74, 0x24, 0x08, 0x85, 0xF6, 0x57, 0x8B, 0xF9, 0x74, 0x35, 0x80, 0x3E, 0x00, 0x74, 0x30, 0x8B, 0xC6, 0x8D, 0x50, 0x01, 0x8A, 0x08, 0x40, 0x84, 0xC9, 0x75, 0xF9, 0x2B, 0xC2, 0x50, 0x8B, 0xCF, 0xE8, null, null, null, null, 0x8B, 0x07 ];
private static readonly byte?[] PatPStringBaseClear = [ 0xA1, 0x1C, 0xF1, 0x8E, 0x00, 0x56, 0x57, 0x8B, 0xF9, 0x8B, 0x37, 0x3B, 0xF0, 0x74, 0x2D, 0x8D, 0x46, 0x04, 0x50, 0xFF, 0x15, 0xF8, 0x31, 0x79, 0x00, 0x85, 0xC0, 0x75, 0x0C, 0x85, 0xF6, 0x74, 0x08, 0x8B, 0x16, 0x6A, 0x01, 0x8B, 0xCE, 0xFF, 0x12, 0xA1, 0x1C, 0xF1, 0x8E, 0x00, 0x8B, 0xC8, 0x83, 0xC1, 0x04, 0x51, 0x89, 0x07, 0xFF, 0x15, 0xFC, 0x31, 0x79, 0x00, 0x5F ];
private static void* ResolveVa(string name, byte?[] pattern, int fallbackVa)
{
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
return (void*)fallbackVa;
HookResolver.ResolveResult r = HookResolver.Resolve(text, name, pattern, fallbackVa);
return (void*)(r.Success ? r.Address : new IntPtr(fallbackVa));
}
// Phase B: PStringBase<char>::s_NullBuffer (0x008EF11C) via code-xref (3B 3D <addr>), offset 2.
private static readonly byte?[] PatXrefPStringNullBuffer = [ 0x3B, 0x3D, null, null, null, null, 0x74, 0xF1 ];
private static IntPtr ResolveDataVa(string name, byte?[] pattern, int operandOffset, int fallbackVa)
{
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
return new IntPtr(fallbackVa);
return HookResolver.ResolveData(text, name, pattern, operandOffset, fallbackVa).Address;
}
// CM_Communication::Event_* — all cdecl, all using AC1Legacy::PStringBase<char>
private static readonly delegate* unmanaged[Cdecl]<LegacyPString*, byte> FnEventTalk =
(delegate* unmanaged[Cdecl]<LegacyPString*, byte>)ResolveVa("ChatCmd.Event_Talk", PatEventTalk, 0x006A53E0);
private static readonly delegate* unmanaged[Cdecl]<LegacyPString*, byte> FnEventEmote =
(delegate* unmanaged[Cdecl]<LegacyPString*, byte>)ResolveVa("ChatCmd.Event_Emote", PatEventEmote, 0x006A4F40);
private static readonly delegate* unmanaged[Cdecl]<LegacyPString*, byte> FnEventSoulEmote =
(delegate* unmanaged[Cdecl]<LegacyPString*, byte>)ResolveVa("ChatCmd.Event_SoulEmote", PatEventSoulEmote, 0x006A5320);
private static readonly delegate* unmanaged[Cdecl]<LegacyPString*, LegacyPString*, byte> FnEventTalkDirectByName =
(delegate* unmanaged[Cdecl]<LegacyPString*, LegacyPString*, byte>)ResolveVa("ChatCmd.Event_TalkDirectByName", PatEventTalkDirectByName, 0x006A55A0);
private static readonly delegate* unmanaged[Cdecl]<uint, LegacyPString*, byte> FnEventChannelBroadcast =
(delegate* unmanaged[Cdecl]<uint, LegacyPString*, byte>)ResolveVa("ChatCmd.Event_ChannelBroadcast", PatEventChannelBroadcast, 0x006A4E50);
private const uint WM_KEYDOWN = 0x0100;
private const uint WM_KEYUP = 0x0101;
private const uint WM_CHAR = 0x0102;
private const int VK_RETURN = 0x0D;
/// <summary>
/// When true, all commands are dispatched via keyboard simulation
/// rather than direct function calls.
/// </summary>
public static bool UseDirectChatInput { get; set; }
/// <summary>
/// Recursion guard for the plugin pre-dispatch step. A plugin's
/// OnChatBarEnter handler may chain by calling Host.InvokeChatParser →
/// PluginManager.InvokeChatParser → ClientHelperHooks.InvokeParser →
/// ChatCommandDispatcher.Dispatch. Without this guard the plugin would
/// re-enter its own OnChatBarEnter on the chained line and could loop.
/// </summary>
[ThreadStatic]
private static bool _inPluginPreDispatch;
/// <summary>
/// AC1Legacy::PStringBase&lt;char&gt; for Event_* functions.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
private struct LegacyPString
{
public IntPtr Buffer;
private static readonly IntPtr NullBufferVa = ResolveDataVa("ChatCmd.PStringChar_NullBuffer", PatXrefPStringNullBuffer, 2, 0x008EF11C);
private static readonly delegate* unmanaged[Thiscall]<LegacyPString*, byte*, void> Ctor =
(delegate* unmanaged[Thiscall]<LegacyPString*, byte*, void>)ResolveVa("ChatCmd.PStringBaseC_ctor", PatPStringBaseCtor, 0x0048C3E0);
private static readonly delegate* unmanaged[Thiscall]<LegacyPString*, void> ClearFn =
(delegate* unmanaged[Thiscall]<LegacyPString*, void>)ResolveVa("ChatCmd.PStringBaseC_Clear", PatPStringBaseClear, 0x004AB990);
public static LegacyPString Create(string text)
{
var value = new LegacyPString { Buffer = Marshal.ReadIntPtr(NullBufferVa) };
byte[] bytes = new byte[text.Length + 1];
for (int i = 0; i < text.Length; i++)
bytes[i] = (byte)text[i];
fixed (byte* pBytes = bytes)
Ctor(&value, pBytes);
return value;
}
public void Dispose()
{
fixed (LegacyPString* ptr = &this)
ClearFn(ptr);
}
}
public static bool Dispatch(string? text)
{
if (string.IsNullOrWhiteSpace(text))
return false;
// Deep-audit finding #4 (2026-06-18): this whole function is not
// network-only — it runs arbitrary plugin OnChatBarEnter handlers,
// constructs/destructs AC's native PStringBase<char> in AC's heap,
// and calls Event_Talk/Event_Emote/etc. directly against AC's live
// chat-manager. The old inline comment claiming this was "thread-safe"
// was an inherited Decal/VTank assumption that contradicts the
// engine's own AcMainThreadQueue design (see the documented
// 0x00460D1D chat-buffer write-AV class). Gating here (rather than at
// each call site) covers every off-thread caller at once:
// OnLoginCommandRunner (ThreadPool), ChatFileDispatcher
// (FileSystemWatcher thread), and Host.InvokeChatParser (plugin
// export, any thread). The queued call re-invokes this same method
// from the drain, where IsOnMainThread is satisfied and the body
// below runs directly — so there's only one code path to keep in sync.
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueChatCommand(text);
try
{
string trimmed = text.Trim();
if (trimmed.Length == 0) return false;
// RynthCore engine commands (/rc ...) are handled before plugin
// pre-dispatch and before any AC chat routing so they work even
// when the overlay is hidden and no plugin can eat the line.
if (RynthCoreChatCommands.TryHandle(trimmed))
return true;
// Expand shorthand: /s → /say, /t → /tell, /e → /emote
trimmed = ExpandShorthand(trimmed);
// Plugin pre-dispatch: matches AC's natural OutgoingChatDetour
// behavior — when a user types in the chat bar, plugins
// (RynthAi /ra, VTank /vt, UBService /ub, MagTools /mt, etc.) get
// first dibs via OnChatBarEnter and can eat the line. We mirror
// that here so callers like OnLoginCommandRunner and
// Host.InvokeChatParser produce identical-to-typed semantics.
//
// Skipped when:
// - Already inside a plugin pre-dispatch on this thread
// (avoids infinite loops on chained Host.InvokeChatParser calls)
// - UseDirectChatInput is on (raw simulate mode bypasses this)
if (!UseDirectChatInput && !_inPluginPreDispatch)
{
_inPluginPreDispatch = true;
try
{
if (PluginManager.DispatchChatBarEnter(trimmed))
return true;
}
catch (Exception ex)
{
RynthLog.Compat($"ChatDispatch: plugin pre-dispatch threw on '{trimmed}' - {ex.GetType().Name}: {ex.Message}");
}
finally { _inPluginPreDispatch = false; }
}
// Direct Chat Input mode — everything goes through keyboard sim
if (UseDirectChatInput)
return SimulateChatInput(trimmed);
// /say message
if (StartsWithCmd(trimmed, "/say "))
return DispatchSay(trimmed.Substring(5));
// /emote message
if (StartsWithCmd(trimmed, "/emote "))
return DispatchEmote(trimmed.Substring(7));
// /e message (soul emote — client-side)
if (StartsWithCmd(trimmed, "/me "))
return DispatchSoulEmote(trimmed.Substring(4));
// /tell Name, message
if (StartsWithCmd(trimmed, "/tell "))
return DispatchTell(trimmed.Substring(6));
// /a message (allegiance channel broadcast)
if (StartsWithCmd(trimmed, "/a "))
return DispatchChannelBroadcast(1, trimmed.Substring(3));
// /f message (fellowship — no direct Event_*; use the raw chat path)
if (StartsWithCmd(trimmed, "/f "))
return DispatchRaw(trimmed);
// Bare text → say
if (!trimmed.StartsWith("/", StringComparison.Ordinal))
return DispatchSay(trimmed);
// Everything else (arbitrary slash commands like /smite) → raw chat path
return DispatchRaw(trimmed);
}
catch (Exception ex)
{
RynthLog.Compat($"ChatDispatch: error - {ex.GetType().Name}: {ex.Message}");
return false;
}
}
private static string ExpandShorthand(string text)
{
if (StartsWithCmd(text, "/s ")) return "/say " + text.Substring(3);
if (StartsWithCmd(text, "/t ")) return "/tell " + text.Substring(3);
return text;
}
private static bool DispatchSay(string message)
{
var ps = LegacyPString.Create(message);
try
{
byte result = FnEventTalk(&ps);
return result != 0;
}
finally { ps.Dispose(); }
}
private static bool DispatchEmote(string emoteText)
{
var ps = LegacyPString.Create(emoteText);
try
{
byte result = FnEventEmote(&ps);
return result != 0;
}
finally { ps.Dispose(); }
}
private static bool DispatchSoulEmote(string emoteText)
{
var ps = LegacyPString.Create(emoteText);
try
{
byte result = FnEventSoulEmote(&ps);
return result != 0;
}
finally { ps.Dispose(); }
}
/// <summary>
/// Dispatches /tell by parsing "Name, message" and calling Event_TalkDirectByName.
/// </summary>
private static bool DispatchTell(string args)
{
// Format: "PlayerName, message text"
int commaIdx = args.IndexOf(',');
if (commaIdx < 1)
{
return DispatchRaw("/tell " + args);
}
string targetName = args.Substring(0, commaIdx).Trim();
string message = args.Substring(commaIdx + 1).TrimStart();
if (targetName.Length == 0 || message.Length == 0)
return false;
var psMsg = LegacyPString.Create(message);
var psTarget = LegacyPString.Create(targetName);
try
{
byte result = FnEventTalkDirectByName(&psMsg, &psTarget);
return result != 0;
}
finally
{
psMsg.Dispose();
psTarget.Dispose();
}
}
/// <summary>
/// Dispatches a message to a Turbine chat channel via Event_ChannelBroadcast.
/// Channel IDs: 1=Allegiance, 2=General, 3=Trade, 4=LFG, 5=Roleplay, 6=Society
/// </summary>
private static bool DispatchChannelBroadcast(uint channelId, string message)
{
if (message.Length == 0)
return false;
var ps = LegacyPString.Create(message);
try
{
byte result = FnEventChannelBroadcast(channelId, &ps);
return result != 0;
}
finally { ps.Dispose(); }
}
/// <summary>
/// Dispatches an arbitrary chat line. Prefers calling AC's outgoing-chat
/// function directly (deterministic and repeatable — no native chat-bar state to
/// corrupt); falls back to keystroke simulation only until the chat 'this' has
/// been captured (typically the very first send of a session, whose successful
/// submit seeds the capture for every send after it).
/// </summary>
private static bool DispatchRaw(string command)
{
if (ChatCallbackHooks.TryDispatchDirect(command))
return true;
return SimulateChatInput(command);
}
/// <summary>
/// Simulates keyboard input to type and submit a chat command.
/// Used as fallback for commands without a direct Event_* function.
/// </summary>
private static bool SimulateChatInput(string command)
{
// Deep-audit finding #18 (2026-06-18): SendToGameWndProc drives
// CallWindowProcA directly into AC's WndProc — calling that off the
// window-owning thread is a cross-thread WndProc re-entry. Dispatch()
// gating (finding #4) already closes the two known off-thread paths
// into this method, but wrap here too per the fix note ("protect
// future callers"): RunOnGameThread inlines with zero overhead when
// already on the game thread (the common case, post-#4) and marshals
// synchronously otherwise.
return ImGuiBackend.Win32Backend.RunOnGameThread(() =>
{
// Enter → opens chat input. The WM_CHAR '\r' is required here to complete
// AC's chat-bar open transition.
IntPtr enterDown = MakeKeyLParam(0x1C, false);
IntPtr enterUp = MakeKeyLParam(0x1C, true);
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_KEYDOWN, new IntPtr(VK_RETURN), enterDown);
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_CHAR, new IntPtr('\r'), enterDown);
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_KEYUP, new IntPtr(VK_RETURN), enterUp);
// Type each character
foreach (char c in command)
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_CHAR, new IntPtr(c), IntPtr.Zero);
// Enter → submit. NO trailing WM_CHAR '\r' here: the WM_KEYDOWN submits and
// closes the bar; a '\r' arriving on the now-closed bar re-opens it (the
// "lone '\r'" behavior the chat-capture path also guards against), leaving the
// bar open so the NEXT command's open-Enter submits an empty bar instead and
// the command is lost — the "works once then stops" symptom.
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_KEYDOWN, new IntPtr(VK_RETURN), enterDown);
ImGuiBackend.Win32Backend.SendToGameWndProc(WM_KEYUP, new IntPtr(VK_RETURN), enterUp);
return true;
});
}
private static IntPtr MakeKeyLParam(byte scanCode, bool keyUp)
{
int lParam = 1;
lParam |= (scanCode << 16);
if (keyUp)
lParam |= (1 << 30) | (1 << 31);
return new IntPtr(lParam);
}
private static bool StartsWithCmd(string text, string prefix)
=> text.StartsWith(prefix, StringComparison.OrdinalIgnoreCase);
}

View file

@ -0,0 +1,188 @@
using System;
using System.IO;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// File-driven chat command dispatcher.
///
/// Watches <c>%APPDATA%\RynthCore\dispatch.txt</c>. Any change to that file
/// is interpreted as a slash command for AC's chat — the file's content
/// (last non-blank line) is sent through <see cref="ChatCommandDispatcher.Dispatch"/>,
/// which routes through any RynthCore-style plugins (RynthAi, VTank, etc.)
/// just like a user-typed command would.
///
/// Use cases:
/// - User is on Remote Desktop and AC's chat input is unresponsive after a
/// hot reload or focus event. Open the dispatch.txt file in Notepad,
/// change the contents, save — command fires.
/// - Scripted automation outside the AC client.
/// - Backup chat path when ImGui/Avalonia keyboard capture is eating input.
///
/// Format: the file is plain text. The dispatcher reads the LAST non-blank
/// non-comment line (lines starting with '#' are ignored). Saving the file
/// triggers a debounced dispatch (~200ms after the last save event, so
/// half-completed edits don't fire).
///
/// Safety:
/// - Empty file or only comments → no dispatch.
/// - Dispatcher does not delete the file. Repeated saves of the same
/// content re-fire the command — by design, so the user can save again
/// to retry. If you want fire-once, write a sentinel line.
/// </summary>
internal static class ChatFileDispatcher
{
private static FileSystemWatcher? _watcher;
private static readonly object SyncRoot = new();
private static long _pendingFireTickMs;
private static Timer? _debounceTimer;
private static string _lastDispatchedContent = string.Empty;
private const int DebounceMs = 200;
public static string FilePath => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"RynthCore",
"dispatch.txt");
public static void Start()
{
if (_watcher != null) return;
try
{
string dir = Path.GetDirectoryName(FilePath) ?? "";
string name = Path.GetFileName(FilePath);
if (string.IsNullOrEmpty(dir) || string.IsNullOrEmpty(name))
{
RynthLog.Compat($"ChatFileDispatcher: invalid FilePath '{FilePath}', not starting.");
return;
}
Directory.CreateDirectory(dir);
if (!File.Exists(FilePath))
{
File.WriteAllText(FilePath,
"# RynthCore chat-command dispatch file.\n" +
"# Save this file with a slash command on the last line to dispatch it.\n" +
"# Example: /ra clearbusy\n" +
"# Comments (lines starting with #) and blank lines are ignored.\n" +
"# Plugin pre-dispatch (RynthAi /ra, etc.) is honored.\n");
}
_watcher = new FileSystemWatcher(dir, name)
{
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size | NotifyFilters.CreationTime,
EnableRaisingEvents = true,
};
_watcher.Changed += OnChanged;
_watcher.Created += OnChanged;
_watcher.Renamed += OnRenamed;
_debounceTimer = new Timer(DispatchOnce, null, Timeout.Infinite, Timeout.Infinite);
RynthLog.Compat($"ChatFileDispatcher: watching '{FilePath}'.");
}
catch (Exception ex)
{
RynthLog.Compat($"ChatFileDispatcher: start failed — {ex.GetType().Name}: {ex.Message}");
}
}
public static void Stop()
{
try
{
if (_watcher != null)
{
_watcher.EnableRaisingEvents = false;
_watcher.Dispose();
_watcher = null;
}
_debounceTimer?.Dispose();
_debounceTimer = null;
}
catch { /* shutdown — non-fatal */ }
}
private static void OnChanged(object _, FileSystemEventArgs e) => ScheduleDispatch();
private static void OnRenamed(object _, RenamedEventArgs e) => ScheduleDispatch();
private static void ScheduleDispatch()
{
lock (SyncRoot)
{
_pendingFireTickMs = Environment.TickCount64 + DebounceMs;
try { _debounceTimer?.Change(DebounceMs, Timeout.Infinite); }
catch { /* timer disposed during shutdown */ }
}
}
private static void DispatchOnce(object? _)
{
string? line = null;
try
{
// ReadAllText with a brief retry: the editor may still hold the
// file briefly after save, FileSystemWatcher fires before the
// handle is released. Try a few times.
string? text = null;
for (int attempt = 0; attempt < 5; attempt++)
{
try { text = File.ReadAllText(FilePath); break; }
catch (IOException) { Thread.Sleep(40); }
}
if (text == null) return;
// Find the LAST non-blank non-comment line.
string[] rawLines = text.Replace("\r\n", "\n").Split('\n');
for (int i = rawLines.Length - 1; i >= 0; i--)
{
string trimmed = rawLines[i].Trim();
if (trimmed.Length == 0) continue;
if (trimmed.StartsWith('#')) continue;
line = trimmed;
break;
}
if (string.IsNullOrWhiteSpace(line))
return;
// Dedup adjacent identical content silently. Saving the file
// re-fires only if content actually differs from last dispatch
// OR the line is prefixed with "force:" (force-fire even if
// same content). User can also clear+resave to fire again.
bool force = line.StartsWith("force:", StringComparison.OrdinalIgnoreCase);
if (force) line = line.Substring("force:".Length).TrimStart();
if (!force && line == _lastDispatchedContent)
{
RynthLog.Verbose($"ChatFileDispatcher: skipped re-dispatch of unchanged line '{line}'.");
return;
}
_lastDispatchedContent = line;
// Strip leading slash if present — Dispatch handles both forms.
string toDispatch = line.StartsWith('/') ? line.Substring(1) : line;
string forDispatch = '/' + toDispatch;
RynthLog.Compat($"ChatFileDispatcher: dispatching '{forDispatch}'.");
try
{
bool ok = ChatCommandDispatcher.Dispatch(forDispatch);
RynthLog.Compat($"ChatFileDispatcher: dispatched ok={ok}.");
}
catch (Exception ex)
{
RynthLog.Compat($"ChatFileDispatcher: Dispatch threw — {ex.GetType().Name}: {ex.Message}");
}
}
catch (Exception ex)
{
RynthLog.Compat($"ChatFileDispatcher: read/parse failed — {ex.GetType().Name}: {ex.Message}");
}
}
}

View file

@ -0,0 +1,160 @@
// ============================================================================
// 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) and calls UIElement::SetVisible
// directly on the captured singleton.
//
// Both addresses (the listen hook and the SetVisible call target) are now
// resolved via HookResolver — pattern-scan first, fallback VA second.
// ============================================================================
using System;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
namespace RynthCore.Engine.Compatibility;
internal static class ChatHooks
{
// Fallback VAs (4,841,472-byte client). Pattern-scan is the source of truth.
private const int GmMainChatUIListenMsgFallbackVa = 0x004CE6F0;
private const int UIElementSetVisibleFallbackVa = 0x00462390;
// gmMainChatUI::ListenToElementMessage(UIElementMessageInfo const&)
// Reads the message kind from [esi+8], decrements, switches on it (0x3C, 0x3E, ...).
private static readonly byte?[] ListenToElementMessagePattern =
[
0x56, 0x8B, 0x74, 0x24, 0x08, 0x8B, 0x46, 0x08,
0x48, 0x57, 0x8B, 0xF9, 0x74, 0x72, 0x83, 0xE8,
0x06, 0x75, 0x7D, 0x8B, 0x4E, 0x04, 0x8B, 0x01,
0x6A, 0x06, 0xFF, 0x90, 0x94, 0x00, 0x00, 0x00
];
// UIElement::SetVisible(bool) — duplicated against RadarHooks deliberately;
// each consumer resolves independently so a partial failure isolates per-file.
private static readonly byte?[] UIElementSetVisiblePattern =
[
0x51, 0x53, 0x56, 0x57,
0x8B, 0x3D, null, null, null, null, // mov edi, ds:[imm32]
0x8B, 0xF1,
0xE8, null, null, null, null, // call rel32
0x8B, 0x9E, 0xA4, 0x00, 0x00, 0x00,
0x88, 0x44, 0x24, 0x0F
];
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void ListenToElementMessageDelegate(IntPtr thisPtr, IntPtr msgInfo);
private static ListenToElementMessageDelegate? _originalListen;
private static ListenToElementMessageDelegate? _listenDetour;
private static IntPtr _gmMainChatInstance;
private static IntPtr _uiElementSetVisibleAddress;
private static bool _hookInstalled;
private static string _statusMessage = "Not initialized.";
public static bool IsInstalled => _hookInstalled;
public static string StatusMessage => _statusMessage;
public static bool SuppressOriginalChat;
public static IntPtr GmMainChatInstance => _gmMainChatInstance;
public static void Initialize()
{
if (_hookInstalled)
return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
{
_statusMessage = "acclient.exe not available.";
return;
}
var setVisible = HookResolver.Resolve(textSection, "ChatHooks.UIElement::SetVisible",
UIElementSetVisiblePattern, UIElementSetVisibleFallbackVa);
if (setVisible.Success) _uiElementSetVisibleAddress = setVisible.Address;
var listen = HookResolver.Resolve(textSection, "ChatHooks.ListenToElementMessage",
ListenToElementMessagePattern, GmMainChatUIListenMsgFallbackVa);
if (!listen.Success)
{
_statusMessage = $"ListenToElementMessage resolve failed ({listen.Detail}).";
return;
}
try
{
_listenDetour = ListenDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_listenDetour);
_originalListen = Marshal.GetDelegateForFunctionPointer<ListenToElementMessageDelegate>(
MinHook.HookCreate(listen.Address, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(listen.Address);
_hookInstalled = true;
_statusMessage = $"Hooked gmMainChatUI::ListenToElementMessage @ 0x{listen.Address.ToInt32():X8}.";
RynthLog.Compat($"ChatHooks: install ok.");
}
catch (Exception ex)
{
_statusMessage = ex.Message;
RynthLog.Compat($"ChatHooks: install threw {ex.GetType().Name}: {ex.Message}");
}
}
private static int _listenFires;
private static void ListenDetour(IntPtr thisPtr, IntPtr msgInfo)
{
RecursionGuard.Tick("ChatHooks.Listen");
if (thisPtr != IntPtr.Zero)
_gmMainChatInstance = thisPtr;
if (++_listenFires <= 3)
RynthLog.Compat($"ChatHooks: Listen fired #{_listenFires} this=0x{thisPtr.ToInt32():X8}");
try { _originalListen!(thisPtr, msgInfo); }
catch (Exception ex) { try { RynthLog.Compat($"ChatHooks: Listen original threw {ex.GetType().Name}: {ex.Message}"); } catch { } throw; }
}
private static bool _isHiddenAsserted;
public static unsafe void TickHide()
{
if (!LoginLifecycleHooks.HasObservedLoginComplete)
return;
IntPtr inst = _gmMainChatInstance;
if (inst == IntPtr.Zero) return;
if (_uiElementSetVisibleAddress == IntPtr.Zero) return;
if (SuppressOriginalChat)
{
try
{
((delegate* unmanaged[Thiscall]<IntPtr, int, void>)_uiElementSetVisibleAddress)(inst, 0);
}
catch { /* best-effort */ }
_isHiddenAsserted = true;
return;
}
if (_isHiddenAsserted)
{
try
{
((delegate* unmanaged[Thiscall]<IntPtr, int, void>)_uiElementSetVisibleAddress)(inst, 1);
}
catch { /* best-effort */ }
_isHiddenAsserted = false;
}
}
public static void ResetCachedInstance()
{
_gmMainChatInstance = IntPtr.Zero;
_isHiddenAsserted = false;
}
}

View file

@ -0,0 +1,184 @@
namespace RynthCore.Engine.Compatibility;
internal readonly record struct ClientActionHookStatus(
bool CombatInitialized,
bool MovementInitialized,
bool CommandInterpreterInitialized,
bool PlayerPhysicsInitialized,
bool MeleeAvailable,
bool MissileAvailable,
bool ChangeCombatModeAvailable,
bool CancelAttackAvailable,
bool QueryHealthAvailable,
bool DoMovementAvailable,
bool StopMovementAvailable,
bool JumpNonAutonomousAvailable,
bool AutonomyLevelAvailable,
bool SetAutoRunAvailable,
bool TapJumpAvailable,
bool SetMotionAvailable,
bool GetPlayerHeadingAvailable,
bool StopCompletelyAvailable,
bool TurnToHeadingAvailable,
string CombatStatus,
string MovementStatus,
string CommandInterpreterStatus);
internal static class ClientActionHooks
{
public static void Initialize()
{
Probe();
}
public static void Probe()
{
RynthLog.Verbose("Compat: probing RynthAi action hooks...");
bool combatReady = CombatActionHooks.Probe();
bool movementReady = MovementActionHooks.Probe();
bool cmdInterpReady = CommandInterpreterHooks.Probe();
bool playerPhysicsReady = PlayerPhysicsHooks.Probe();
bool objectReady = ClientObjectHooks.Probe();
RynthLog.Verbose($"Compat: probe complete. combat={(combatReady ? "ready" : "off")}, movement={(movementReady ? "ready" : "off")}, local={(cmdInterpReady ? "ready" : "off")}, player={(playerPhysicsReady ? "ready" : "off")}, objects={(objectReady ? "ready" : "off")}");
}
public static ClientActionHookStatus GetStatus()
{
return new ClientActionHookStatus(
CombatActionHooks.IsInitialized,
MovementActionHooks.IsInitialized,
CommandInterpreterHooks.IsInitialized,
PlayerPhysicsHooks.IsInitialized,
CombatActionHooks.HasMeleeAttack,
CombatActionHooks.HasMissileAttack,
CombatActionHooks.HasChangeCombatMode,
CombatActionHooks.HasCancelAttack,
CombatActionHooks.HasQueryHealth,
MovementActionHooks.HasDoMovement,
MovementActionHooks.HasStopMovement,
MovementActionHooks.HasJumpNonAutonomous,
MovementActionHooks.HasAutonomyLevel,
CommandInterpreterHooks.HasSetAutoRun,
CommandInterpreterHooks.HasTapJump,
CommandInterpreterHooks.HasSetMotion,
PlayerPhysicsHooks.HasGetHeading,
CommandInterpreterHooks.HasStopCompletely,
PlayerPhysicsHooks.HasSetHeading || CommandInterpreterHooks.HasTurnToHeading,
CombatActionHooks.StatusMessage,
MovementActionHooks.StatusMessage,
CommandInterpreterHooks.StatusMessage);
}
public static bool MeleeAttack(uint targetId, int attackHeight, float powerLevel)
{
return CombatActionHooks.MeleeAttack(targetId, attackHeight, powerLevel);
}
public static bool MissileAttack(uint targetId, int attackHeight, float accuracyLevel)
{
return CombatActionHooks.MissileAttack(targetId, attackHeight, accuracyLevel);
}
public static bool ChangeCombatMode(int combatMode)
{
return CombatActionHooks.ChangeCombatMode(combatMode);
}
public static bool CancelAttack()
{
return CombatActionHooks.CancelAttack();
}
public static bool QueryHealth(uint targetId)
{
return CombatActionHooks.QueryHealth(targetId);
}
public static bool RequestId(uint objectId)
{
return CombatActionHooks.RequestId(objectId);
}
public static bool CastSpell(uint targetId, int spellId)
{
return CombatActionHooks.CastSpell(targetId, spellId);
}
public static bool DoMovement(uint motion, float speed = 1.0f, int holdKey = MovementActionHooks.HoldKeyRun)
{
return MovementActionHooks.DoMovement(motion, speed, holdKey);
}
public static bool StopMovement(uint motion, int holdKey = MovementActionHooks.HoldKeyRun)
{
return MovementActionHooks.StopMovement(motion, holdKey);
}
public static bool JumpNonAutonomous(float extent)
{
return MovementActionHooks.JumpNonAutonomous(extent);
}
public static bool SetAutonomyLevel(uint level)
{
return MovementActionHooks.SetAutonomyLevel(level);
}
public static bool SetAutoRun(bool enabled)
{
return CommandInterpreterHooks.SetAutoRun(enabled);
}
public static bool TapJump()
{
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);
}
public static bool StopCompletely()
{
return CommandInterpreterHooks.StopCompletely();
}
public static bool TurnToHeading(float headingDegrees)
{
// Direct quaternion write — instant snap, most reliable (uses proven SmartBox offsets).
// Equivalent to old Decal Actions.Heading = value.
if (PlayerPhysicsHooks.SetPlayerHeadingDirect(headingDegrees))
return true;
// Fallback: command interpreter gradual turn
return CommandInterpreterHooks.TurnToHeading(headingDegrees);
}
public static bool TryGetPlayerHeading(out float headingDegrees)
{
return PlayerPhysicsHooks.TryGetPlayerHeading(out headingDegrees);
}
public static bool TryGetObjectName(uint objectId, out string name)
{
return ClientObjectHooks.TryGetObjectName(objectId, out name);
}
}

View file

@ -0,0 +1,261 @@
using System;
using System.Runtime.InteropServices;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Hooks into the AC client's ClientCombatSystem — the high-level combat pipeline
/// that handles turn-to-face, power bar build, and attack execution naturally.
/// Contrast with CombatActionHooks which sends raw game actions (bypassing facing).
/// </summary>
internal static class ClientCombatHooks
{
// ── VAs from Chorizite ClientCombatSystem (confirmed from IDA .text comments) ──
/// <summary>Static cdecl: ClientCombatSystem* GetCombatSystem()</summary>
private const int GetCombatSystemVa = 0x0056B210;
/// <summary>Global pointer: ClientCombatSystem* s_pCombatSystem</summary>
private const int CombatSystemPtrVa = 0x0087166C;
// Thiscall instance methods on ClientCombatSystem:
private const int SetRequestedAttackHeightVa = 0x0056D640;
private const int StartAttackRequestVa = 0x0056CD90;
private const int EndAttackRequestVa = 0x0056CE30;
private const int PlayerInReadyPositionVa = 0x0056C570;
private const int AutoTargetVa = 0x0056C9D0;
// Static cdecl CM_Combat function — notifies the client of height change (same as pressing Del/End/PgDn)
private const int SendAttackHeightChangedVa = 0x006AAE10;
// ── Delegates ───────────────────────────────────────────────────────
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate IntPtr GetCombatSystemDelegate();
// Thiscall: first param = this pointer (passed via ECX on x86)
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void SetRequestedAttackHeightDelegate(IntPtr thisPtr, int attackHeight);
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void StartAttackRequestDelegate(IntPtr thisPtr);
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void EndAttackRequestDelegate(IntPtr thisPtr, int attackHeight, float power);
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate byte PlayerInReadyPositionDelegate(IntPtr thisPtr, byte considerAttackingReady);
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void AutoTargetDelegate(IntPtr thisPtr);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate byte SendAttackHeightChangedDelegate(int attackHeight);
// ── Function pointers ───────────────────────────────────────────────
private static GetCombatSystemDelegate? _getCombatSystem;
private static SetRequestedAttackHeightDelegate? _setAttackHeight;
private static StartAttackRequestDelegate? _startAttackRequest;
private static EndAttackRequestDelegate? _endAttackRequest;
private static PlayerInReadyPositionDelegate? _playerInReadyPosition;
private static AutoTargetDelegate? _autoTarget;
private static SendAttackHeightChangedDelegate? _sendAttackHeightChanged;
// ── Pattern-resolved binding (1a hardening, 2026-06-05) ─────────────
// The *Va consts above are now FALLBACKs. These signatures (verified unique + landing
// exactly at the VA offline against this client via tools/pe_pattern.py) are the source
// of truth, so binding survives AC-patch / ACE-rebuild drift. null = wildcard (rel32).
private static readonly byte?[] PatGetCombatSystem = [ 0xA1, 0x6C, 0x16, 0x87, 0x00, 0xC3, 0x90, 0x90 ];
private static readonly byte?[] PatSetRequestedAttackHeight = [ 0x8B, 0x51, 0x24, 0x8B, 0x44, 0x24, 0x04, 0x3B ];
private static readonly byte?[] PatStartAttackRequest = [ 0x51, 0x56, 0x8B, 0xF1, 0xE8, null, null, null, null, 0x8A ];
private static readonly byte?[] PatEndAttackRequest = [ 0x51, 0x56, 0x8B, 0xF1, 0x8A, 0x46, 0x3E, 0x84, 0xC0, 0x0F ];
private static readonly byte?[] PatPlayerInReadyPosition = [ 0xA1, 0x58, 0xDA, 0x83, 0x00, 0x83, 0xEC, 0x18 ];
private static readonly byte?[] PatAutoTarget = [ 0x83, 0xEC, 0x18, 0x53, 0x56, 0x57, 0x8D, 0x44, 0x24, 0x10 ];
private static readonly byte?[] PatSendAttackHeightChanged = [ 0xE8, null, null, null, null, 0x8B, 0x10, 0x68, 0xFC ];
// Phase B (1a-data): s_pCombatSystem global (0x0087166C) resolved by code-xref — the unique
// "mov [s_pCombatSystem],esi" site (89 35 <addr>); read the address from the operand at
// offset 2. The VA stays as the logged fallback.
private static readonly byte?[] PatXrefCombatSystemPtr = [ 0x89, 0x35, null, null, null, null, 0x8B, 0x06 ];
private static IntPtr _combatSystemPtrAddr = new(CombatSystemPtrVa);
private static T? Bind<T>(AcClientTextSection text, string name, byte?[] pattern, int fallbackVa) where T : Delegate
{
HookResolver.ResolveResult r = HookResolver.Resolve(text, name, pattern, fallbackVa);
return r.Success ? Marshal.GetDelegateForFunctionPointer<T>(r.Address) : null;
}
private static bool _initialized;
private static string _statusMessage = "Not probed yet.";
public static bool IsInitialized => _initialized;
public static string StatusMessage => _statusMessage;
public static bool HasClientCombat => _startAttackRequest != null;
// ── Probe ───────────────────────────────────────────────────────────
public static bool Probe()
{
try
{
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
{
_statusMessage = "acclient .text not readable for pattern resolve.";
RynthLog.Compat($"Compat: ClientCombat probe failed - {_statusMessage}");
return false;
}
_combatSystemPtrAddr = HookResolver.ResolveData(text, "ClientCombat.s_pCombatSystem", PatXrefCombatSystemPtr, 2, CombatSystemPtrVa).Address;
_getCombatSystem = Bind<GetCombatSystemDelegate>(text, "ClientCombat.GetCombatSystem", PatGetCombatSystem, GetCombatSystemVa);
_setAttackHeight = Bind<SetRequestedAttackHeightDelegate>(text, "ClientCombat.SetRequestedAttackHeight", PatSetRequestedAttackHeight, SetRequestedAttackHeightVa);
_startAttackRequest = Bind<StartAttackRequestDelegate>(text, "ClientCombat.StartAttackRequest", PatStartAttackRequest, StartAttackRequestVa);
_endAttackRequest = Bind<EndAttackRequestDelegate>(text, "ClientCombat.EndAttackRequest", PatEndAttackRequest, EndAttackRequestVa);
_playerInReadyPosition = Bind<PlayerInReadyPositionDelegate>(text, "ClientCombat.PlayerInReadyPosition", PatPlayerInReadyPosition, PlayerInReadyPositionVa);
_autoTarget = Bind<AutoTargetDelegate>(text, "ClientCombat.AutoTarget", PatAutoTarget, AutoTargetVa);
_sendAttackHeightChanged = Bind<SendAttackHeightChangedDelegate>(text, "ClientCombat.SendAttackHeightChanged", PatSendAttackHeightChanged, SendAttackHeightChangedVa);
// Verify the combat system singleton is accessible
IntPtr cs = _getCombatSystem?.Invoke() ?? IntPtr.Zero;
IntPtr globalPtr = Marshal.ReadIntPtr(_combatSystemPtrAddr);
RynthLog.Verbose($"Compat: ClientCombat GetCombatSystem()=0x{cs:X8}, global=0x{globalPtr:X8}");
if (cs == IntPtr.Zero && globalPtr == IntPtr.Zero)
{
_statusMessage = "GetCombatSystem returned null — client not ready.";
RynthLog.Verbose($"Compat: ClientCombat probe - {_statusMessage}");
// Don't fail — the pointer may be valid after login
}
else
{
IntPtr used = cs != IntPtr.Zero ? cs : globalPtr;
RynthLog.Verbose($"Compat: ClientCombatSystem at 0x{used:X8}");
}
_initialized = true;
_statusMessage = "Ready.";
RynthLog.Verbose("Compat: ClientCombat hooks ready — native attack pipeline available.");
return true;
}
catch (Exception ex)
{
Reset();
_statusMessage = ex.Message;
RynthLog.Compat($"Compat: ClientCombat probe failed - {ex.Message}");
return false;
}
}
// ── Public API ──────────────────────────────────────────────────────
/// <summary>
/// Initiate a native attack using the client's combat pipeline.
/// Sets attack height then calls StartAttackRequest which begins
/// auto-repeating attacks. The client handles turn-to-face naturally.
/// Target must be selected via SelectItem first.
/// </summary>
/// <summary>
/// Initiate a native attack using the client's combat pipeline.
/// Calls StartAttackRequest to begin the power bar, then EndAttackRequest
/// to fire at the specified height and power. The client handles turn-to-face.
/// Target must be selected via SelectItem first.
/// </summary>
public static bool NativeAttack(int attackHeight, float power)
{
if (_startAttackRequest == null || _endAttackRequest == null || _getCombatSystem == null)
{
RynthLog.Compat($"ClientCombat: NativeAttack — delegates null (start={_startAttackRequest != null}, end={_endAttackRequest != null}, getCS={_getCombatSystem != null})");
return false;
}
// Deep-audit finding #15 (2026-06-18): this fires 4 AC combat-state
// mutators (height notify, SetRequestedAttackHeight, StartAttackRequest,
// EndAttackRequest) that must land in the SAME order as the paired
// SelectItem that precedes it. Reachable off-thread via the host API,
// and UseNativeAttack defaults true — so unlike this file's sibling
// MeleeAttack/MissileAttack, this ran un-marshalled every fight. Marshal
// as ONE queue entry (not split into four) so the sequence stays atomic
// relative to the drain loop's other actions.
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueNativeAttack(attackHeight, power);
try
{
IntPtr cs = _getCombatSystem();
if (cs == IntPtr.Zero)
{
IntPtr globalPtr = Marshal.ReadIntPtr(_combatSystemPtrAddr);
if (globalPtr == IntPtr.Zero) return false;
cs = globalPtr;
}
if (!ClientObjectHooks.IsReadablePointer(cs)) return false;
// Notify client of height change via CM_Combat (same path as keyboard Del/End/PgDn)
_sendAttackHeightChanged?.Invoke(attackHeight);
_setAttackHeight!(cs, attackHeight);
_startAttackRequest(cs);
_endAttackRequest(cs, attackHeight, power);
return true;
}
catch (Exception ex)
{
RynthLog.Compat($"ClientCombat: NativeAttack EXCEPTION - {ex.GetType().Name}: {ex.Message}");
return false;
}
}
/// <summary>
/// Check if the player is in a ready position to begin an attack.
/// </summary>
public static bool IsPlayerReady()
{
if (_playerInReadyPosition == null || _getCombatSystem == null)
return false;
try
{
IntPtr cs = _getCombatSystem();
if (cs == IntPtr.Zero) return false;
return _playerInReadyPosition(cs, 1) != 0;
}
catch { return false; }
}
/// <summary>
/// Auto-target the nearest enemy using the client's targeting system.
/// </summary>
public static bool AutoTarget()
{
if (_autoTarget == null || _getCombatSystem == null)
return false;
// Same mutator class as NativeAttack (audit finding #15). Not currently
// exposed through the plugin SDK, so there's no live off-thread caller
// today — fail closed rather than queue, since queuing an unreachable
// path is dead-weight; revisit with an ActionKind if this is exposed.
if (!MainThreadGuard.IsOnMainThread())
return false;
try
{
IntPtr cs = _getCombatSystem();
if (cs == IntPtr.Zero) return false;
if (!ClientObjectHooks.IsReadablePointer(cs)) return false;
_autoTarget(cs);
return true;
}
catch { return false; }
}
public static void Reset()
{
_getCombatSystem = null;
_setAttackHeight = null;
_startAttackRequest = null;
_endAttackRequest = null;
_playerInReadyPosition = null;
_autoTarget = null;
_sendAttackHeightChanged = null;
_initialized = false;
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,968 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.Compatibility;
internal static class CombatActionHooks
{
private const int QueryHealthResponseVa = 0x006AA900;
// ── Pattern-resolved binding (1a hardening, 2026-06-06) ─────────────
// The cast/tick VAs were previously bound by raw VA + in-module/warn-only-prologue checks.
// These signatures (verified unique + landing exactly at the VA offline via
// tools/pe_pattern.py) are now the source of truth; the VA stays as logged fallback.
// GetMagicSystem/FreeHandsAndCastSpell are invoked via the SEH trampoline on AC's main
// thread — resolving by pattern changes only how the address is found, not the call path.
private static readonly byte?[] QueryHealthResponsePattern = [ 0x8B, 0x44, 0x24, 0x04, 0x85, 0xC0, 0x74, 0x18, 0x8B, 0x48, 0x50 ];
private static readonly byte?[] CastSpellClientPattern = [ 0x81, 0xEC, 0x48, 0x01, 0x00, 0x00, 0x53, 0x56 ];
private static readonly byte?[] GetMagicSystemPattern = [ 0xA1, 0x4C, 0x14, 0x87, 0x00, 0xC3, 0x90, 0x90 ];
private static readonly byte?[] FreeHandsAndCastSpellPattern = [ 0xA1, 0x58, 0xDA, 0x83, 0x00, 0x8B, 0x88, 0xB8, 0x00, 0x00, 0x00, 0x8B, 0x11, 0xFF, 0x92, 0xC0, 0x00, 0x00, 0x00, 0x8B, 0x44 ];
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool TargetedMeleeAttackDelegate(uint targetId, int attackHeight, float powerLevel);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool TargetedMissileAttackDelegate(uint targetId, int attackHeight, float accuracyLevel);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool ChangeCombatModeDelegate(int combatMode);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool CancelAttackDelegate();
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool QueryHealthDelegate(uint targetId);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool RequestIdDelegate(uint objectId);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool CastSpellDelegate(uint targetId, int spellId);
// Chorizite-style: ClientMagicSystem::CastSpell(uint spellId, byte targetIsSelected)
// VA 0x00568DE0 — static Cdecl. The client uses the currently selected target.
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void CastSpellClientDelegate(uint spellId, byte targetIsSelected);
private const int ClientMagicSystemCastSpellVa = 0x00568DE0;
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate uint QueryHealthResponseDelegate(IntPtr uiQueueManager, IntPtr buffer, uint size);
public const int AttackHeightHigh = 1;
public const int AttackHeightMedium = 2;
public const int AttackHeightLow = 3;
public const int CombatModeNonCombat = 1;
public const int CombatModeMelee = 2;
public const int CombatModeMissile = 4;
public const int CombatModeMagic = 8;
private static readonly byte[] CombatPrologue = [0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8];
private static TargetedMeleeAttackDelegate? _meleeAttack;
private static TargetedMissileAttackDelegate? _missileAttack;
private static ChangeCombatModeDelegate? _changeCombatMode;
private static CancelAttackDelegate? _cancelAttack;
private static QueryHealthDelegate? _queryHealth;
private static RequestIdDelegate? _requestId;
private static CastSpellDelegate? _castSpell;
private static CastSpellClientDelegate? _castSpellClient;
private static IntPtr _castSpellClientPtr;
// RC2-proven explicit-target cast (no SelectItem / global selection). VAs verified
// against acclient.map. GetMagicSystem returns the ClientMagicSystem singleton ('this');
// FreeHandsAndCastSpell(this, spellId, targetId) takes the target as an EXPLICIT arg, so
// it never reads AC's selected-object global ([singleton+0xF4]) the way CastSpell(...,1)
// @ 0x00568DE0 does — which is why it survives being marshalled onto AC's game tick.
private const int GetMagicSystemVa = 0x00567C00; // void* __cdecl GetMagicSystem()
private const int FreeHandsAndCastSpellVa = 0x00567C90; // void __thiscall FreeHandsAndCastSpell(this, uint spellId, uint targetId)
private static IntPtr _getMagicSystemPtr;
private static IntPtr _freeHandsCastPtr;
private static int _sehAvLogCount;
private static QueryHealthResponseDelegate? _queryHealthResponseDetour;
private static QueryHealthResponseDelegate? _originalQueryHealthResponse;
private static QueryHealthResponseDelegate? _identifyObjectDetour;
private static QueryHealthResponseDelegate? _originalIdentifyObject;
private static string _statusMessage = "Not probed yet.";
public static bool IsInitialized { get; private set; }
public static bool HasMeleeAttack => _meleeAttack != null;
public static bool HasMissileAttack => _missileAttack != null;
public static bool HasChangeCombatMode => _changeCombatMode != null;
public static bool HasCancelAttack => _cancelAttack != null;
public static bool HasQueryHealth => _queryHealth != null;
public static bool HasRequestId => _requestId != null;
public static bool HasCastSpell => _castSpell != null;
public static string StatusMessage => _statusMessage;
public static bool Probe()
{
Reset();
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
{
_statusMessage = "acclient.exe not available.";
return false;
}
try
{
byte[] text = textSection.Bytes;
byte[] cancelOpcode = [0xC7, 0x02, 0xB7, 0x01, 0x00, 0x00];
int cancelOpcodeOff = PatternScanner.FindPattern(text, cancelOpcode);
if (cancelOpcodeOff < 0)
{
_statusMessage = "CancelAttack opcode 0x1B7 not found.";
RynthLog.Compat("Compat: combat probe failed - CancelAttack opcode 0x1B7 not found.");
return false;
}
int cancelFuncOff = PatternScanner.FindPrologueBefore(text, cancelOpcodeOff, CombatPrologue);
if (cancelFuncOff < 0)
{
_statusMessage = "CancelAttack prologue not found.";
RynthLog.Compat("Compat: combat probe failed - CancelAttack prologue not found.");
return false;
}
int regionStart = Math.Max(0, cancelOpcodeOff - 0x500);
int regionEnd = Math.Min(text.Length, cancelOpcodeOff + 0x500);
byte[] changeModeOpcode = [0xC7, 0x02, 0x53, 0x00, 0x00, 0x00];
int changeModeOff = PatternScanner.FindPatternInRegion(text, changeModeOpcode, regionStart, regionEnd);
int changeModeFuncOff = changeModeOff >= 0
? PatternScanner.FindPrologueBefore(text, changeModeOff, CombatPrologue)
: -1;
byte[] queryHealthOpcode = [0xC7, 0x02, 0xBF, 0x01, 0x00, 0x00];
int queryHealthOff = PatternScanner.FindPatternInRegion(text, queryHealthOpcode, regionStart, regionEnd);
int queryHealthFuncOff = queryHealthOff >= 0
? PatternScanner.FindPrologueBefore(text, queryHealthOff, CombatPrologue)
: -1;
byte[] meleeOpcode = [0xC7, 0x02, 0x08, 0x00, 0x00, 0x00];
int meleeOff = PatternScanner.FindPatternInRegion(text, meleeOpcode, regionStart, regionEnd);
int meleeFuncOff = meleeOff >= 0
? PatternScanner.FindPrologueBefore(text, meleeOff, CombatPrologue)
: -1;
byte[] missileOpcode = [0xC7, 0x02, 0x0A, 0x00, 0x00, 0x00];
int missileOff = PatternScanner.FindPatternInRegion(text, missileOpcode, regionStart, regionEnd);
int missileFuncOff = missileOff >= 0
? PatternScanner.FindPrologueBefore(text, missileOff, CombatPrologue)
: -1;
// RequestId / IdentifyObject — game action 0xC8
// Search wider region since it may not be near the combat actions
int wideRegionStart = Math.Max(0, cancelOpcodeOff - 0x2000);
int wideRegionEnd = Math.Min(text.Length, cancelOpcodeOff + 0x2000);
byte[] requestIdOpcode = [0xC7, 0x02, 0xC8, 0x00, 0x00, 0x00];
int requestIdOff = PatternScanner.FindPatternInRegion(text, requestIdOpcode, wideRegionStart, wideRegionEnd);
int requestIdFuncOff = requestIdOff >= 0
? PatternScanner.FindPrologueBefore(text, requestIdOff, CombatPrologue)
: -1;
// CastSpell — search full text section for known candidate opcodes
// Candidates: 0x4A (cast targeted), 0x48, 0x55, 0x5D
int castSpellFuncOff = -1;
int castSpellOff = -1;
byte[][] castSpellCandidates = [
[0xC7, 0x02, 0x4A, 0x00, 0x00, 0x00],
[0xC7, 0x02, 0x48, 0x00, 0x00, 0x00],
[0xC7, 0x02, 0x55, 0x00, 0x00, 0x00],
[0xC7, 0x02, 0x5D, 0x00, 0x00, 0x00],
];
foreach (byte[] candidate in castSpellCandidates)
{
int off = PatternScanner.FindPattern(text, candidate);
if (off >= 0)
{
int funcOff = PatternScanner.FindPrologueBefore(text, off, CombatPrologue);
if (funcOff >= 0)
{
castSpellOff = off;
castSpellFuncOff = funcOff;
RynthLog.Verbose($"Compat: CastSpell candidate opcode=0x{candidate[2]:X2} matched at text+0x{off:X}");
break;
}
}
}
if (changeModeFuncOff < 0 || queryHealthFuncOff < 0 || meleeFuncOff < 0 || missileFuncOff < 0)
{
_statusMessage =
$"Incomplete. mode={changeModeFuncOff >= 0}, health={queryHealthFuncOff >= 0}, melee={meleeFuncOff >= 0}, missile={missileFuncOff >= 0}.";
RynthLog.Compat($"Compat: combat probe incomplete - {_statusMessage}");
return false;
}
if (!PatternScanner.VerifyBytes(text, cancelFuncOff, CombatPrologue) ||
!PatternScanner.VerifyBytes(text, changeModeFuncOff, CombatPrologue) ||
!PatternScanner.VerifyBytes(text, queryHealthFuncOff, CombatPrologue) ||
!PatternScanner.VerifyBytes(text, meleeFuncOff, CombatPrologue) ||
!PatternScanner.VerifyBytes(text, missileFuncOff, CombatPrologue))
{
_statusMessage = "Prologue verification failed.";
RynthLog.Compat("Compat: combat probe failed - prologue verification failed.");
return false;
}
int cancelVa = textSection.TextBaseVa + cancelFuncOff;
int changeModeVa = textSection.TextBaseVa + changeModeFuncOff;
int queryHealthVa = textSection.TextBaseVa + queryHealthFuncOff;
int meleeVa = textSection.TextBaseVa + meleeFuncOff;
int missileVa = textSection.TextBaseVa + missileFuncOff;
_cancelAttack = Marshal.GetDelegateForFunctionPointer<CancelAttackDelegate>(new IntPtr(cancelVa));
_changeCombatMode = Marshal.GetDelegateForFunctionPointer<ChangeCombatModeDelegate>(new IntPtr(changeModeVa));
_queryHealth = Marshal.GetDelegateForFunctionPointer<QueryHealthDelegate>(new IntPtr(queryHealthVa));
_meleeAttack = Marshal.GetDelegateForFunctionPointer<TargetedMeleeAttackDelegate>(new IntPtr(meleeVa));
_missileAttack = Marshal.GetDelegateForFunctionPointer<TargetedMissileAttackDelegate>(new IntPtr(missileVa));
if (requestIdFuncOff >= 0)
{
int requestIdVa = textSection.TextBaseVa + requestIdFuncOff;
_requestId = Marshal.GetDelegateForFunctionPointer<RequestIdDelegate>(new IntPtr(requestIdVa));
RynthLog.Compat($"Compat: RequestId (IdentifyObject 0xC8) found at 0x{requestIdVa:X8}");
}
else
{
RynthLog.Compat("Compat: RequestId (IdentifyObject 0xC8) not found — target appraisal unavailable.");
}
if (castSpellFuncOff >= 0)
{
int castSpellVa = textSection.TextBaseVa + castSpellFuncOff;
_castSpell = Marshal.GetDelegateForFunctionPointer<CastSpellDelegate>(new IntPtr(castSpellVa));
RynthLog.Compat($"Compat: CastSpell (0x4A) found at 0x{castSpellVa:X8}");
}
else
{
RynthLog.Compat("Compat: CastSpell (0x4A) not found — magic combat unavailable.");
}
// ClientMagicSystem::CastSpell — static Cdecl:
// void CastSpell(uint spellId, byte targetIsSelected)
// Uses the currently selected target (from SelectItem).
//
// The in-module check uses `textSection` (already read above), NOT
// SmartBoxLocator.IsPointerInModule. SmartBoxLocator's bounds are
// populated only by its own Probe(), which runs lazily at the first
// TryGetSmartBox (around login) — long AFTER this early init step
// (ClientActionHooks.Initialize). IsPointerInModule therefore always
// saw _moduleBase==0 here and fail-closed for EVERY pointer, so this
// correct VA was rejected on essentially every launch and casting
// was forced onto the mis-bound _castSpell pattern fallback — the
// root cause of the AC-side near-null write AV (0x00568DE0 logged
// "outside module"; AC crashed at 0x00416C86 [null+0x28] /
// 0x0055FA24 [null+0x40]). acclient.exe is byte-identical to retail
// (only PE-header metadata differs) so this retail VA is valid here;
// it is validated live below per the no-blind-decompile-RVA rule.
HookResolver.ResolveResult csRes = HookResolver.Resolve(textSection, "CombatAction.CastSpellClient", CastSpellClientPattern, ClientMagicSystemCastSpellVa);
if (csRes.Success)
{
_castSpellClient = Marshal.GetDelegateForFunctionPointer<CastSpellClientDelegate>(csRes.Address);
_castSpellClientPtr = csRes.Address;
RynthLog.Compat($"Compat: ClientMagicSystem::CastSpell bound at 0x{csRes.Address.ToInt32():X8} ({csRes.Detail})");
}
else
{
RynthLog.Compat($"Compat: ClientMagicSystem::CastSpell VA 0x{ClientMagicSystemCastSpellVa:X8} unresolved — unavailable.");
}
// Explicit-target cast pair (RC2-proven): GetMagicSystem + FreeHandsAndCastSpell,
// invoked via the SEH trampoline on AC's main thread. Replaces the SelectItem +
// CastSpell(targetIsSelected=1) two-step for TARGETED casts (the global-selection
// read that didn't survive being marshalled onto the tick).
HookResolver.ResolveResult gmsRes = HookResolver.Resolve(textSection, "CombatAction.GetMagicSystem", GetMagicSystemPattern, GetMagicSystemVa);
HookResolver.ResolveResult fhcRes = HookResolver.Resolve(textSection, "CombatAction.FreeHandsAndCastSpell", FreeHandsAndCastSpellPattern, FreeHandsAndCastSpellVa);
if (gmsRes.Success && fhcRes.Success)
{
_getMagicSystemPtr = gmsRes.Address;
_freeHandsCastPtr = fhcRes.Address;
RynthLog.Compat(
$"Compat: explicit-target cast bound — GetMagicSystem=0x{gmsRes.Address.ToInt32():X8} ({gmsRes.Detail}), " +
$"FreeHandsAndCastSpell=0x{fhcRes.Address.ToInt32():X8} ({fhcRes.Detail}).");
}
else
{
RynthLog.Compat(
$"Compat: explicit-target cast VAs unresolved (gms={gmsRes.Success}, fhc={fhcRes.Success}) — " +
"targeted casts fail closed.");
}
InstallQueryHealthResponseHook();
// InstallInnerDispatcherHook intentionally disabled 2026-05-14.
// Its anchor-then-scan-backward heuristic (find CALL to
// QueryHealthResponseVa, then walk back ≤0x1000 bytes looking for
// `SUB ESP, 0x1C0`) lands on a function that — on this ACE
// build at least — AC traverses during world-entry, and the
// MinHook trampoline at that entry point hangs the load (player
// stuck on "Entering World", no SendLoginCompleteNotification).
// The 0xF658 character-list and 0xC9 IdentifyObject packets we
// were collecting here are redundantly captured by SmartBoxHooks'
// DispatchSmartBoxEvent / DispatchGameEvent hooks (see
// SmartBoxHooks.DispatchSmartBoxEventDetour → ProcessPotentialCharacterMessage
// at line ~117). Re-enabling requires a tighter pattern that
// *uniquely* identifies the intended inner dispatcher, plus a
// verification that AC's world-load path is unaffected.
// InstallInnerDispatcherHook();
IsInitialized = true;
_statusMessage = "Ready.";
RynthLog.Compat($"Compat: combat hooks ready - cancel=0x{cancelVa:X8}, mode=0x{changeModeVa:X8}, health=0x{queryHealthVa:X8}, melee=0x{meleeVa:X8}, missile=0x{missileVa:X8}");
return true;
}
catch (Exception ex)
{
Reset();
_statusMessage = ex.Message;
RynthLog.Compat($"Compat: combat probe failed - {ex.Message}");
return false;
}
}
public static bool MeleeAttack(uint targetId, int attackHeight, float powerLevel)
{
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueMeleeAttack(targetId, attackHeight, powerLevel);
if (_meleeAttack == null)
return false;
try
{
return _meleeAttack(targetId, attackHeight, Math.Clamp(powerLevel, 0f, 1f));
}
catch
{
return false;
}
}
public static bool MissileAttack(uint targetId, int attackHeight, float accuracyLevel)
{
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueMissileAttack(targetId, attackHeight, accuracyLevel);
if (_missileAttack == null)
return false;
try
{
return _missileAttack(targetId, attackHeight, Math.Clamp(accuracyLevel, 0f, 1f));
}
catch
{
return false;
}
}
public static bool ChangeCombatMode(int combatMode)
{
// P1 marshalling: off-thread mutators run on AC's main thread (via the
// OnEndScene drain) so AC mutates its single-threaded object/animation
// (CSequence) state on the thread that updates it — eliminating the
// off-thread-mutation corruption class (e.g. the CSequence::update_internal
// AV). On the main thread (incl. the drain) this executes directly.
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueChangeCombatMode(combatMode);
// Prefer the CLIENT-level entry point. _changeCombatMode is bound by
// scanning for the function that writes network opcode 0x53
// (CM_Combat::Event_ChangeCombatMode) — that is the packet sender and
// nothing more. It tells the server and leaves the client's own UI
// untouched, so the stance widgets never learn and the toolbar icon sits
// on Peace while the character is in Magic and casting.
//
// ClientCombatSystem::SetCombatMode is the layer above: it sets the mode
// field, sends the same 0x53, AND notifies the UI. Calling it is what a
// toolbar click does. Falls through to the raw sender when the hook isn't
// installed, so behaviour is unchanged if the pattern ever fails to resolve.
if (CombatModeHooks.RequestCombatMode(combatMode))
return true;
if (_changeCombatMode == null)
return false;
try
{
return _changeCombatMode(combatMode);
}
catch
{
return false;
}
}
public static bool CancelAttack()
{
if (_cancelAttack == null)
return false;
try
{
return _cancelAttack();
}
catch
{
return false;
}
}
public static bool QueryHealth(uint targetId)
{
if (_queryHealth == null)
return false;
try
{
return _queryHealth(targetId);
}
catch
{
return false;
}
}
public static bool RequestId(uint objectId)
{
if (_requestId == null || objectId == 0)
return false;
try
{
return _requestId(objectId);
}
catch
{
return false;
}
}
public static bool CastSpell(uint targetId, int spellId)
{
if (spellId <= 0) return false;
if (_castSpellClient == null) return false;
// P2 cast marshalling — drain-BEFORE-tick variant (2026-06-03, attempt 2).
// Off the main thread, enqueue the cast; GameTickHooks drains it on AC's
// game-logic tick (Client::UseTime) BEFORE _originalUseTime runs, so AC's SAME
// tick processes the freshly-set selection + cast (mimics AC's natural
// input -> UseTime flow). Attempt 1 (drain AFTER the tick) landed self-buffs but
// NOT targeted casts: SelectItem + cast initiated at the END of tick N weren't
// processed until tick N+1, by which point the selection was clobbered (target
// held hp=50/50, zero damage).
//
// Off-thread casting is NOT a safe fallback: it races AC's cast/UI state and
// AVs UNCAUGHT (0xC0000005 WRITE in UIElement::GetAttribute_Bool, off the main
// thread, tid != main) — it killed a 37-min P1 soak. So the cast MUST run on the
// main thread; the only open question is landing a targeted cast from the tick,
// which the drain-before order is intended to fix. On the main thread (the
// UseTime drain, or any main-thread caller) this falls through to the direct
// cast below.
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueCast(targetId, (uint)spellId);
// Call ClientMagicSystem::CastSpell directly off the plugin pump thread.
// This is the proven-working casting path (buffs + combat resolve in
// chat). The earlier EndScene-marshalled variant (AcMainThreadQueue,
// drained from OnEndScene) was REVERTED 2026-05-19: EndScene fires AC's
// IncrementBusyCount but is not the context that drives the cast state
// machine to completion, so combat casts never produced a projectile /
// damage / "You cast" chat — busy leaked, AC's single cast slot jammed
// "Casting <spell>" client-wide, and even manual casting died. Do NOT
// re-introduce queue/EndScene marshalling for casts.
// The documented object-teardown AV (0x0055FA24 [null+0x40] /
// 0x00416C86 [null+0x28]) is contained per-callsite by the SEH
// trampoline below (__try/__except in RynthCore.SehTrampoline.dll),
// which is the correct fix for that AV. AC's CastSpell reads its
// "currently selected target" when targetIsSelected=1; SelectItem
// first so AC's selection matches the caller's intent.
if (_castSpellClient != null)
{
try
{
// TARGETED cast (targetId != 0): explicit-target path — RC2-proven, NO
// SelectItem. GetMagicSystem() -> FreeHandsAndCastSpell(mgr, spellId, targetId).
// The old SelectItem + CastSpell(targetIsSelected=1) two-step relied on AC's
// global selection ([magicSysSingleton+0xF4], read inside 0x00568DE0) surviving
// the marshal onto AC's tick — it didn't (targets held hp=50/50, zero damage).
// FreeHandsAndCastSpell takes the target as an explicit arg and auto-readies the
// wand, so there is nothing to clobber.
if (targetId != 0)
{
if (SehTrampoline.IsAvailable && _freeHandsCastPtr != IntPtr.Zero && _getMagicSystemPtr != IntPtr.Zero)
{
IntPtr mgr = SehTrampoline.CdeclPtrVoid(_getMagicSystemPtr, out bool avMgr);
if (avMgr || mgr == IntPtr.Zero)
{
if (System.Threading.Interlocked.Increment(ref _sehAvLogCount) <= 20)
RynthLog.Compat($"[SEH] GetMagicSystem null/AV — targeted cast skipped spell={spellId} target=0x{targetId:X8}");
return false;
}
// Measure the real m_cBusy delta around the call: the direct cast
// increments it (wand-ready + cast, often +2) but never registers
// the queued action whose completion would decrement — the per-cast
// busy leak. BusyCountHooks reconciles the delta once the cast
// gesture completes.
int busyBefore = BusyCountHooks.CaptureRealBusyForCast();
bool okCast = SehTrampoline.FreeHandsCast(_freeHandsCastPtr, mgr, (uint)spellId, targetId);
BusyCountHooks.NoteDirectCastIssued(busyBefore);
if (!okCast && System.Threading.Interlocked.Increment(ref _sehAvLogCount) <= 20)
RynthLog.Compat($"[SEH] AV in FreeHandsAndCastSpell spell={spellId} target=0x{targetId:X8} — caught");
return okCast;
}
return false; // trampoline / VAs unavailable — fail closed (never the off-thread SelectItem two-step)
}
// SELF cast (targetId == 0): the proven CastSpell(spellId, targetIsSelected=0)
// path — no selection dependency; lands buffs reliably.
if (SehTrampoline.IsAvailable && _castSpellClientPtr != IntPtr.Zero)
{
// Same per-cast busy-leak reconciliation as the targeted path —
// buff self-casts were the dominant leak source (4322 plugin
// clears / 10h soak, nearly all on buffs).
int busyBefore = BusyCountHooks.CaptureRealBusyForCast();
bool ok = SehTrampoline.CdeclVoidUintByte(_castSpellClientPtr, (uint)spellId, 0);
BusyCountHooks.NoteDirectCastIssued(busyBefore);
if (!ok && System.Threading.Interlocked.Increment(ref _sehAvLogCount) <= 20)
RynthLog.Compat($"[SEH] AV in self-CastSpell spell={spellId} — caught");
return ok;
}
{
int busyBefore = BusyCountHooks.CaptureRealBusyForCast();
_castSpellClient((uint)spellId, 0);
BusyCountHooks.NoteDirectCastIssued(busyBefore);
}
return true;
}
catch
{
// Fall through to "refuse" rather than the pattern-scanned
// _castSpell — see the comment block on that fallback.
}
}
// No safe fallback — fail closed. The pattern-scanned game-action-0x4A
// wrapper (_castSpell) resolves to the WRONG function on this
// acclient.exe: CombatPrologue (83 EC 0C 53 56 57 E8) is shared by many
// AC functions and FindPrologueBefore takes the FIRST match, which is
// not the cast wrapper, so calling it would crash AC. The 2026-05-14
// "binaries are byte-identical so the pattern is fine" reasoning was
// wrong: identity makes the pattern consistently wrong on BOTH retail
// and ACE, not correct.
// ⚠ 2026-05-18, DUMP-VERIFIED: the AVs at 0x00416C86 [null+0x28] and
// 0x0055FA24 [null+0x40] that older notes/comments blamed on this
// fallback are NOT cast-related. Resolved via acclient.map they are
// DBOCache::DestroyObj and CPlayerSystem::CalculateObjectRangeChecks →
// List<ObjectRangeInfo>::remove — AC OBJECT-TEARDOWN code tripping over
// a corrupted object/range list (async lifecycle corruption class, not
// spellcasting). Do NOT chase CastSpell for these. See
// rynthcore_castspell_fallback_pitfall.md / rynthcore_crash_investigation.md.
// _castSpellClient (the verified ClientMagicSystem::CastSpell VA bound
// in Probe) is the only safe path; if it is unavailable we refuse the
// cast. BuffManager.CastSpellInner and CombatManager both handle a
// false / no-op return without wedging (skip the spell, retry next
// cycle), so refusing is strictly safer than crashing the client.
return false;
}
// Called by AcMainThreadQueue.Drain on AC's main thread (EndScene path).
// The preceding queued SelectItem entry already set AC's selection, so
// cast with targetIsSelected=1. Defensive: never throw into the drain loop.
internal static void ExecuteQueuedCast(uint spellId)
{
if (_castSpellClient == null) return;
if (SehTrampoline.IsAvailable && _castSpellClientPtr != IntPtr.Zero)
{
bool ok = SehTrampoline.CdeclVoidUintByte(_castSpellClientPtr, spellId, 1);
if (!ok && System.Threading.Interlocked.Increment(ref _sehAvLogCount) <= 20)
RynthLog.Compat($"[SEH] AV in CastSpell spell={spellId} — caught, cast skipped");
return;
}
try { _castSpellClient.Invoke(spellId, 1); } catch { }
}
public static int MapAttackHeight(int uiHeight)
{
return uiHeight switch
{
0 => AttackHeightLow,
2 => AttackHeightHigh,
_ => AttackHeightMedium
};
}
private static void Reset()
{
_meleeAttack = null;
_missileAttack = null;
_changeCombatMode = null;
_cancelAttack = null;
_queryHealth = null;
_requestId = null;
_castSpell = null;
_castSpellClient = null;
_castSpellClientPtr = IntPtr.Zero;
_getMagicSystemPtr = IntPtr.Zero;
_freeHandsCastPtr = IntPtr.Zero;
_queryHealthResponseDetour = null;
_originalQueryHealthResponse = null;
_identifyObjectDetour = null;
_originalIdentifyObject = null;
IsInitialized = false;
}
/// Hooks the inner game-event dispatcher at its entry point. The dispatcher is thiscall
/// with RET 8: uint __thiscall Dispatch(void* buffer, uint size). We intercept 0xC9
/// (IdentifyObject response) events and parse the CreatureProfile for health/maxHealth.
/// </summary>
private static IntPtr _originalInnerDispatcherPtr;
private static void InstallInnerDispatcherHook()
{
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
return;
byte[] text = textSection.Bytes;
int textBase = textSection.TextBaseVa;
// Find the call to QueryHealthResponse to anchor the inner dispatcher region
int anchorOff = -1;
for (int i = 0; i < text.Length - 5; i++)
{
if (text[i] != 0xE8) continue;
int rel = BitConverter.ToInt32(text, i + 1);
if (textBase + i + 5 + rel == QueryHealthResponseVa)
{
anchorOff = i;
break;
}
}
if (anchorOff < 0)
{
RynthLog.Compat("Compat: dispatch scan - no CALL to QueryHealthResponse found.");
return;
}
// Find the inner dispatcher function entry by searching backward for SUB ESP, 0x1C0
int subEspOff = -1;
for (int i = anchorOff; i >= Math.Max(0, anchorOff - 0x1000); i--)
{
if (text[i] == 0x81 && text[i + 1] == 0xEC &&
text[i + 2] == 0xC0 && text[i + 3] == 0x01 &&
text[i + 4] == 0x00 && text[i + 5] == 0x00)
{
subEspOff = i;
break;
}
}
if (subEspOff < 0)
{
RynthLog.Compat("Compat: inner dispatcher SUB ESP not found.");
return;
}
int funcEntryVa = textBase + subEspOff;
RynthLog.Verbose($"Compat: inner dispatcher entry @ 0x{funcEntryVa:X8}");
try
{
unsafe
{
delegate* unmanaged[Thiscall]<IntPtr, IntPtr, uint, uint> pDetour = &InnerDispatcherDetour;
MinHook.Hook(new IntPtr(funcEntryVa), (IntPtr)pDetour, out _originalInnerDispatcherPtr);
RynthLog.Verbose($"Compat: inner dispatcher hook installed @ 0x{funcEntryVa:X8}");
}
}
catch (Exception ex)
{
RynthLog.Compat($"Compat: inner dispatcher hook failed - {ex.Message}");
}
}
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvThiscall)])]
private static unsafe uint InnerDispatcherDetour(IntPtr thisPtr, IntPtr buffer, uint size)
{
var pOriginal = (delegate* unmanaged[Thiscall]<IntPtr, IntPtr, uint, uint>)_originalInnerDispatcherPtr;
try
{
if (buffer != IntPtr.Zero && size >= 4)
{
uint eventType = unchecked((uint)Marshal.ReadInt32(buffer));
// Intercept IdentifyObject response (0xC9)
if (eventType == 0xC9 && size >= 16)
TryParseIdentifyResponse(buffer, size);
// Intercept character list packet (0xF658) — login screen
if (eventType == 0xF7EA || eventType == 0xF658)
CharacterCaptureHooks.ProcessRawCharacterMessage(buffer, size);
}
}
catch
{
}
return pOriginal(thisPtr, buffer, size);
}
private static int _identifyWireLogCount;
private static int _mobHpReadLogCount;
/// <summary>
/// Parses the IdentifyObject response (game event 0xC9) to extract
/// health/maxHealth from the CreatureProfile section. Wire format is
/// authoritative per ACE AppraiseInfoExtensions.Write / CreatureProfile:
///
/// header: [_(4)][objectId(4)][Flags(4)][Success(4)] (parser base+0..+15)
/// then sections, in ACE *write* order (NOT flag-bit order):
/// 0x0001 IntStatsTable hashtbl, entry 8 (u32 key + i32)
/// 0x2000 Int64StatsTable hashtbl, entry 12 (u32 key + i64)
/// 0x0002 BoolStatsTable hashtbl, entry 8 (u32 key + u32)
/// 0x0004 FloatStatsTable hashtbl, entry 12 (u32 key + f64)
/// 0x0008 StringStatsTable hashtbl, string entries (u32 key + str16L)
/// 0x1000 DidStatsTable hashtbl, entry 8 (u32 key + u32)
/// 0x0010 SpellBook list: i32 count + count*u32
/// 0x0080 ArmorProfile fixed 32 bytes (8 floats)
/// 0x0100 CreatureProfile &lt;-- target
/// hashtbl header = ushort count + ushort numBuckets (4 bytes).
///
/// CreatureProfile: cpFlags(4), Health(4), HealthMax(4),
/// if cpFlags&amp;0x8: Str,End,Quick,Coord,Focus,Self,
/// Stamina,Mana,StaminaMax,ManaMax (10*4),
/// if cpFlags&amp;0x1: AttrHighlights(2)+AttrColors(2).
/// </summary>
internal static void TryParseIdentifyResponse(IntPtr buffer, uint size)
{
try
{
// Header: _(4) + objectId(4) + flags(4) + success(4) = 16 bytes
uint objectId = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, 4)));
uint flags = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, 8)));
uint success = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, 12)));
if (success == 0 || objectId == 0)
return;
const uint CreatureProfile = 0x0100;
if ((flags & CreatureProfile) == 0)
return;
int offset = 16; // Past the header
int iSize = (int)size;
// Skip sections written before CreatureProfile, in ACE write order.
if ((flags & 0x0001) != 0 && !SkipPackedHashTable(buffer, iSize, ref offset, 8))
return; // IntStatsTable
if ((flags & 0x2000) != 0 && !SkipPackedHashTable(buffer, iSize, ref offset, 12))
return; // Int64StatsTable
if ((flags & 0x0002) != 0 && !SkipPackedHashTable(buffer, iSize, ref offset, 8))
return; // BoolStatsTable
if ((flags & 0x0004) != 0 && !SkipPackedHashTable(buffer, iSize, ref offset, 12))
return; // FloatStatsTable
if ((flags & 0x0008) != 0 && !SkipStringHashTable(buffer, iSize, ref offset))
return; // StringStatsTable
if ((flags & 0x1000) != 0 && !SkipPackedHashTable(buffer, iSize, ref offset, 8))
return; // DidStatsTable
if ((flags & 0x0010) != 0 && !SkipPackableListUInt(buffer, iSize, ref offset))
return; // SpellBook
if ((flags & 0x0080) != 0)
{
offset += 32; // ArmorProfile = 8 floats, fixed
if (offset > iSize)
return;
}
// CreatureProfile: cpFlags(4), Health(4), HealthMax(4), ...
if (offset + 12 > iSize)
return;
uint cpFlags = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset)));
uint health = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset + 4)));
uint maxHealth = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset + 8)));
uint stamina = 0, maxStamina = 0, mana = 0, maxMana = 0;
if ((cpFlags & 0x8) != 0 && offset + 52 <= iSize)
{
// Str(+12) End(+16) Quick(+20) Coord(+24) Focus(+28) Self(+32)
// Stamina(+36) Mana(+40) StaminaMax(+44) ManaMax(+48)
stamina = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset + 36)));
mana = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset + 40)));
maxStamina = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset + 44)));
maxMana = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, offset + 48)));
}
int log = Interlocked.Increment(ref _identifyWireLogCount);
if (log <= 20)
RynthLog.Compat($"Compat: identify-wire obj=0x{objectId:X8} flags=0x{flags:X4} cp=0x{cpFlags:X} hp={health}/{maxHealth}");
if (maxHealth > 0 && maxHealth < 1_000_000)
{
var vitals = new CreatureVitals(health, maxHealth, stamina, maxStamina, mana, maxMana);
ObjectQualityCache.SetCreatureVitals(objectId, vitals);
float ratio = (float)health / maxHealth;
PluginManager.QueueUpdateHealth(objectId, ratio, health, maxHealth);
uint playerId = ClientHelperHooks.GetPlayerId();
if (playerId != 0 && objectId == playerId)
PlayerVitalsHooks.SeedMaxVitalsFromIdentify(maxHealth, maxStamina, maxMana);
}
}
catch
{
}
}
/// <summary>Skips a packed hash table with fixed-size entries.</summary>
private static bool SkipPackedHashTable(IntPtr buffer, int size, ref int offset, int entrySize)
{
if (offset + 4 > size) return false;
ushort entryCount = unchecked((ushort)Marshal.ReadInt16(IntPtr.Add(buffer, offset)));
offset += 4; // header: count(2) + buckets(2)
int dataSize = entryCount * entrySize;
offset += dataSize;
return offset <= size;
}
/// <summary>Skips a packed hash table with string values (variable length).</summary>
private static bool SkipStringHashTable(IntPtr buffer, int size, ref int offset)
{
if (offset + 4 > size) return false;
ushort entryCount = unchecked((ushort)Marshal.ReadInt16(IntPtr.Add(buffer, offset)));
offset += 4; // header
for (int i = 0; i < entryCount; i++)
{
if (offset + 6 > size) return false;
offset += 4; // key (uint32)
// AC packed string: ushort length, then chars, then padding to 4-byte boundary
ushort strLen = unchecked((ushort)Marshal.ReadInt16(IntPtr.Add(buffer, offset)));
offset += 2;
offset += strLen;
// Align to 4-byte boundary (from the start of the string field, which is offset-2-strLen)
int totalStringField = 2 + strLen;
int padding = (4 - (totalStringField % 4)) % 4;
offset += padding;
}
return offset <= size;
}
/// <summary>Skips a PackableList&lt;uint&gt;: int32 count + count*uint32.</summary>
private static bool SkipPackableListUInt(IntPtr buffer, int size, ref int offset)
{
if (offset + 4 > size) return false;
int count = Marshal.ReadInt32(IntPtr.Add(buffer, offset));
offset += 4;
if (count < 0 || count > 100_000) return false;
offset += count * 4;
return offset <= size;
}
private static void InstallQueryHealthResponseHook()
{
if (_originalQueryHealthResponse != null)
return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
return;
HookResolver.ResolveResult resolved = HookResolver.Resolve(textSection, "CombatAction.QueryHealthResponse", QueryHealthResponsePattern, QueryHealthResponseVa);
if (!resolved.Success)
{
RynthLog.Compat($"Compat: query-health-response hook skipped - unresolved 0x{QueryHealthResponseVa:X8}");
return;
}
IntPtr responsePtr = resolved.Address;
_queryHealthResponseDetour = QueryHealthResponseDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_queryHealthResponseDetour);
IntPtr originalPtr = MinHook.HookCreate(responsePtr, detourPtr);
_originalQueryHealthResponse = Marshal.GetDelegateForFunctionPointer<QueryHealthResponseDelegate>(originalPtr);
Thread.MemoryBarrier();
MinHook.Enable(responsePtr);
RynthLog.Verbose($"Compat: query-health-response hook ready - Handle_Combat__QueryHealthResponse=0x{QueryHealthResponseVa:X8}");
}
private static uint QueryHealthResponseDetour(IntPtr uiQueueManager, IntPtr buffer, uint size)
{
try
{
if (buffer != IntPtr.Zero && size >= 12)
{
uint opcode = unchecked((uint)Marshal.ReadInt32(buffer));
uint targetId = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(buffer, 4)));
float healthRatio = Marshal.PtrToStructure<float>(IntPtr.Add(buffer, 8));
// Resolve absolute health: first check the cache, then try a direct
// read via InqAttribute2ndStruct (works after an IdentifyObject response
// has populated the weenie's qualities). This detour runs on the game
// thread so the direct read is safe.
uint maxHealth = 0;
uint currentHealth = 0;
uint playerId = ClientHelperHooks.GetPlayerId();
// Appraisal-only (see SmartBoxHooks.TryQueueHealthUpdate):
// emit absolute ONLY from a real appraisal's wire-parsed
// CreatureProfile; otherwise max=0 → UI shows %. ACE creature
// Inq / pointer-cache maxes are unreliable.
if (ObjectQualityCache.TryGetCreatureVitals(targetId, out CreatureVitals exact) && exact.MaxHealth > 0)
{
maxHealth = exact.MaxHealth;
currentHealth = (uint)Math.Round(maxHealth * Math.Clamp(healthRatio, 0f, 1f));
}
else if (targetId != 0 && targetId != playerId)
{
// No appraisal yet: read the mob's real MaxHealth straight from its
// CACQualities (InqAttribute2nd on the qualities sub-object, SEH-
// guarded). This is what fills in true HP (e.g. Olthoi Swarm
// Harvester = 175) BEFORE the player's appraise skill is high enough
// to produce a CreatureProfile. The earlier bug passed the weenie
// ptr as `this`; InqAttribute2nd derefs this+0x60 for the attribute
// cache, so it MUST get the CACQualities sub-object (resolved inside
// TryReadCreatureMaxHealth). Gated to the main thread inside
// TryGetQualitiesPtr — this detour runs on AC's game thread.
if (ClientObjectHooks.TryReadCreatureMaxHealth(targetId, out uint mobMax)
&& mobMax > 0 && mobMax < 1_000_000)
{
maxHealth = mobMax;
currentHealth = (uint)Math.Round(maxHealth * Math.Clamp(healthRatio, 0f, 1f));
ObjectQualityCache.SetCreatureVitals(targetId,
new CreatureVitals(currentHealth, maxHealth, 0, 0, 0, 0));
int hlog = Interlocked.Increment(ref _mobHpReadLogCount);
if (hlog <= 20)
RynthLog.Compat($"Compat: mob-hp qualities-read id=0x{targetId:X8} maxHp={maxHealth} ratio={healthRatio:F3}");
}
}
// If this response is for the player, derive true MaxHealth from the ratio.
// e.g. health=92541, ratio=0.925 → trueMax ≈ 99999
if (playerId != 0 && targetId == playerId && healthRatio > 0f && healthRatio <= 1f)
PlayerVitalsHooks.UpdateMaxFromHealthRatio(healthRatio);
PluginManager.QueueUpdateHealth(targetId, healthRatio, currentHealth, maxHealth);
}
}
catch
{
}
return _originalQueryHealthResponse != null
? _originalQueryHealthResponse(uiQueueManager, buffer, size)
: 0;
}
}

View file

@ -0,0 +1,308 @@
using System;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.Compatibility;
internal static class CombatModeHooks
{
private const int SetCombatModeFallbackVa = 0x0056CB80;
// ClientCombatSystem::SetCombatMode(int newMode, int playerRequested)
// Loads current mode from [esi+0x1C], compares with new arg from [esp+0x14],
// jumps if equal. Distinctive 0x0F 0x84 EA 01 00 00 (je rel32 +0x1EA).
private static readonly byte?[] SetCombatModePattern =
[
0x51, 0x53, 0x56, 0x8B, 0xF1, 0x8B, 0x46, 0x1C,
0x57, 0x8B, 0x7C, 0x24, 0x14, 0x3B, 0xF8, 0x8B,
0xD8, 0x0F, 0x84, 0xEA, 0x01, 0x00, 0x00, 0x8A,
0x44, 0x24, 0x18, 0x84, 0xC0
];
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void SetCombatModeDelegate(IntPtr thisPtr, int newCombatMode, int playerRequested);
private static SetCombatModeDelegate? _originalSetCombatMode;
private static SetCombatModeDelegate? _setCombatModeDetour;
private static IntPtr _targetAddress;
private static string _statusMessage = "Not probed yet.";
// Defaults to NonCombat (not 0) so an off-thread reader that arrives before
// the first SetCombatMode detour fire still gets a sane value instead of an
// unnormalized 0.
private static int _lastObservedCombatMode = CombatActionHooks.CombatModeNonCombat;
// ClientCombatSystem::s_pCombatSystem — pointer to the singleton in .data.
// This is a DATA address (not code), so it can't be pattern-scanned in .text;
// it's left as a fallback constant. If the binary's .data layout shifted, the
// first dereference would AV and CrashLogger would log it as
// ACCESS_VIOLATION inside the engine's thiscall thunk.
private const uint CombatSystemPtrVa = 0x0087166C;
private const int CombatModeOffset = 28;
// Phase B: resolve s_pCombatSystem's address by code-xref ("mov [s_pCombatSystem],esi" =
// 89 35 <addr>), operand at offset 2; the VA stays as fallback. Resolved in Initialize.
private static readonly byte?[] PatXrefCombatSystemPtr = [ 0x89, 0x35, null, null, null, null, 0x8B, 0x06 ];
private static uint _combatSystemPtrAddr = CombatSystemPtrVa;
public static bool IsInstalled { get; private set; }
public static string StatusMessage => _statusMessage;
// Deep-audit finding #4 (2026-06-18): this used to raw-dereference the
// ClientCombatSystem singleton unconditionally, including off AC's main
// thread — a teardown-window read (relog/portal, singleton being torn
// down) can land on a freed/mid-reassignment pointer, an uncatchable AV
// under NativeAOT. SetCombatModeDetour already runs ON the main thread
// (it's the inbound-echo hook) and maintains _lastObservedCombatMode as a
// main-thread-verified cache — off-thread callers get that instead of
// touching AC memory at all.
public static unsafe int ReadCurrentCombatMode()
{
if (!MainThreadGuard.IsOnMainThread())
return Volatile.Read(ref _lastObservedCombatMode);
try
{
IntPtr combatSystemPtrAddr = (IntPtr)_combatSystemPtrAddr;
if (!ClientObjectHooks.IsReadablePointer(combatSystemPtrAddr))
return Volatile.Read(ref _lastObservedCombatMode);
IntPtr combatSystem = *(IntPtr*)_combatSystemPtrAddr;
if (combatSystem == IntPtr.Zero || !ClientObjectHooks.IsReadablePointer(combatSystem + CombatModeOffset))
return CombatActionHooks.CombatModeNonCombat;
int raw = NormalizeCombatMode(*(int*)(combatSystem + CombatModeOffset));
// Heal the off-thread cache from this live main-thread read.
//
// _lastObservedCombatMode is only advanced by the detour, which fires
// on a mode CHANGE. After a hot reload or a fresh client it starts at
// its NonCombat default, so if the character is already in Magic and
// stays there, no change ever occurs, the detour never fires, and the
// cache stays wrong forever. Off-thread callers then read NonCombat
// and request Magic in a loop that cannot succeed — nothing needs
// changing — until EnsureMagicMode's deadlock recovery re-equips the
// wand and forces a real transition. That is the 8s stance stall seen
// at 01:49 (after a client restart) and 10:36 (after a reload) on
// 2026-09-03, both visible as an unnecessary unwield/re-wield.
//
// Safe for the change-detection above: the detour compares against
// this value, so healing it to the truth only suppresses events that
// would have reported a change that did not happen.
Volatile.Write(ref _lastObservedCombatMode, raw);
return raw;
}
catch
{
return Volatile.Read(ref _lastObservedCombatMode);
}
}
/// <summary>
/// Request a combat-mode change the way the CLIENT does it, by calling
/// ClientCombatSystem::SetCombatMode(newMode, playerRequested: 1).
///
/// Why this exists: CombatActionHooks.ChangeCombatMode binds the function that
/// writes network opcode 0x53 (CM_Combat::Event_ChangeCombatMode) and calls it
/// directly. That is the bottom of the stack — it tells the SERVER, and nothing
/// else. SetCombatMode is the layer above it, and it does three things:
/// * sets the client's own mode field,
/// * calls CM_Combat::Event_ChangeCombatMode → sends 0x53 to the server,
/// * calls CM_Combat::SendNotice_SetCombatMode → notifies the UI widgets
/// (gmCombatUI / gmToolbarUI / gmSpellcastingUI each have a
/// RecvNotice_SetCombatMode handler).
/// Going in below it meant the stance widgets were never told, so the toolbar
/// icon kept showing Peace while the character was genuinely in Magic and
/// casting — reported from live play 2026-09-02.
///
/// playerRequested: 1 marks this as player-initiated, which is the path the
/// toolbar button itself takes. The inbound server echo arrives as 0, and the
/// UI-refresh branch is skipped there because a real click has already updated
/// the widget optimistically — which is exactly why the echo alone never fixed
/// the icon for us.
///
/// Calls the trampoline, so our own detour does not re-enter. _lastObservedCombatMode
/// is deliberately NOT updated here: it must keep meaning "what the server
/// decided", or a server that refuses the stance (the documented wand-stance
/// wedge) would look like it had accepted it. The echo updates it.
///
/// Main thread only — the caller marshals. Returns false if the hook isn't
/// installed or the singleton isn't readable, so the caller can fall back.
/// </summary>
public static unsafe bool RequestCombatMode(int combatMode)
{
if (!IsInstalled || _originalSetCombatMode == null)
{ LogRequestPath(combatMode, -1, "FALLBACK: hook not installed"); return false; }
if (!MainThreadGuard.IsOnMainThread())
{ LogRequestPath(combatMode, -1, "FALLBACK: off main thread"); return false; }
try
{
IntPtr combatSystemPtrAddr = (IntPtr)_combatSystemPtrAddr;
if (!ClientObjectHooks.IsReadablePointer(combatSystemPtrAddr))
{ LogRequestPath(combatMode, -1, "FALLBACK: s_pCombatSystem address unreadable"); return false; }
IntPtr combatSystem = *(IntPtr*)_combatSystemPtrAddr;
if (combatSystem == IntPtr.Zero || !ClientObjectHooks.IsReadablePointer(combatSystem + CombatModeOffset))
{ LogRequestPath(combatMode, -1, "FALLBACK: combat system singleton unreadable"); return false; }
// Read the field SetCombatMode itself compares against ([esi+0x1C]).
// Its prologue jumps past the whole body when the request equals the
// current mode — so if these are equal, the call sends NO packet and
// notifies nothing, and the stance silently will not change. That is
// the leading suspect for the 8s stance stall seen on force rebuff
// (2026-09-03 01:49), so record it explicitly rather than guess.
int cur = *(int*)(combatSystem + CombatModeOffset);
// Same healing as ReadCurrentCombatMode: this is a live main-thread
// read, so it is strictly better than a stale cached default.
Volatile.Write(ref _lastObservedCombatMode, NormalizeCombatMode(cur));
// The client already believes it is in this mode, so SetCombatMode
// would jump straight past its body: no 0x53 to the server and no UI
// notice. But the SERVER can disagree with the client's field — that
// is exactly the case worth sending — so decline here and let the
// caller fall through to the raw opcode-0x53 sender, which is what
// this code did unconditionally before the client-level path existed.
// Confirmed live 2026-09-03 01:57: req=8 against clientField=8
// swallowed every retry for ~8s until EnsureMagicMode's deadlock
// recovery re-equipped the wand and forced a real transition.
//
// Nothing is lost on the UI side by taking the raw path here: the
// widgets read the same field, and it already holds the requested
// mode, so there is no stale icon to correct.
if (cur == combatMode)
{
LogRequestPath(combatMode, cur, "declining — client field already equals request (SetCombatMode would no-op); using raw 0x53 sender so the server is still told");
return false;
}
_originalSetCombatMode(combatSystem, combatMode, 1);
LogRequestPath(combatMode, cur, "sent via ClientCombatSystem::SetCombatMode(playerRequested=1)");
return true;
}
catch (Exception ex)
{
try { RynthLog.Compat($"CombatModeHooks: RequestCombatMode({combatMode}) threw {ex.GetType().Name}: {ex.Message}"); } catch { }
return false;
}
}
private static string _lastRequestLog = "";
private static long _lastRequestLogTicks;
/// <summary>One line per combat-mode request telling us which path ran.
/// Stance flips are rare, but a retry loop would repeat, so identical
/// messages are throttled to 1/s.</summary>
private static void LogRequestPath(int requested, int current, string outcome)
{
try
{
string msg = $"CombatModeHooks: RequestCombatMode(req={requested}, clientField={current}) — {outcome}";
long now = Environment.TickCount64;
if (msg == _lastRequestLog && (now - _lastRequestLogTicks) < 1000) return;
_lastRequestLog = msg;
_lastRequestLogTicks = now;
RynthLog.Compat(msg);
}
catch { }
}
public static void Initialize()
{
if (IsInstalled)
return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
{
_statusMessage = "acclient.exe not available.";
return;
}
var resolved = HookResolver.Resolve(textSection, "CombatModeHooks.SetCombatMode",
SetCombatModePattern, SetCombatModeFallbackVa);
if (!resolved.Success)
{
_statusMessage = $"Resolve failed ({resolved.Detail}).";
return;
}
_combatSystemPtrAddr = (uint)HookResolver.ResolveData(textSection, "CombatMode.s_pCombatSystem", PatXrefCombatSystemPtr, 2, (int)CombatSystemPtrVa).Address.ToInt32();
try
{
_targetAddress = resolved.Address;
_setCombatModeDetour = SetCombatModeDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_setCombatModeDetour);
_originalSetCombatMode = Marshal.GetDelegateForFunctionPointer<SetCombatModeDelegate>(
MinHook.HookCreate(_targetAddress, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(_targetAddress);
IsInstalled = true;
_statusMessage = $"Hooked ClientCombatSystem::SetCombatMode @ 0x{_targetAddress.ToInt32():X8}.";
RynthLog.Compat($"CombatModeHooks: install ok.");
}
catch (Exception ex)
{
_statusMessage = ex.Message;
RynthLog.Compat($"CombatModeHooks: install threw {ex.GetType().Name}: {ex.Message}");
}
}
private static int _fires;
private static int _lastLoggedMode = int.MinValue;
private static long _lastLogTicks;
private static void SetCombatModeDetour(IntPtr thisPtr, int newCombatMode, int playerRequested)
{
// First detour to fire latches AC's main thread ID so background
// threads (DecalCoexistence plugin-tick, panel snapshot, etc.) can
// refuse to call into AC's non-thread-safe internals.
MainThreadGuard.RecordIfFirst();
RecursionGuard.Tick("CombatModeHooks.SetCombatMode");
// This detour fires on the INBOUND server echo (RecvNotice_SetCombatMode ->
// ClientCombatSystem::SetCombatMode), so it reflects what the SERVER decided,
// not what the plugin requested. The old `_fires <= 3` lifetime cap went dark
// hours before any wedge, hiding the diagnosis. Log every distinct mode plus
// repeats throttled to 1/s, so a wand-stance wedge (server re-echoing
// NonCombat=1 against repeated Magic requests) is visible instead of silent.
// See rynthai_combat_busy_wedge ADDENDUM 5.
long nowTicks = Environment.TickCount64;
if (++_fires <= 3 || newCombatMode != _lastLoggedMode || (nowTicks - _lastLogTicks) >= 1000)
{
_lastLoggedMode = newCombatMode;
_lastLogTicks = nowTicks;
RynthLog.Compat($"CombatModeHooks: SetCombatMode fired #{_fires} mode={newCombatMode} requested={playerRequested} (main TID = {MainThreadGuard.MainThreadId})");
}
try
{
_originalSetCombatMode!(thisPtr, newCombatMode, playerRequested);
}
catch (Exception ex)
{
try { RynthLog.Compat($"CombatModeHooks: original threw {ex.GetType().Name}: {ex.Message}"); } catch { }
throw;
}
int currentCombatMode = NormalizeCombatMode(newCombatMode);
int previousCombatMode = Interlocked.Exchange(ref _lastObservedCombatMode, currentCombatMode);
if (currentCombatMode == previousCombatMode)
return;
PluginManager.QueueCombatModeChange(currentCombatMode, previousCombatMode);
}
private static int NormalizeCombatMode(int combatMode)
{
return combatMode switch
{
CombatActionHooks.CombatModeNonCombat => CombatActionHooks.CombatModeNonCombat,
CombatActionHooks.CombatModeMelee => CombatActionHooks.CombatModeMelee,
CombatActionHooks.CombatModeMissile => CombatActionHooks.CombatModeMissile,
CombatActionHooks.CombatModeMagic => CombatActionHooks.CombatModeMagic,
_ => combatMode
};
}
}

View file

@ -0,0 +1,502 @@
using System;
using System.Runtime.InteropServices;
namespace RynthCore.Engine.Compatibility;
internal static class CommandInterpreterHooks
{
private const int VtblCommenceJumpIndex = 16;
private const int VtblDoJumpIndex = 17;
private const int VtblSetAutoRunIndex = 51;
private const int ReferenceAccCmdInterpCommenceJump = 0x0058BFD0;
private const int ReferenceAccCmdInterpDoJump = 0x0058BFF0;
private const int ReferenceAccCmdInterpSetMotion = 0x0058C140;
private const int ReferenceCommandInterpreterSetAutoRun = 0x006B5790;
private const int ReferenceCommandInterpreterStopCompletely = 0x006B4A90;
private const int ReferenceCommandInterpreterTurnToHeading = 0x006B54B0;
private const int ReferenceCommandInterpreterPlayerTeleported = 0x006B41F0;
private const int ReferenceCommandInterpreterTakeControlFromServer = 0x006B4210;
private const int ReferenceCommandInterpreterClearAllCommands = 0x006B40E0;
private const int SetMotionOffsetFromCommenceJump = ReferenceAccCmdInterpSetMotion - ReferenceAccCmdInterpCommenceJump;
private const int SetMotionOffsetFromDoJump = ReferenceAccCmdInterpSetMotion - ReferenceAccCmdInterpDoJump;
private const int StopCompletelyOffsetFromSetAutoRun = ReferenceCommandInterpreterStopCompletely - ReferenceCommandInterpreterSetAutoRun;
private const int TurnToHeadingOffsetFromSetAutoRun = ReferenceCommandInterpreterTurnToHeading - ReferenceCommandInterpreterSetAutoRun;
private const int PlayerTeleportedOffsetFromSetAutoRun = ReferenceCommandInterpreterPlayerTeleported - ReferenceCommandInterpreterSetAutoRun;
private const int TakeControlOffsetFromSetAutoRun = ReferenceCommandInterpreterTakeControlFromServer - ReferenceCommandInterpreterSetAutoRun;
private const int ClearAllCommandsOffsetFromSetAutoRun = ReferenceCommandInterpreterClearAllCommands - ReferenceCommandInterpreterSetAutoRun;
// Verified unique + lands at the Reference VA offline (tools/pe_pattern.py).
// Primary resolution; the *Offset deltas below remain as fallback only.
private static readonly byte?[] SetMotionPattern = [ 0x8B, 0x41, 0x08, 0x81, 0xEC, 0x0C, 0x01, 0x00 ];
private static readonly byte?[] StopCompletelyPattern = [ 0x56, 0x8B, 0xF1, 0x8B, 0x46, 0x04, 0x85, 0xC0, 0x74, 0x32 ];
private static readonly byte?[] TurnToHeadingPattern = [ 0x83, 0xEC, 0x2C, 0x56, 0x8B, 0xF1, 0x8B, 0x06 ];
private static readonly byte?[] PlayerTeleportedPattern = [ 0x56, 0x8B, 0xF1, 0x8B, 0x06, 0x6A, 0x01, 0x6A ];
private static readonly byte?[] TakeControlFromServerPattern = [ 0x56, 0x8B, 0xF1, 0x8B, 0x46, 0x34, 0x85, 0xC0, 0x74 ];
private static readonly byte?[] ClearAllCommandsPattern = [ 0x56, 0x8B, 0xF1, 0x8D, 0x4E, 0x0C, 0xE8, null, null, null, null, 0x8D, 0x4E, 0x18, 0xE8, null, null, null, null, 0x8D, 0x4E, 0x24, 0x5E ];
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void CommenceJumpDelegate(IntPtr thisPtr);
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void DoJumpDelegate(IntPtr thisPtr, int autonomous);
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void SetAutoRunDelegate(IntPtr thisPtr, int val, int applyMovement);
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void SetMotionDelegate(IntPtr thisPtr, uint motion, int enabled);
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void StopCompletelyDelegate(IntPtr thisPtr);
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void TurnToHeadingDelegate(IntPtr thisPtr, float headingDegrees);
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void PlayerTeleportedDelegate(IntPtr thisPtr);
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void TakeControlFromServerDelegate(IntPtr thisPtr);
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void ClearAllCommandsDelegate(IntPtr thisPtr);
private static IntPtr _smartboxStaticAddr;
private static IntPtr _boundCmdInterp;
private static bool _absResolved;
private static IntPtr _setMotionAbs, _stopCompletelyAbs, _turnToHeadingAbs, _playerTeleportedAbs, _takeControlAbs, _clearAllCommandsAbs;
private static CommenceJumpDelegate? _commenceJump;
private static DoJumpDelegate? _doJump;
private static SetAutoRunDelegate? _setAutoRun;
private static SetMotionDelegate? _setMotion;
private static StopCompletelyDelegate? _stopCompletely;
private static TurnToHeadingDelegate? _turnToHeading;
private static PlayerTeleportedDelegate? _playerTeleported;
private static TakeControlFromServerDelegate? _takeControlFromServer;
private static ClearAllCommandsDelegate? _clearAllCommands;
private static string _statusMessage = "Not probed yet.";
public static bool IsInitialized { get; private set; }
public static bool HasTapJump => _commenceJump != null && _doJump != null;
public static bool HasSetAutoRun => _setAutoRun != null;
public static bool HasSetMotion => _setMotion != null;
public static bool HasStopCompletely => _stopCompletely != null;
public static bool HasTurnToHeading => _turnToHeading != null;
public static bool HasTakeControlFromServer => _takeControlFromServer != null;
public static bool HasClearAllCommands => _clearAllCommands != null;
public static string StatusMessage => _statusMessage;
public static bool Probe()
{
Reset();
if (!AcClientModule.TryReadTextSection(out _))
{
_statusMessage = "acclient.exe not available.";
return false;
}
try
{
if (!SmartBoxLocator.Probe())
{
_statusMessage = SmartBoxLocator.StatusMessage;
return false;
}
if (!TryBindDelegates())
{
if (string.IsNullOrEmpty(_statusMessage))
_statusMessage = "cmdinterp unavailable.";
return false;
}
IsInitialized = true;
_statusMessage = "Ready.";
return true;
}
catch (Exception ex)
{
Reset();
_statusMessage = ex.Message;
RynthLog.Compat($"Compat: command interpreter probe failed - {ex.Message}");
return false;
}
}
// Rate-limited diag counters — see why patrol "creates a route but stands
// still" by surfacing the actual movement API calls in RynthCore.log.
private static int _setAutoRunCalls;
private static int _turnToHeadingCalls;
private static int _setMotionCalls;
private static bool ShouldLogMove(int n) => n <= 3 || (n & 0x7) == 0;
public static bool SetAutoRun(bool enabled)
{
// ⚠ Main thread only (2026-06-12 cross-incident forensics): these
// CommandInterpreter calls were the last direct off-thread AC mutators
// — dump-proven executing 15s after a main thread had wedged. They
// rewrite the locomotion channels of the same CommandInterpreter /
// motion graph the CSequence-AV corruption class kills. Off-thread
// callers marshal through the action ring (drained post-tick,
// gesture-gated) like every other mutator.
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueSetAutoRun(enabled);
int n = System.Threading.Interlocked.Increment(ref _setAutoRunCalls);
if (!TryBindDelegates())
{
if (ShouldLogMove(n))
RynthLog.Compat($"Move: SetAutoRun({enabled}) #{n} — TryBindDelegates failed: {_statusMessage}");
return false;
}
try
{
_setAutoRun!(_boundCmdInterp, enabled ? 1 : 0, 1);
if (ShouldLogMove(n))
RynthLog.Compat($"Move: SetAutoRun({enabled}) #{n} -> ok (cmdInterp=0x{_boundCmdInterp.ToInt32():X8})");
return true;
}
catch (Exception ex)
{
if (ShouldLogMove(n))
RynthLog.Compat($"Move: SetAutoRun({enabled}) #{n} threw {ex.GetType().Name}: {ex.Message}");
return false;
}
}
public static bool SetMotion(uint motion, bool enabled)
{
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueSetMotion(motion, enabled); // same off-thread class as SetAutoRun
if (!TryBindDelegates() || _setMotion == null)
return false;
try
{
_setMotion(_boundCmdInterp, motion, enabled ? 1 : 0);
return true;
}
catch
{
return false;
}
}
public static bool StopCompletely()
{
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueStopCompletely(); // same off-thread class as SetAutoRun
if (!TryBindDelegates() || _stopCompletely == null)
return false;
try
{
_stopCompletely(_boundCmdInterp);
return true;
}
catch
{
return false;
}
}
public static bool TurnToHeading(float headingDegrees)
{
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueTurnToHeading(headingDegrees); // same off-thread class as SetAutoRun
int n = System.Threading.Interlocked.Increment(ref _turnToHeadingCalls);
if (!TryBindDelegates() || _turnToHeading == null)
{
if (ShouldLogMove(n))
RynthLog.Compat($"Move: TurnToHeading({headingDegrees:0.0}) #{n} — bind={(_turnToHeading != null)} status='{_statusMessage}'");
return false;
}
try
{
_turnToHeading(_boundCmdInterp, headingDegrees);
if (ShouldLogMove(n))
RynthLog.Compat($"Move: TurnToHeading({headingDegrees:0.0}) #{n} -> ok");
return true;
}
catch (Exception ex)
{
if (ShouldLogMove(n))
RynthLog.Compat($"Move: TurnToHeading({headingDegrees:0.0}) #{n} threw {ex.GetType().Name}: {ex.Message}");
return false;
}
}
// Recovery triplet: unguarded like the jump trio, but only latent today
// (reached solely from the main-thread-gated ForceResetBusyCount) — public
// API surface though, so gate defensively rather than add queue plumbing
// for a currently-unreached off-thread path (revisit with an ActionKind if
// one of these is ever exposed to off-thread callers).
public static bool PlayerTeleported()
{
if (!MainThreadGuard.IsOnMainThread())
return false;
if (!TryBindDelegates() || _playerTeleported == null)
return false;
try
{
_playerTeleported(_boundCmdInterp);
return true;
}
catch
{
return false;
}
}
public static bool TakeControlFromServer()
{
if (!MainThreadGuard.IsOnMainThread())
return false;
if (!TryBindDelegates() || _takeControlFromServer == null)
return false;
try
{
_takeControlFromServer(_boundCmdInterp);
return true;
}
catch
{
return false;
}
}
public static bool ClearAllCommands()
{
if (!MainThreadGuard.IsOnMainThread())
return false;
if (!TryBindDelegates() || _clearAllCommands == null)
return false;
try
{
_clearAllCommands(_boundCmdInterp);
return true;
}
catch
{
return false;
}
}
// Jump trio marshalled 2026-09-02 (deep-audit finding #2): these called the
// native CommandInterpreter through _boundCmdInterp with zero
// MainThreadGuard gate, unlike every sibling (SetAutoRun/SetMotion/
// StopCompletely/TurnToHeading above), live-exercised off-thread via
// Jumper.cs's Decal-coexistence pump-thread tick.
public static bool TapJump()
{
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueTapJump();
if (!TryBindDelegates())
return false;
try
{
// Mirror the normal keyboard jump path: key-down starts charge,
// key-up immediately executes an autonomous tap jump.
_commenceJump!(_boundCmdInterp);
_doJump!(_boundCmdInterp, 1);
return true;
}
catch
{
return false;
}
}
public static bool CommenceJump()
{
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueCommenceJump();
if (!TryBindDelegates())
return false;
try
{
_commenceJump!(_boundCmdInterp);
return true;
}
catch
{
return false;
}
}
public static bool DoJump(bool autonomous)
{
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueDoJumpAutonomous(autonomous);
if (!TryBindDelegates())
return false;
try
{
_doJump!(_boundCmdInterp, autonomous ? 1 : 0);
return true;
}
catch
{
return false;
}
}
// Resolve the six non-vtable-slot member functions by unique .text signature (primary),
// once and cached — they are static code addresses. On a miss they stay Zero and
// TryBindDelegates falls back to the live-anchor + hardcoded-delta computation (old behavior).
private static void EnsureAbsoluteResolved()
{
if (_absResolved) return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text)) return; // retry next call
HookResolver.ResolveResult r;
r = HookResolver.Resolve(text, "CmdInterp.SetMotion", SetMotionPattern, ReferenceAccCmdInterpSetMotion);
_setMotionAbs = r.Success ? r.Address : IntPtr.Zero;
r = HookResolver.Resolve(text, "CmdInterp.StopCompletely", StopCompletelyPattern, ReferenceCommandInterpreterStopCompletely);
_stopCompletelyAbs = r.Success ? r.Address : IntPtr.Zero;
r = HookResolver.Resolve(text, "CmdInterp.TurnToHeading", TurnToHeadingPattern, ReferenceCommandInterpreterTurnToHeading);
_turnToHeadingAbs = r.Success ? r.Address : IntPtr.Zero;
r = HookResolver.Resolve(text, "CmdInterp.PlayerTeleported", PlayerTeleportedPattern, ReferenceCommandInterpreterPlayerTeleported);
_playerTeleportedAbs = r.Success ? r.Address : IntPtr.Zero;
r = HookResolver.Resolve(text, "CmdInterp.TakeControlFromServer", TakeControlFromServerPattern, ReferenceCommandInterpreterTakeControlFromServer);
_takeControlAbs = r.Success ? r.Address : IntPtr.Zero;
r = HookResolver.Resolve(text, "CmdInterp.ClearAllCommands", ClearAllCommandsPattern, ReferenceCommandInterpreterClearAllCommands);
_clearAllCommandsAbs = r.Success ? r.Address : IntPtr.Zero;
_absResolved = true;
}
private static bool TryBindDelegates()
{
IntPtr selectedStaticAddr = IntPtr.Zero;
IntPtr smartBox = IntPtr.Zero;
IntPtr cmdInterp = IntPtr.Zero;
IntPtr vtable = IntPtr.Zero;
if (!SmartBoxLocator.TryGetSmartBox(out smartBox, out selectedStaticAddr, out string smartBoxFailure))
{
_statusMessage = smartBoxFailure;
return false;
}
try
{
cmdInterp = Marshal.ReadIntPtr(smartBox + SmartBoxLocator.SmartBoxCmdInterpOffset);
if (cmdInterp == IntPtr.Zero)
{
_statusMessage = "SmartBox active but CommandInterpreter not ready.";
return false;
}
vtable = Marshal.ReadIntPtr(cmdInterp);
if (!SmartBoxLocator.IsPointerInModule(vtable))
{
_statusMessage = $"CommandInterpreter vtable looks invalid (0x{vtable.ToInt32():X8}).";
return false;
}
}
catch (Exception ex)
{
_statusMessage = ex.Message;
return false;
}
if (cmdInterp == _boundCmdInterp &&
_commenceJump != null &&
_doJump != null &&
_setAutoRun != null &&
_setMotion != null &&
_stopCompletely != null &&
_turnToHeading != null &&
_playerTeleported != null &&
_takeControlFromServer != null &&
_clearAllCommands != null)
{
_smartboxStaticAddr = selectedStaticAddr;
IsInitialized = true;
_statusMessage = "Ready.";
return true;
}
IntPtr commenceJumpPtr = Marshal.ReadIntPtr(vtable, VtblCommenceJumpIndex * IntPtr.Size);
IntPtr doJumpPtr = Marshal.ReadIntPtr(vtable, VtblDoJumpIndex * IntPtr.Size);
IntPtr setAutoRunPtr = Marshal.ReadIntPtr(vtable, VtblSetAutoRunIndex * IntPtr.Size);
EnsureAbsoluteResolved();
IntPtr setMotionPtr = _setMotionAbs != IntPtr.Zero ? _setMotionAbs : ResolveSetMotionPointer(commenceJumpPtr, doJumpPtr);
IntPtr stopCompletelyPtr = _stopCompletelyAbs != IntPtr.Zero ? _stopCompletelyAbs : AddOffset(setAutoRunPtr, StopCompletelyOffsetFromSetAutoRun);
IntPtr turnToHeadingPtr = _turnToHeadingAbs != IntPtr.Zero ? _turnToHeadingAbs : AddOffset(setAutoRunPtr, TurnToHeadingOffsetFromSetAutoRun);
IntPtr playerTeleportedPtr = _playerTeleportedAbs != IntPtr.Zero ? _playerTeleportedAbs : AddOffset(setAutoRunPtr, PlayerTeleportedOffsetFromSetAutoRun);
IntPtr takeControlPtr = _takeControlAbs != IntPtr.Zero ? _takeControlAbs : AddOffset(setAutoRunPtr, TakeControlOffsetFromSetAutoRun);
IntPtr clearAllCommandsPtr = _clearAllCommandsAbs != IntPtr.Zero ? _clearAllCommandsAbs : AddOffset(setAutoRunPtr, ClearAllCommandsOffsetFromSetAutoRun);
if (!SmartBoxLocator.IsPointerInModule(commenceJumpPtr) ||
!SmartBoxLocator.IsPointerInModule(doJumpPtr) ||
!SmartBoxLocator.IsPointerInModule(setAutoRunPtr) ||
!SmartBoxLocator.IsPointerInModule(setMotionPtr) ||
!SmartBoxLocator.IsPointerInModule(stopCompletelyPtr) ||
!SmartBoxLocator.IsPointerInModule(turnToHeadingPtr) ||
!SmartBoxLocator.IsPointerInModule(playerTeleportedPtr) ||
!SmartBoxLocator.IsPointerInModule(takeControlPtr) ||
!SmartBoxLocator.IsPointerInModule(clearAllCommandsPtr))
{
_statusMessage = "CommandInterpreter pointers look invalid.";
return false;
}
_commenceJump = Marshal.GetDelegateForFunctionPointer<CommenceJumpDelegate>(commenceJumpPtr);
_doJump = Marshal.GetDelegateForFunctionPointer<DoJumpDelegate>(doJumpPtr);
_setAutoRun = Marshal.GetDelegateForFunctionPointer<SetAutoRunDelegate>(setAutoRunPtr);
_setMotion = Marshal.GetDelegateForFunctionPointer<SetMotionDelegate>(setMotionPtr);
_stopCompletely = Marshal.GetDelegateForFunctionPointer<StopCompletelyDelegate>(stopCompletelyPtr);
_turnToHeading = Marshal.GetDelegateForFunctionPointer<TurnToHeadingDelegate>(turnToHeadingPtr);
_playerTeleported = Marshal.GetDelegateForFunctionPointer<PlayerTeleportedDelegate>(playerTeleportedPtr);
_takeControlFromServer = Marshal.GetDelegateForFunctionPointer<TakeControlFromServerDelegate>(takeControlPtr);
_clearAllCommands = Marshal.GetDelegateForFunctionPointer<ClearAllCommandsDelegate>(clearAllCommandsPtr);
_smartboxStaticAddr = selectedStaticAddr;
_boundCmdInterp = cmdInterp;
IsInitialized = true;
_statusMessage = "Ready.";
RynthLog.Verbose("Compat: command interpreter bound");
return true;
}
private static IntPtr ResolveSetMotionPointer(IntPtr commenceJumpPtr, IntPtr doJumpPtr)
{
IntPtr fromCommenceJump = AddOffset(commenceJumpPtr, SetMotionOffsetFromCommenceJump);
IntPtr fromDoJump = AddOffset(doJumpPtr, SetMotionOffsetFromDoJump);
return fromCommenceJump == fromDoJump ? fromCommenceJump : IntPtr.Zero;
}
private static IntPtr AddOffset(IntPtr address, int offset)
{
return new IntPtr(address.ToInt64() + offset);
}
private static void Reset()
{
_smartboxStaticAddr = IntPtr.Zero;
_boundCmdInterp = IntPtr.Zero;
_absResolved = false;
_setMotionAbs = _stopCompletelyAbs = _turnToHeadingAbs = _playerTeleportedAbs = _takeControlAbs = _clearAllCommandsAbs = IntPtr.Zero;
_commenceJump = null;
_doJump = null;
_setAutoRun = null;
_setMotion = null;
_stopCompletely = null;
_turnToHeading = null;
_playerTeleported = null;
_takeControlFromServer = null;
_clearAllCommands = null;
IsInitialized = false;
_statusMessage = "Not probed yet.";
}
}

View file

@ -0,0 +1,88 @@
using System;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.Compatibility;
internal static class CreateObjectHooks
{
private const int CreateObjectVa = 0x005594B0;
// Verified unique + lands at 0x005594B0 offline (tools/pe_pattern.py).
private static readonly byte?[] CreateObjectPattern =
[
0x55, 0x8B, 0x6C, 0x24, 0x08, 0x56, 0x8B, 0xF1, 0x8B, 0x8E
];
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate IntPtr CreateObjectDelegate(IntPtr thisPtr, uint objectId, IntPtr visualDesc, IntPtr physicsDesc, IntPtr weenieDesc);
private static CreateObjectDelegate? _originalCreateObject;
private static CreateObjectDelegate? _createObjectDetour;
private static IntPtr _targetAddress;
private static string _statusMessage = "Not probed yet.";
private static int _dispatchCount;
public static bool IsInstalled { get; private set; }
public static string StatusMessage => _statusMessage;
public static int DispatchCount => _dispatchCount;
public static void Initialize()
{
if (IsInstalled)
return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
{
_statusMessage = "acclient.exe not available.";
return;
}
HookResolver.ResolveResult resolved = HookResolver.Resolve(textSection, "CreateObject.CreateObject", CreateObjectPattern, CreateObjectVa);
if (!resolved.Success)
{
_statusMessage = $"ACCObjectMaint::CreateObject unresolved (VA 0x{CreateObjectVa:X8}).";
RynthLog.Compat($"Compat: create-object hook failed - {_statusMessage}");
return;
}
try
{
_targetAddress = resolved.Address;
_createObjectDetour = CreateObjectDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_createObjectDetour);
_originalCreateObject = Marshal.GetDelegateForFunctionPointer<CreateObjectDelegate>(MinHook.HookCreate(_targetAddress, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(_targetAddress);
IsInstalled = true;
_statusMessage = $"Hooked ACCObjectMaint::CreateObject @ 0x{_targetAddress.ToInt32():X8}.";
RynthLog.Verbose($"Compat: create-object hook ready - CreateObject=0x{_targetAddress.ToInt32():X8}");
}
catch (Exception ex)
{
_statusMessage = ex.Message;
RynthLog.Compat($"Compat: create-object hook failed - {ex.Message}");
}
}
private static IntPtr CreateObjectDetour(IntPtr thisPtr, uint objectId, IntPtr visualDesc, IntPtr physicsDesc, IntPtr weenieDesc)
{
RecursionGuard.Tick("CreateObjectHooks.CreateObject");
if (objectId != 0 && visualDesc != IntPtr.Zero)
PaletteCache.ReadFromObjDesc(objectId, visualDesc);
IntPtr result = _originalCreateObject!(thisPtr, objectId, visualDesc, physicsDesc, weenieDesc);
if (result == IntPtr.Zero || objectId == 0)
return result;
int count = Interlocked.Increment(ref _dispatchCount);
if (count <= 0)
RynthLog.Verbose($"Compat: create object #{count} id=0x{objectId:X8} ptr=0x{result.ToInt32():X8}");
PluginManager.QueueCreateObject(objectId);
AutoIdService.Enqueue(objectId);
return result;
}
}

View file

@ -0,0 +1,495 @@
using System;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// IAT-hooks acclient.exe's <c>kernel32!CreateFileW</c> and <c>CreateFileA</c>
/// imports to force maximally-permissive share semantics on AC's data files.
///
/// Why this exists:
/// <see cref="MultiClientHooks"/> patches AC's <c>OpenDataFile</c> high-level
/// <c>openFlags</c> bit 0x2, which selects AC's "shared" branch — but that
/// branch still translates to a CreateFile call whose <c>dwShareMode</c> may
/// not be wide enough to coexist with handles already held by Decal-injected
/// clients launched by other launchers (Thwargle etc.). Windows file-sharing
/// compatibility is decided by the kernel at CreateFile time, not by AC's
/// internal flag.
///
/// This hook intercepts CreateFile right before the kernel sees it, and for
/// the known DAT paths rewrites:
/// dwDesiredAccess = GENERIC_READ (drop WRITE — DATs are read-only after patch)
/// dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE
/// Other paths pass through untouched.
///
/// Why IAT-hook instead of MinHook on the kernel32 export:
/// Decal coexistence. Decal almost certainly already detours kernel32!CreateFile
/// (that's how Decal-injected Thwargle clients can multibox without a
/// second AC install). IAT-hooking acclient.exe's import slot intercepts only
/// acclient.exe's own calls; our detour's call into the saved IAT pointer
/// still routes through any Decal MinHook trampoline on the kernel32 export.
/// No collision; both hooks fire in order.
/// </summary>
internal static class DatFileShareHooks
{
// We force-share by file *extension* (.dat) rather than an explicit name
// list. Stock retail AC ships portal.dat / cell.dat / client_*.dat, but
// private servers commonly add split client-cell DATs (client_cell_1.dat,
// client_cell_2.dat, ...) and other variants we can't enumerate up front.
// Filtering on extension catches them all without per-server tuning.
// AC only opens .dat files via CreateFile for game data; non-DAT writes
// (logs, prefs, screenshots) pass through unmodified.
private const string DatExtension = ".dat";
private const uint GENERIC_READ = 0x80000000;
private const uint FILE_SHARE_READ = 0x00000001;
private const uint FILE_SHARE_WRITE = 0x00000002;
private const uint FILE_SHARE_DELETE = 0x00000004;
private const uint FILE_SHARE_ALL = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
private const uint PAGE_READWRITE = 0x04;
private const uint PAGE_EXECUTE_READWRITE = 0x40;
[UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Unicode, SetLastError = true)]
private delegate IntPtr CreateFileWDelegate(
IntPtr lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile);
[UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Ansi, SetLastError = true)]
private delegate IntPtr CreateFileADelegate(
IntPtr lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool VirtualProtect(IntPtr lpAddress, uint dwSize, uint flNewProtect, out uint lpflOldProtect);
// Pinned via static field — Marshal.GetFunctionPointerForDelegate keeps a
// weak handle, so the delegate must be reachable for the process lifetime.
private static CreateFileWDelegate? _wDetour;
private static CreateFileADelegate? _aDetour;
// The IAT slot pointer (the address inside the IAT array, NOT the original
// function address) — needed for the unhook path.
private static IntPtr _wIatSlot;
private static IntPtr _aIatSlot;
// What was in the IAT slot when we patched it. Could be the real
// kernel32!CreateFile, or another hooker's detour if they got there first.
private static IntPtr _wOriginalPtr;
private static IntPtr _aOriginalPtr;
private static CreateFileWDelegate? _wOriginal;
private static CreateFileADelegate? _aOriginal;
private static string _statusMessage = "Not probed yet.";
public static bool IsEnabled { get; private set; }
public static bool IsInstalled { get; private set; }
public static string StatusMessage => _statusMessage;
public static void Initialize()
{
if (IsInstalled)
return;
// Diagnostic kill-switch. Set "EnableDatShareHook": false in
// %APPDATA%\RynthCore\engine.json to skip detouring CreateFileA/W
// entirely. Used to isolate this hook as a crash suspect.
if (!Plugins.EngineSettings.EnableDatShareHook)
{
_statusMessage = "DAT share hook disabled via engine.json (EnableDatShareHook=false).";
RynthLog.Info($"Compat: {_statusMessage}");
return;
}
// Gate behind AllowMultipleClients. If the user has multi-client off,
// they're not multiboxing, so we have no reason to widen DAT sharing.
if (!LauncherSettings.AllowMultipleClientsEnabled)
{
_statusMessage = "Multi-client disabled — DAT share hook skipped.";
RynthLog.Verbose($"Compat: {_statusMessage}");
return;
}
IsEnabled = true;
try
{
IntPtr moduleBase = AcClientGetModuleBase();
if (moduleBase == IntPtr.Zero)
{
_statusMessage = "acclient.exe module base not found.";
RynthLog.Compat($"Compat: DAT share hook failed - {_statusMessage}");
return;
}
// Hook the kernel32 exports directly with MinHook so we catch ALL
// callers in the process — acclient.exe itself, the CRT layer
// (msvcrt.dll, which is how AC's fopen-style DAT loads route), and
// any plugin or runtime DLL. IAT-hooking acclient.exe alone misses
// CRT-mediated calls because they go through msvcrt's own IAT slot.
IntPtr hKernel32 = GetModuleHandleW("kernel32.dll");
if (hKernel32 == IntPtr.Zero)
{
_statusMessage = "kernel32.dll module handle not found.";
RynthLog.Compat($"Compat: DAT share hook failed - {_statusMessage}");
return;
}
// Two-phase install. Phase 1: create both hooks (inactive),
// assign typed trampolines into _aOriginal/_wOriginal. Phase 2:
// memory barrier then Enable. Critical ordering: the detour can
// fire from ANY caller in the process the moment Enable returns,
// and the detour calls _aOriginal/_wOriginal — those fields MUST
// be set first or the first invocation null-derefs and kills the
// engine init thread.
IntPtr aTarget = GetProcAddress(hKernel32, "CreateFileA");
IntPtr wTarget = GetProcAddress(hKernel32, "CreateFileW");
int patched = 0;
if (aTarget != IntPtr.Zero)
{
_aDetour = CreateFileADetour;
IntPtr aDetourPtr = Marshal.GetFunctionPointerForDelegate(_aDetour);
_aOriginalPtr = MinHook.HookCreate(aTarget, aDetourPtr);
_aOriginal = Marshal.GetDelegateForFunctionPointer<CreateFileADelegate>(_aOriginalPtr);
patched++;
}
if (wTarget != IntPtr.Zero)
{
_wDetour = CreateFileWDetour;
IntPtr wDetourPtr = Marshal.GetFunctionPointerForDelegate(_wDetour);
_wOriginalPtr = MinHook.HookCreate(wTarget, wDetourPtr);
_wOriginal = Marshal.GetDelegateForFunctionPointer<CreateFileWDelegate>(_wOriginalPtr);
patched++;
}
// Publish trampolines to other cores before enabling.
Thread.MemoryBarrier();
if (aTarget != IntPtr.Zero)
{
MinHook.Enable(aTarget);
RynthLog.Info($"Compat: DAT share - hooked kernel32!CreateFileA @ 0x{aTarget.ToInt32():X8} (trampoline 0x{_aOriginalPtr.ToInt32():X8}).");
}
else
{
RynthLog.Compat("Compat: DAT share - kernel32!CreateFileA export not found.");
}
if (wTarget != IntPtr.Zero)
{
MinHook.Enable(wTarget);
RynthLog.Info($"Compat: DAT share - hooked kernel32!CreateFileW @ 0x{wTarget.ToInt32():X8} (trampoline 0x{_wOriginalPtr.ToInt32():X8}).");
}
else
{
RynthLog.Compat("Compat: DAT share - kernel32!CreateFileW export not found.");
}
if (patched == 0)
{
_statusMessage = "MinHook on kernel32 CreateFile exports failed.";
RynthLog.Compat($"Compat: DAT share hook failed - {_statusMessage}");
return;
}
IsInstalled = true;
_statusMessage = $"DAT share hook installed ({patched} kernel32 export(s) detoured).";
RynthLog.Info($"Compat: {_statusMessage}");
}
catch (Exception ex)
{
_statusMessage = $"DAT share hook exception: {ex.Message}";
RynthLog.Compat($"Compat: DAT share hook failed - {ex.Message}");
}
}
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr GetModuleHandleW(string? lpModuleName);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
/// <summary>
/// Diagnostic — log every kernel32 import name we find that looks file- or
/// memory-mapping-related. Useful when the standard CreateFileW/A hook
/// doesn't catch DAT opens, because it tells us what API AC actually uses.
/// </summary>
private static unsafe void EnumerateKernel32FileImports(IntPtr moduleBase)
{
try
{
byte* basePtr = (byte*)moduleBase;
int peOffset = *(int*)(basePtr + 0x3C);
byte* optHeader = basePtr + peOffset + 24;
uint importDirRva = *(uint*)(optHeader + 96 + 8 * 1);
if (importDirRva == 0)
return;
byte* descriptor = basePtr + importDirRva;
for (; ; descriptor += 20)
{
uint nameRva = *(uint*)(descriptor + 12);
uint firstThunk = *(uint*)(descriptor + 16);
if (nameRva == 0 && firstThunk == 0) break;
string? dllName = Marshal.PtrToStringAnsi((IntPtr)(basePtr + nameRva));
if (!string.Equals(dllName, "kernel32.dll", StringComparison.OrdinalIgnoreCase))
continue;
uint origFirstThunk = *(uint*)(descriptor + 0);
uint nameTableRva = origFirstThunk != 0 ? origFirstThunk : firstThunk;
uint* names = (uint*)(basePtr + nameTableRva);
int i = 0;
var hits = new System.Text.StringBuilder("Compat: DAT share - kernel32 file/mmap imports in acclient.exe IAT:");
int hitCount = 0;
while (names[i] != 0)
{
uint thunk = names[i];
if ((thunk & 0x80000000u) == 0)
{
string? candidate = Marshal.PtrToStringAnsi((IntPtr)(basePtr + thunk + 2));
if (candidate != null &&
(candidate.Contains("File", StringComparison.Ordinal) ||
candidate.Contains("Mapping", StringComparison.Ordinal) ||
candidate.Contains("MapView", StringComparison.Ordinal) ||
candidate.StartsWith("_l", StringComparison.Ordinal) ||
candidate.StartsWith("_open", StringComparison.Ordinal)))
{
hits.Append(' ').Append(candidate);
hitCount++;
}
}
i++;
}
RynthLog.Info(hitCount > 0 ? hits.ToString() : "Compat: DAT share - no file-related kernel32 imports found in acclient.exe IAT.");
return;
}
RynthLog.Info("Compat: DAT share - kernel32.dll import descriptor not found in acclient.exe.");
}
catch (Exception ex)
{
RynthLog.Compat($"Compat: DAT share - import enumeration failed: {ex.Message}");
}
}
private static IntPtr AcClientGetModuleBase()
{
IntPtr moduleBase = GetModuleHandleW("acclient.exe");
if (moduleBase == IntPtr.Zero)
moduleBase = GetModuleHandleW(null);
return moduleBase;
}
/// <summary>
/// Walks the import directory of <paramref name="moduleBase"/> looking for
/// kernel32.dll's import descriptor, then locates the named import
/// <paramref name="importName"/>'s IAT slot. Returns the slot's absolute
/// address (not the function pointer it contains) plus the current
/// pointer value.
/// </summary>
private static unsafe bool TryPatchIatSlot(IntPtr moduleBase, string importName, out IntPtr iatSlot, out IntPtr currentPtr)
{
iatSlot = IntPtr.Zero;
currentPtr = IntPtr.Zero;
byte* basePtr = (byte*)moduleBase;
int peOffset = *(int*)(basePtr + 0x3C);
if (peOffset <= 0 || *(uint*)(basePtr + peOffset) != 0x00004550) // "PE\0\0"
return false;
// OPTIONAL_HEADER starts at peOffset + 24 (4-byte sig + 20-byte FILE_HEADER).
// PE32 magic is 0x010B; DataDirectory starts at OptionalHeader+96.
byte* optHeader = basePtr + peOffset + 24;
if (*(ushort*)optHeader != 0x010B)
return false;
uint importDirRva = *(uint*)(optHeader + 96 + 8 * 1); // DataDirectory[1] = IMPORT
if (importDirRva == 0)
return false;
byte* descriptor = basePtr + importDirRva;
// Each IMAGE_IMPORT_DESCRIPTOR is 20 bytes; terminated by all zeros.
for (; ; descriptor += 20)
{
uint nameRva = *(uint*)(descriptor + 12);
uint firstThunk = *(uint*)(descriptor + 16);
if (nameRva == 0 && firstThunk == 0)
break; // End of descriptor list.
string? dllName = Marshal.PtrToStringAnsi((IntPtr)(basePtr + nameRva));
if (!string.Equals(dllName, "kernel32.dll", StringComparison.OrdinalIgnoreCase) &&
!string.Equals(dllName, "KERNEL32.dll", StringComparison.OrdinalIgnoreCase))
{
continue;
}
uint origFirstThunk = *(uint*)(descriptor + 0);
// INT (Import Name Table) — prefer OriginalFirstThunk if present;
// some bound imports may have it zeroed, in which case the IAT
// itself is still a valid name table pre-binding. Both arrays are
// parallel, 4-byte entries on PE32.
uint nameTableRva = origFirstThunk != 0 ? origFirstThunk : firstThunk;
uint* names = (uint*)(basePtr + nameTableRva);
int i = 0;
while (names[i] != 0)
{
uint thunk = names[i];
// High bit set = import by ordinal — no name to match.
if ((thunk & 0x80000000u) == 0)
{
// IMAGE_IMPORT_BY_NAME = { WORD Hint; CHAR Name[]; }
string? candidate = Marshal.PtrToStringAnsi((IntPtr)(basePtr + thunk + 2));
if (string.Equals(candidate, importName, StringComparison.Ordinal))
{
iatSlot = (IntPtr)(basePtr + firstThunk + 4 * i);
currentPtr = Marshal.ReadIntPtr(iatSlot);
return currentPtr != IntPtr.Zero;
}
}
i++;
}
}
return false;
}
private static bool WriteIatPointer(IntPtr iatSlot, IntPtr newValue)
{
// IAT lives in .rdata which is read-only after the loader binds it.
// Flip protection, write, restore. Use the original-protection value
// from VirtualProtect so we put the page back exactly the way we
// found it (some loaders mark IAT pages as PAGE_READWRITE post-binding,
// some PAGE_READONLY).
if (!VirtualProtect(iatSlot, sizeof(int), PAGE_READWRITE, out uint oldProtect))
{
RynthLog.Compat($"Compat: DAT share - VirtualProtect(RW) on IAT slot 0x{iatSlot.ToInt32():X8} failed (error {Marshal.GetLastWin32Error()}).");
return false;
}
try
{
Marshal.WriteIntPtr(iatSlot, newValue);
}
finally
{
VirtualProtect(iatSlot, sizeof(int), oldProtect, out _);
}
return true;
}
private static bool IsDatPath(string? path)
{
return !string.IsNullOrEmpty(path)
&& path.EndsWith(DatExtension, StringComparison.OrdinalIgnoreCase);
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern uint GetLastError();
private static IntPtr CreateFileWDetour(
IntPtr lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile)
{
string? path = null;
bool isDat = false;
bool isAnyDatExt = false;
uint origAccess = dwDesiredAccess;
uint origShare = dwShareMode;
try
{
path = Marshal.PtrToStringUni(lpFileName);
isDat = IsDatPath(path);
isAnyDatExt = path != null && path.EndsWith(".dat", StringComparison.OrdinalIgnoreCase);
if (isDat)
{
dwDesiredAccess = GENERIC_READ;
dwShareMode = FILE_SHARE_ALL;
}
}
catch
{
}
IntPtr result = _wOriginal!(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes,
dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
if (isAnyDatExt)
{
uint err = result == new IntPtr(-1) ? GetLastError() : 0;
string fname = Path.GetFileName(path!);
string note = isDat ? "filtered" : "passthrough";
RynthLog.Info($"Compat: DAT share - W [{note}]: {fname} access=0x{origAccess:X8}->0x{dwDesiredAccess:X8} share=0x{origShare:X}->0x{dwShareMode:X} result=0x{result.ToInt32():X8}{(err != 0 ? $" GetLastError={err}" : "")}");
}
return result;
}
private static IntPtr CreateFileADetour(
IntPtr lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile)
{
string? path = null;
bool isDat = false;
bool isAnyDatExt = false;
uint origAccess = dwDesiredAccess;
uint origShare = dwShareMode;
try
{
path = Marshal.PtrToStringAnsi(lpFileName);
isDat = IsDatPath(path);
isAnyDatExt = path != null && path.EndsWith(".dat", StringComparison.OrdinalIgnoreCase);
if (isDat)
{
dwDesiredAccess = GENERIC_READ;
dwShareMode = FILE_SHARE_ALL;
}
}
catch
{
}
IntPtr result = _aOriginal!(lpFileName, dwDesiredAccess, dwShareMode, lpSecurityAttributes,
dwCreationDisposition, dwFlagsAndAttributes, hTemplateFile);
if (isAnyDatExt)
{
uint err = result == new IntPtr(-1) ? GetLastError() : 0;
string fname = Path.GetFileName(path!);
string note = isDat ? "filtered" : "passthrough";
RynthLog.Info($"Compat: DAT share - A [{note}]: {fname} access=0x{origAccess:X8}->0x{dwDesiredAccess:X8} share=0x{origShare:X}->0x{dwShareMode:X} result=0x{result.ToInt32():X8}{(err != 0 ? $" GetLastError={err}" : "")}");
}
return result;
}
}

View file

@ -0,0 +1,131 @@
using System;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Hooks AC's DAT object-cache teardown <c>DBCache::DestroyObjectCaches</c>
/// (acclient.map 0x00014040 + 0x401000 = 0x00415040; ImageBase 0x00400000, ASLR off)
/// to QUIESCE off-thread enchantment-registry reads WHILE AC frees its DB objects.
///
/// Crash this addresses: the recurring <c>0x00416C86</c> (DBOCache::DestroyObj + 0x06,
/// read [null+0x28]) AV. Root cause (MainThreadGuard.cs 2026-05-14 note): the
/// off-thread plugin pump walks AC's CACQualities -> CEnchantmentRegistry linked lists
/// (EnchantmentHooks.ReadEnchantmentsFromQualities / WalkEnchantList) while AC frees
/// those nodes during a cache teardown; the pump reads a half-freed node and AC AVs in
/// DestroyObj. Decal never hits this because it drives AC only on AC's own thread.
///
/// ⚠ CRITICAL (verified 2026-06-02 from the live log): DestroyObjectCaches is NOT
/// close-only — AC calls it during world-load / zone-entry too (it fired ~5s after
/// login). So this is a SCOPED guard: raise a depth latch on entry, lower it when the
/// call returns. It must NOT stop the plugin pump or shut down the engine — an earlier
/// destructive version (RequestTickPumpStop + EngineLifecycle.Shutdown in this detour)
/// tore the engine down ~5-30s after EVERY login ("most things don't work"). The
/// engine's real teardown stays on the ExitProcess / WM_CLOSE path. While the latch is
/// set, EnchantmentHooks bails its registry walk, so the off-thread read never races
/// AC's free — at world-load, zone change, logout, AND final close alike.
///
/// Ported (and corrected for v1's in-process threading) from RynthCore2's
/// DestroyObjectCaches guard (RynthSuite2 f8a291e).
/// </summary>
internal static class DbCacheTeardownHooks
{
// DBCache::DestroyObjectCaches. Fallback VA; pattern-scan is the source of truth.
private const int DestroyObjectCachesFallbackVa = 0x00415040;
// 8B 01 / 83 EC 0C / 53 56 57 / 6A 01 / FF 50 38 / 8D 4C 24 .. — unique in .text,
// lands exactly at 0x00415040 (byte-verified against this client).
private static readonly byte?[] DestroyObjectCachesPattern =
[
0x8B, 0x01, 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57,
0x6A, 0x01, 0xFF, 0x50, 0x38, 0x8D, 0x4C, 0x24,
];
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void ThisCallVoidDelegate(IntPtr thisPtr);
private static ThisCallVoidDelegate? _originalDestroyObjectCaches;
private static ThisCallVoidDelegate? _destroyObjectCachesDetour;
private static IntPtr _targetAddress;
private static int _teardownDepth;
private static int _installed;
private static int _enterLogCount;
public static bool IsInstalled => Volatile.Read(ref _installed) != 0;
/// <summary>
/// True only WHILE AC is inside DBCache::DestroyObjectCaches (freeing/rebuilding its
/// DB object caches — world-load, zone change, logout, or final close). Off-thread
/// AC object/registry walkers (the plugin-pump enchantment reader) must bail while
/// this is set so they never deref a node AC is concurrently freeing. SCOPED —
/// cleared when the call returns; NOT a one-way latch.
/// </summary>
public static bool TeardownActive => Volatile.Read(ref _teardownDepth) > 0;
public static void Initialize()
{
if (Interlocked.CompareExchange(ref _installed, 1, 0) != 0)
return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
{
Volatile.Write(ref _installed, 0);
RynthLog.Compat("DbCacheTeardownHooks: acclient.exe not available.");
return;
}
var resolved = HookResolver.Resolve(
textSection, "DbCacheTeardown.DestroyObjectCaches",
DestroyObjectCachesPattern, DestroyObjectCachesFallbackVa);
if (!resolved.Success)
{
Volatile.Write(ref _installed, 0);
return;
}
try
{
_targetAddress = resolved.Address;
_destroyObjectCachesDetour = DestroyObjectCachesDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_destroyObjectCachesDetour);
_originalDestroyObjectCaches = Marshal.GetDelegateForFunctionPointer<ThisCallVoidDelegate>(
MinHook.HookCreate(_targetAddress, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(_targetAddress);
RynthLog.Compat($"DbCacheTeardownHooks: ready (DestroyObjectCaches=0x{_targetAddress.ToInt32():X8}).");
}
catch (Exception ex)
{
Volatile.Write(ref _installed, 0);
RynthLog.Compat($"DbCacheTeardownHooks: install threw {ex.GetType().Name}: {ex.Message}");
}
}
private static void DestroyObjectCachesDetour(IntPtr thisPtr)
{
// SCOPED read-quiesce. Raise the latch BEFORE AC frees anything; lower it when
// AC's teardown loop returns. While raised, EnchantmentHooks (the off-thread
// registry walker) bails, so the pump can't read a node AC is concurrently
// freeing -> kills the 0x00416C86 (DBOCache::DestroyObj) AV. NO pump-stop / NO
// engine shutdown here: DestroyObjectCaches ALSO fires at world-load/zone, and
// destructive work tore the engine down mid-play (2026-06-02).
Interlocked.Increment(ref _teardownDepth);
try
{
if (Interlocked.Increment(ref _enterLogCount) <= 3)
RynthLog.Compat("DbCacheTeardownHooks: DestroyObjectCaches entry — off-thread registry reads quiesced for this teardown.");
_originalDestroyObjectCaches!(thisPtr);
}
catch (Exception ex)
{
try { RynthLog.Compat($"DbCacheTeardownHooks: original threw {ex.GetType().Name}: {ex.Message}"); } catch { }
}
finally
{
Interlocked.Decrement(ref _teardownDepth);
}
}
}

View file

@ -0,0 +1,71 @@
using System;
using System.Diagnostics;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Detects whether a Decal-style coexistence stack is loaded inside this
/// acclient.exe process. When true, the engine skips its D3D9 hooks and
/// in-game overlays so Decal's own EndScene rendering isn't disrupted —
/// only Avalonia floating panels (LayeredWindow / GDI) remain available.
///
/// Result is cached on first call: a Decal stack appearing later in the
/// session would still take effect on a hot-reload, but during a single
/// run the snapshot at engine init is what gates the D3D9 path.
/// </summary>
internal static class DecalDetection
{
private static readonly string[] DecalModuleNames =
{
"decal.dll",
"UBLoader.dll",
"Decal.Adapter.dll",
"phatacd.dll",
};
private static readonly object Sync = new();
private static bool _evaluated;
private static string? _detectedModule;
public static bool IsDecalLoaded => DetectedModule != null;
public static string? DetectedModule
{
get
{
lock (Sync)
{
if (_evaluated)
return _detectedModule;
_evaluated = true;
_detectedModule = ProbeOnce();
return _detectedModule;
}
}
}
private static string? ProbeOnce()
{
try
{
using Process self = Process.GetCurrentProcess();
foreach (ProcessModule module in self.Modules)
{
string name = module.ModuleName;
for (int i = 0; i < DecalModuleNames.Length; i++)
{
if (string.Equals(name, DecalModuleNames[i], StringComparison.OrdinalIgnoreCase))
return DecalModuleNames[i];
}
}
}
catch
{
// Failed to enumerate modules — treat as no Decal so we don't
// disable our own rendering on a transient probe error.
}
return null;
}
}

View file

@ -0,0 +1,80 @@
using System;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.Compatibility;
internal static class DeleteObjectHooks
{
private const int DeleteObjectVa = 0x00558330;
// Verified unique + lands at 0x00558330 offline (tools/pe_pattern.py).
private static readonly byte?[] DeleteObjectPattern =
[
0x56, 0x57, 0x8B, 0xF9, 0xE8, null, null, null, null, 0x85, 0xC0, 0x8B, 0x74, 0x24, 0x0C
];
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate int DeleteObjectDelegate(IntPtr thisPtr, uint objectId);
private static DeleteObjectDelegate? _originalDeleteObject;
private static DeleteObjectDelegate? _deleteObjectDetour;
private static IntPtr _targetAddress;
private static string _statusMessage = "Not probed yet.";
public static bool IsInstalled { get; private set; }
public static string StatusMessage => _statusMessage;
public static void Initialize()
{
if (IsInstalled)
return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
{
_statusMessage = "acclient.exe not available.";
return;
}
HookResolver.ResolveResult resolved = HookResolver.Resolve(textSection, "DeleteObject.DeleteObject", DeleteObjectPattern, DeleteObjectVa);
if (!resolved.Success)
{
_statusMessage = $"ACCObjectMaint::DeleteObject unresolved (VA 0x{DeleteObjectVa:X8}).";
RynthLog.Compat($"Compat: delete-object hook failed - {_statusMessage}");
return;
}
try
{
_targetAddress = resolved.Address;
_deleteObjectDetour = DeleteObjectDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_deleteObjectDetour);
_originalDeleteObject = Marshal.GetDelegateForFunctionPointer<DeleteObjectDelegate>(MinHook.HookCreate(_targetAddress, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(_targetAddress);
IsInstalled = true;
_statusMessage = $"Hooked ACCObjectMaint::DeleteObject @ 0x{_targetAddress.ToInt32():X8}.";
RynthLog.Verbose($"Compat: delete-object hook ready - DeleteObject=0x{_targetAddress.ToInt32():X8}");
}
catch (Exception ex)
{
_statusMessage = ex.Message;
RynthLog.Compat($"Compat: delete-object hook failed - {ex.Message}");
}
}
private static int DeleteObjectDetour(IntPtr thisPtr, uint objectId)
{
RecursionGuard.Tick("DeleteObjectHooks.DeleteObject");
if (objectId != 0)
{
PaletteCache.Remove(objectId);
PluginManager.QueueDeleteObject(objectId);
AutoIdService.Evict(objectId);
}
return _originalDeleteObject!(thisPtr, objectId);
}
}

View file

@ -0,0 +1,140 @@
// ============================================================================
// RynthCore.Engine - Compatibility/DoMotionHooks.cs
//
// Hooks CPhysicsObj::DoMotion to track per-object On/Off motion state.
// Used by wobjectgetisdooropen[] to detect runtime door open/close state,
// since STypeBool.OPEN in CBaseQualities reflects the default/creation state
// and is NOT updated when a door is animated open or closed at runtime.
// ============================================================================
using System;
using System.Collections.Concurrent;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
namespace RynthCore.Engine.Compatibility;
internal static class DoMotionHooks
{
private const int DoMotionFallbackVa = 0x00510AF0;
// CPhysicsObj::DoMotion(uint motion, MovementParameters* params, int sendEvent)
// Distinctive 0x83 0xEC 0x64 (sub esp, 0x64) and the +0xC4 / +0xCC field
// accesses; the 'mov dword ptr [esi+0xCC],1' is unique to this function's prologue.
private static readonly byte?[] DoMotionPattern =
[
0x83, 0xEC, 0x64, 0x56, 0x8B, 0xF1, 0x8B, 0x8E,
0xC4, 0x00, 0x00, 0x00, 0x33, 0xC0, 0x3B, 0xC8,
0xC7, 0x86, 0xCC, 0x00, 0x00, 0x00, 0x01, 0x00,
0x00, 0x00, 0x75, 0x0C
];
// Door motion commands (AC1Legacy Command enum)
private const uint MotionOn = 0x4000000B;
private const uint MotionOff = 0x4000000C;
private const int WeenieObjOffset = 0x128;
private const int WeenieIdOffset = 8;
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate uint DoMotionDelegate(IntPtr thisPtr, uint motion, IntPtr paramsPtr, int sendEvent);
private static DoMotionDelegate? _originalDoMotion;
private static DoMotionDelegate? _doMotionDetour;
private static bool _hookInstalled;
private static string _statusMessage = "Not initialized.";
private static readonly ConcurrentDictionary<uint, bool> _objectOnState = new();
public static bool IsInstalled => _hookInstalled;
public static string StatusMessage => _statusMessage;
public static void Initialize()
{
if (_hookInstalled)
return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
{
_statusMessage = "acclient.exe not available.";
return;
}
var resolved = HookResolver.Resolve(textSection, "DoMotionHooks.DoMotion",
DoMotionPattern, DoMotionFallbackVa);
if (!resolved.Success)
{
_statusMessage = $"Resolve failed ({resolved.Detail}).";
return;
}
try
{
_doMotionDetour = DoMotionDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_doMotionDetour);
_originalDoMotion = Marshal.GetDelegateForFunctionPointer<DoMotionDelegate>(
MinHook.HookCreate(resolved.Address, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(resolved.Address);
_hookInstalled = true;
_statusMessage = $"Hooked CPhysicsObj::DoMotion @ 0x{resolved.Address.ToInt32():X8}.";
RynthLog.Compat($"DoMotionHooks: install ok.");
}
catch (Exception ex)
{
_statusMessage = ex.Message;
RynthLog.Compat($"DoMotionHooks: install threw {ex.GetType().Name}: {ex.Message}");
}
}
public static bool TryGetObjectMotionOn(uint objectId, out bool isOn)
{
return _objectOnState.TryGetValue(objectId, out isOn);
}
private static int _fires;
private static uint DoMotionDetour(IntPtr thisPtr, uint motion, IntPtr paramsPtr, int sendEvent)
{
RecursionGuard.Tick("DoMotionHooks.DoMotion");
if (Interlocked.Increment(ref _fires) <= 3)
RynthLog.Compat($"DoMotionHooks: fired #{_fires} this=0x{thisPtr.ToInt32():X8} motion=0x{motion:X8}");
try
{
if (thisPtr != IntPtr.Zero && (motion == MotionOn || motion == MotionOff))
{
uint objectId = ReadWeenieId(thisPtr);
if (objectId != 0)
_objectOnState[objectId] = motion == MotionOn;
}
}
catch { }
try { return _originalDoMotion!(thisPtr, motion, paramsPtr, sendEvent); }
catch (Exception ex) { try { RynthLog.Compat($"DoMotionHooks: original threw {ex.GetType().Name}: {ex.Message}"); } catch { } throw; }
}
private static uint ReadWeenieId(IntPtr physObjPtr)
{
try
{
IntPtr weenieFieldAddr = physObjPtr + WeenieObjOffset;
if (!ClientObjectHooks.IsReadablePointer(weenieFieldAddr))
return 0;
IntPtr weeniePtr = Marshal.ReadIntPtr(weenieFieldAddr);
if (weeniePtr == IntPtr.Zero)
return 0;
IntPtr idAddr = weeniePtr + WeenieIdOffset;
if (!ClientObjectHooks.IsReadablePointer(idAddr))
return 0;
return (uint)Marshal.ReadInt32(idAddr);
}
catch { return 0; }
}
}

View file

@ -0,0 +1,256 @@
using System;
using System.Runtime.InteropServices;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Reads the player's active spell enchantments from the CEnchantmentRegistry.
///
/// Hookless approach: reads the registry directly from the player's CACQualities struct.
///
/// Path: PlayerVitalsHooks.KnownPlayerQualitiesPtr → CACQualities+0x70 → CEnchantmentRegistry*
/// Offset 0x70 confirmed by disassembling CACQualities::EnchantAttribute2nd (0x0058FEC0):
/// 8B 49 70 = mov ecx, [ecx+0x70] ; reads _enchantment_reg from this (CACQualities*)
///
/// CEnchantmentRegistry layout (from Chorizite + PDB):
/// +0 PackObj (vtable, 4 bytes)
/// +4 PackableList&lt;Enchantment&gt;* _mult_list
/// +8 PackableList&lt;Enchantment&gt;* _add_list
/// +12 PackableList&lt;Enchantment&gt;* _cooldown_list
/// +16 Enchantment* _vitae
/// +20 uint m_cHelpfulEnchantments
/// +24 uint m_cHarmfulEnchantments
///
/// Enchantment struct (sizeof=72, pack 4):
/// +0 PackObj (vtable) +4 _id (uint)
/// +8 m_SpellSetID +12 _spell_category
/// +16 _power_level +20 _start_time (double)
/// +28 _duration (double) +36 _caster (uint)
/// +40 _degrade_modifier +44 _degrade_limit
/// +48 _last_time_degraded +56 StatMod(16 bytes)
///
/// PackableLLNode&lt;Enchantment&gt;: data(72) + next*(4) + prev*(4)
/// </summary>
internal static class EnchantmentHooks
{
// Offset of _enchantment_reg within CACQualities
// Confirmed by disassembly: mov ecx, [ecx+0x70] at 0x0058FEC0
private const int QualitiesRegistryOffset = 0x70;
// CEnchantmentRegistry offsets
private const int RegistryMultListOffset = 4;
private const int RegistryAddListOffset = 8;
private const int RegistryCooldownListOffset = 12;
// PackableList<Enchantment>: +0=vtable, +4=head, +8=tail, +12=curNum
private const int ListHeadOffset = 4;
// Enchantment fields within each PackableLLNode
// MSVC x86 pack(8): doubles are 8-byte aligned, inserting 4 bytes padding after _power_level
private const int EnchantmentIdOffset = 4; // _id (uint)
private const int EnchantmentStartTimeOffset = 24; // _start_time (double) — padded from +20 to +24
private const int EnchantmentDurationOffset = 32; // _duration (double)
// sizeof(Enchantment) = 80 with MSVC padding; PackableLLNode has next* and prev* after data
private const int NodeNextOffset = 80; // next*
private static bool _initialized;
private static bool _loggedFirstRead;
public static bool IsInitialized => _initialized;
public static bool Initialize()
{
if (_initialized) return true;
_initialized = true;
RynthLog.Verbose("Compat: enchantment reader ready (hookless, CACQualities+0x70)");
return true;
}
/// <summary>
/// Reads active enchantments from the player's CEnchantmentRegistry.
/// Returns count written, 0 if no enchantments, -1 if player qualities not available.
/// Expiry times are server-time seconds (subtract current server time for remaining).
/// </summary>
public static unsafe int ReadPlayerEnchantments(uint* spellIds, double* expiryTimes, int maxCount)
{
if (maxCount <= 0) return 0;
// Get player's CACQualities pointer (set by login hooks)
IntPtr qualPtr = PlayerVitalsHooks.KnownPlayerQualitiesPtr;
if (qualPtr == IntPtr.Zero) return -1;
int count = ReadEnchantmentsFromQualities(qualPtr, spellIds, expiryTimes, maxCount);
if (_enchReadLogCount < 8)
{
System.Threading.Interlocked.Increment(ref _enchReadLogCount);
RynthLog.Info($"[EnchRead] player read #{_enchReadLogCount}: {count} enchantments (qualPtr=0x{qualPtr.ToInt64():X8})");
}
return count;
}
private static int _enchReadLogCount;
/// <summary>
/// Reads active enchantments from any game object's CEnchantmentRegistry.
/// Path: GetWeenieObject(objectId) → weenie+qualitiesOffset → CACQualities+0x70.
/// Returns count written, 0 if no enchantments, -1 if object not found or has no registry.
///
/// Uses VirtualQuery to validate every pointer before dereferencing — critical because
/// AccessViolationException cannot be caught in NativeAOT/.NET 5+.
/// </summary>
public static unsafe int ReadObjectEnchantments(uint objectId, uint* spellIds, double* expiryTimes, int maxCount)
{
if (maxCount <= 0) return 0;
if (!ClientObjectHooks.TryGetWeenieObjectPtr(objectId, out IntPtr weeniePtr))
return -1;
// Navigate weenie → CACQualities via the probed/fallback offset
IntPtr qualAddr = weeniePtr + ClientObjectHooks.WeenieQualitiesOffset;
if (!SmartBoxLocator.IsMemoryReadable(qualAddr, 4))
return -1;
IntPtr qualPtr = Marshal.ReadIntPtr(qualAddr);
if (qualPtr == IntPtr.Zero) return -1;
// Validate: CACQualities inherits PackObj → vtable must point into acclient.exe.
if (!SmartBoxLocator.IsMemoryReadable(qualPtr, 4))
return -1;
IntPtr vtable = Marshal.ReadIntPtr(qualPtr);
if (!SmartBoxLocator.IsPointerInModule(vtable))
return -1;
// Validate the enchantment registry pointer
IntPtr regAddr = qualPtr + QualitiesRegistryOffset;
if (!SmartBoxLocator.IsMemoryReadable(regAddr, 4))
return -1;
IntPtr regPtr = Marshal.ReadIntPtr(regAddr);
if (regPtr == IntPtr.Zero) return 0;
// Validate registry vtable
if (!SmartBoxLocator.IsMemoryReadable(regPtr, 4))
return -1;
IntPtr regVtable = Marshal.ReadIntPtr(regPtr);
if (!SmartBoxLocator.IsPointerInModule(regVtable))
return -1;
return ReadEnchantmentsFromQualities(qualPtr, spellIds, expiryTimes, maxCount);
}
/// <summary>
/// Core: reads enchantments from a CACQualities pointer's enchantment registry.
/// </summary>
private static unsafe int ReadEnchantmentsFromQualities(IntPtr qualPtr, uint* spellIds, double* expiryTimes, int maxCount)
{
// While AC is inside a DB object-cache teardown (DbCacheTeardownHooks sets this
// on AC's main thread for the duration of DestroyObjectCaches — which fires at
// world-load, zone change, logout, AND final close), refuse to walk the
// CEnchantmentRegistry linked lists: AC is concurrently freeing those nodes, and
// an off-thread (plugin-pump) walk over a half-freed node is the recurring
// 0x00416C86 (DBOCache::DestroyObj, [null+0x28]) AV.
if (DbCacheTeardownHooks.TeardownActive)
return -1;
// Deep-audit finding #23 (2026-06-18): ReadObjectEnchantments (the
// other caller of this method) validates the qualities pointer's own
// vtable-in-module before ever reaching here; the player path used to
// skip straight to walking the registry off a cached pointer with no
// such check. KnownPlayerQualitiesPtr is zeroed on logout and
// TeardownActive covers the dominant relog race, but a
// committed-but-stale pointer surviving both (mainly a
// Decal-coexistence exposure) would otherwise be walked as if it
// were still a real CACQualities object — a use-after-free read.
// Reuses the same canonical-vtable check the skill-read path already
// relies on instead of a fresh page-probe-only check.
if (!SmartBoxLocator.IsMemoryReadable(qualPtr, 4) || !ClientObjectHooks.IsCacQualitiesObject(qualPtr))
return -1;
IntPtr regAddr = qualPtr + QualitiesRegistryOffset;
if (!SmartBoxLocator.IsMemoryReadable(regAddr, 4))
return -1;
IntPtr registryPtr = Marshal.ReadIntPtr(regAddr);
if (registryPtr == IntPtr.Zero) return 0;
// Validate the registry's own vtable too, mirroring ReadObjectEnchantments.
if (!SmartBoxLocator.IsMemoryReadable(registryPtr, 4))
return -1;
IntPtr registryVtable = Marshal.ReadIntPtr(registryPtr);
if (!SmartBoxLocator.IsPointerInModule(registryVtable))
return -1;
// Stability check (2026-09-02 "infinite buffing loop" bug): AC's own
// main thread mutates these linked lists as buffs land/expire, and in
// Decal-coexistence mode this reader runs off-thread on the 30Hz
// plugin pump (no EndScene-driven main-thread tick exists there) — a
// walk here can race that mutation. A torn/truncated walk silently
// under-reports the active buff set; BuffManager.RefreshFromLiveMemory
// treats a short read as "buffs expired" and clears its timers,
// making a just-completed rebuff pass look like nothing landed and
// instantly restarting it. Walk twice and only trust an exact match;
// on a mismatch, skip this tick (return -1, already a safe no-op for
// every caller) rather than report a truncated set.
int countA = WalkAllLists(registryPtr, spellIds, expiryTimes, maxCount);
uint* idsB = stackalloc uint[maxCount];
double* expB = stackalloc double[maxCount];
int countB = WalkAllLists(registryPtr, idsB, expB, maxCount);
if (countA != countB)
return -1;
for (int i = 0; i < countA; i++)
{
if (spellIds[i] != idsB[i] || expiryTimes[i] != expB[i])
return -1;
}
return countA;
}
private static unsafe int WalkAllLists(IntPtr registryPtr, uint* spellIds, double* expiryTimes, int maxCount)
{
int count = 0;
count = WalkEnchantList(registryPtr + RegistryMultListOffset, spellIds, expiryTimes, maxCount, count);
count = WalkEnchantList(registryPtr + RegistryAddListOffset, spellIds, expiryTimes, maxCount, count);
count = WalkEnchantList(registryPtr + RegistryCooldownListOffset, spellIds, expiryTimes, maxCount, count);
return count;
}
private static unsafe int WalkEnchantList(IntPtr listPtrAddress, uint* spellIds, double* expiryTimes, int maxCount, int count)
{
if (!SmartBoxLocator.IsMemoryReadable(listPtrAddress, 4))
return count;
IntPtr listPtr = Marshal.ReadIntPtr(listPtrAddress);
if (listPtr == IntPtr.Zero) return count;
if (!SmartBoxLocator.IsMemoryReadable(listPtr + ListHeadOffset, 4))
return count;
IntPtr nodePtr = Marshal.ReadIntPtr(listPtr + ListHeadOffset);
int guard = 0;
while (nodePtr != IntPtr.Zero && guard++ < 512 && count < maxCount)
{
// Validate entire node is readable before accessing any field
if (!SmartBoxLocator.IsMemoryReadable(nodePtr, NodeNextOffset + 4))
break;
// _id field is enchantment ID: (layer << 16) | spellId — mask to get spell ID
uint spellId = unchecked((uint)Marshal.ReadInt32(nodePtr + EnchantmentIdOffset)) & 0xFFFF;
long startBits = Marshal.ReadInt64(nodePtr + EnchantmentStartTimeOffset);
long durBits = Marshal.ReadInt64(nodePtr + EnchantmentDurationOffset);
double start = BitConverter.Int64BitsToDouble(startBits);
double duration = BitConverter.Int64BitsToDouble(durBits);
if (spellId != 0)
{
spellIds[count] = spellId;
expiryTimes[count] = duration > 0 ? start + duration : double.MaxValue;
count++;
}
nodePtr = Marshal.ReadIntPtr(nodePtr + NodeNextOffset);
}
return count;
}
}

View file

@ -0,0 +1,161 @@
// ============================================================================
// RynthCore.Engine - EngineStatusMetrics.cs
//
// A benign, generic "here are my own metrics" accessor. Each heartbeat tick
// caches the engine's live metrics (UpdateMetrics); BuildEngineStatusJson
// composes them — plus the main-thread-cached player stats and session
// identity — into a small JSON object that a plugin can pull via the
// GetEngineStatusJson host bridge. The engine NEVER writes a file, opens a
// socket, or networks; it only hands a plugin its own numbers on request.
//
// (The per-client status file and phone command drain now live entirely in the
// private RynthCore.Plugin.RynthRemote plugin, so the public engine carries no
// remote or networking code — just this benign metrics accessor.)
// ============================================================================
using System;
using System.IO;
using System.Text.Json;
namespace RynthCore.Engine.Compatibility;
internal static class EngineStatusMetrics
{
// Latest heartbeat metrics, cached so the parameterless BuildEngineStatusJson
// accessor (backing the GetEngineStatusJson host bridge) can compose without
// the heartbeat thread's locals. Updated every heartbeat tick; ~1s staleness
// is fine for a status pull.
private static long _mUptimeSec, _mWorkingSetMb, _mQueueDropped, _mReconciles, _mForceClears;
private static int _mFps, _mPluginTicksPerSec;
private static bool _mInWorld;
/// <summary>
/// Cache this tick's engine metrics. Called once/second from the heartbeat
/// thread with values it already computed — a few field writes, no I/O.
/// </summary>
internal static void UpdateMetrics(
long uptimeSeconds, int fps, int pluginTicksPerSec, long workingSetMb,
bool inWorld, long queueDropped, long reconciles, long forceClears)
{
_mUptimeSec = uptimeSeconds; _mFps = fps; _mPluginTicksPerSec = pluginTicksPerSec;
_mWorkingSetMb = workingSetMb; _mInWorld = inWorld; _mQueueDropped = queueDropped;
_mReconciles = reconciles; _mForceClears = forceClears;
}
// Per-process session baselines for the per-hour rates. Each client is its own
// process, so these naturally reset per launch; we also reset on an XP drop
// (relog / char swap).
private static long _xpBaseline = -1;
private static long _lumBaseline = -1;
private static int _deathsBaseline = -1;
private static DateTime _statsSessionStartUtc = DateTime.UtcNow;
/// <summary>
/// Compose the engine-side status fields as a JSON object string, from the
/// latest cached heartbeat metrics. Backs the GetEngineStatusJson host bridge.
/// Never throws; returns "{}" on failure. Safe off the main thread — player
/// stats come from a main-thread-cached source.
/// </summary>
internal static string BuildEngineStatusJson()
{
try
{
using var ms = new MemoryStream(1024);
using (var w = new Utf8JsonWriter(ms))
{
w.WriteStartObject();
WriteEngineFields(w, _mUptimeSec, _mFps, _mPluginTicksPerSec, _mWorkingSetMb,
_mInWorld, _mQueueDropped, _mReconciles, _mForceClears);
w.WriteEndObject();
}
return System.Text.Encoding.UTF8.GetString(ms.ToArray());
}
catch
{
return "{}";
}
}
// Writes the engine status fields into an already-open JSON object. The per-hour
// baselines below have a single writer (the GetEngineStatusJson accessor path).
private static void WriteEngineFields(
Utf8JsonWriter w,
long uptimeSeconds, int fps, int pluginTicksPerSec, long workingSetMb,
bool inWorld, long queueDropped, long reconciles, long forceClears)
{
w.WriteString("schema", "rynthcore.client-status/1");
w.WriteString("ts", DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fff'Z'"));
w.WriteString("host", SafeMachineName());
w.WriteNumber("pid", Environment.ProcessId);
w.WriteString("account", SessionStateRegistry.LastAccountName ?? string.Empty);
w.WriteString("character", SessionStateRegistry.LastCharacterName ?? string.Empty);
w.WriteString("server", SessionStateRegistry.LastServerName ?? string.Empty);
w.WriteNumber("uptimeSec", uptimeSeconds);
w.WriteNumber("fps", fps);
w.WriteNumber("pluginTicksPerSec", pluginTicksPerSec);
w.WriteNumber("workingSetMB", workingSetMb);
w.WriteBoolean("inWorld", inWorld);
w.WriteNumber("queueDropped", queueDropped);
w.WriteNumber("reconciles", reconciles);
w.WriteNumber("forceClears", forceClears);
// Player stats, read on the main thread by PrefetchPlayerStats and served here off-thread
// (the plugin pump can't read these live). deaths all-time; rates/session = whole-session.
ClientObjectHooks.TryGetPlayerStats(out long xp, out long lum, out int deaths, out float vitae,
out int encVal, out int encCap, out uint landcell,
out float px, out float py, out float pz);
double vitaePct = Math.Clamp((1.0 - vitae) * 100.0, 0.0, 100.0);
// Lazy baselines; reset on an XP drop (relog / char change).
if (xp > 0 && (_xpBaseline < 0 || xp < _xpBaseline))
{
_xpBaseline = xp; _deathsBaseline = deaths; _statsSessionStartUtc = DateTime.UtcNow;
}
if (_deathsBaseline < 0 && xp > 0) _deathsBaseline = deaths;
if (lum > 0 && (_lumBaseline < 0 || lum < _lumBaseline)) _lumBaseline = lum;
double hours = (DateTime.UtcNow - _statsSessionStartUtc).TotalHours;
double xpPerHour = (hours > 1.0 / 3600.0 && _xpBaseline >= 0 && xp >= _xpBaseline) ? (xp - _xpBaseline) / hours : 0;
double lumPerHour = (hours > 1.0 / 3600.0 && _lumBaseline >= 0 && lum >= _lumBaseline) ? (lum - _lumBaseline) / hours : 0;
long xpSession = (_xpBaseline >= 0 && xp >= _xpBaseline) ? xp - _xpBaseline : 0;
int deathsSession = (_deathsBaseline >= 0 && deaths >= _deathsBaseline) ? deaths - _deathsBaseline : 0;
double burdenPct = encCap > 0 ? Math.Round((double)encVal / encCap * 100.0) : 0;
w.WriteNumber("deaths", deaths);
w.WriteNumber("deathsSession", deathsSession);
w.WriteNumber("vitaePct", Math.Round(vitaePct, 1));
w.WriteNumber("xpPerHour", Math.Round(xpPerHour));
w.WriteNumber("luminancePerHour", Math.Round(lumPerHour));
w.WriteNumber("xpSession", xpSession);
w.WriteNumber("burdenPct", burdenPct);
w.WriteString("area", landcell != 0 ? (landcell >> 16).ToString("X4") : "");
// [status-export] live map-dot position. wx/wy are ABSOLUTE world coords (cell-local origin + the
// landblock grid offset) because the baked dungeon map's bounds are absolute (DungeonLOS adds the
// same gx/gy per vertex). The app maps these straight to map pixels.
uint lb = landcell != 0 ? (landcell >> 16) : 0u;
bool indoor = lb != 0 && (landcell & 0xFFFF) >= 0x0100; // indoor EnvCells are 0x0100+; outdoor = 0
w.WriteString("landblock", lb != 0 ? lb.ToString("X8") : ""); // matches the .bin filename {lb:X8}
w.WriteBoolean("indoor", indoor);
if (indoor)
{
double wx = px + ((lb >> 8) & 0xFF) * 192.0;
double wy = py + (lb & 0xFF) * 192.0;
w.WriteNumber("wx", Math.Round(wx, 2));
w.WriteNumber("wy", Math.Round(wy, 2));
w.WriteNumber("pz", Math.Round(pz, 2)); // raw local Z — floor-label / fallback hint
}
// Last engine warning/error (truncated) + age, for remote diagnosis of a stuck box.
string? li = RynthLog.LastIssue;
if (!string.IsNullOrEmpty(li))
{
w.WriteString("lastIssue", li.Length > 140 ? li.Substring(0, 140) : li);
w.WriteNumber("lastIssueAgeSec", (long)Math.Max(0, (DateTime.UtcNow - RynthLog.LastIssueUtc).TotalSeconds));
}
else { w.WriteNull("lastIssue"); w.WriteNumber("lastIssueAgeSec", -1); }
}
private static string SafeMachineName()
{
try { return Environment.MachineName; }
catch { return string.Empty; }
}
}

View file

@ -0,0 +1,183 @@
using System;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Hooks AC's top-level per-frame game-logic tick, <c>Client::UseTime</c>
/// (acclient.map 0x00010FA0 + 0x401000 = 0x00411FA0; ImageBase 0x00400000, ASLR
/// off), to drain the marshalled CAST queue on AC's MAIN thread IN THE GAME-LOGIC
/// PHASE.
///
/// Why this tick (not EndScene): a cast must run where AC processes player actions
/// and advances its cast state machine. EndScene is the RENDER phase — marshalling
/// the cast there fired IncrementBusyCount but never completed the cast (proven
/// dead-end, reverted 2026-05-19: no projectile/damage, busy leaked, cast slot
/// jammed). Client::UseTime IS the game-logic phase, so the cast completes there.
///
/// Why marshal casts at all: CastSpell is the LAST off-thread AC mutator. Run off
/// the pump thread it mutates AC's single-threaded object/animation/enchant graph
/// and corrupts it; AC then AVs LATER in its own per-tick code — CSequence::
/// update_internal (animation, captured 2026-06-03), 0x67E779 (classify), 0x0055FA24
/// (range-list). Running the cast here, on AC's own game thread, removes that race
/// at the source — the root fix for the off-thread object-graph corruption class.
///
/// Thiscall detour, same proven pattern as DbCacheTeardownHooks / LogoutLifecycleHooks.
/// DrainCasts early-returns when no cast is pending, so the detour is alloc-free in
/// the common per-frame case — the same safe profile as the existing EndScene detour.
/// </summary>
internal static class GameTickHooks
{
private const int UseTimeVa = 0x00411FA0; // Client::UseTime — thiscall, returns bool in AL
// Client::UseTime returns a bool (AL): AC's main loop drives it as
// do { } while ( UseTime() != 0 );
// so the return value MUST be propagated. A void delegate discards AC's AL
// and the loop then reads whatever the managed epilogue left in EAX — when
// that is nonzero the loop never exits and the client hard-freezes (main
// thread spins in UseTime pumping messages but never rendering; bot threads
// keep running). Dump-confirmed root cause, 2026-06-05.
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate int ThisCallBoolDelegate(IntPtr thisPtr);
private static ThisCallBoolDelegate? _originalUseTime;
private static ThisCallBoolDelegate? _useTimeDetour;
private static IntPtr _targetAddress;
private static int _installed;
private static int _exitLatch;
// Verified unique + lands exactly at UseTimeVa offline (tools/pe_pattern.py).
// Replaces the prior warn-only prologue check; null = wildcard (rel32 call operand).
private static readonly byte?[] UseTimePattern = [ 0x56, 0x8B, 0xF1, 0xE8, null, null, null, null, 0xE8, null, null, null, null, 0x84, 0xC0, 0x74 ];
public static bool IsInstalled => Volatile.Read(ref _installed) != 0;
public static void Initialize()
{
if (Interlocked.CompareExchange(ref _installed, 1, 0) != 0)
return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
{
Volatile.Write(ref _installed, 0);
RynthLog.Compat("GameTickHooks: acclient.exe not available.");
return;
}
HookResolver.ResolveResult resolved = HookResolver.Resolve(textSection, "GameTick.UseTime", UseTimePattern, UseTimeVa);
if (!resolved.Success)
{
Volatile.Write(ref _installed, 0);
RynthLog.Compat($"GameTickHooks: Client::UseTime unresolved (VA 0x{UseTimeVa:X8}) — cast marshalling NOT installed.");
return;
}
try
{
_targetAddress = resolved.Address;
_useTimeDetour = UseTimeDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_useTimeDetour);
_originalUseTime = Marshal.GetDelegateForFunctionPointer<ThisCallBoolDelegate>(
MinHook.HookCreate(_targetAddress, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(_targetAddress);
Volatile.Write(ref _installed, 1);
RynthLog.Compat($"GameTickHooks: Client::UseTime hooked @ 0x{_targetAddress.ToInt32():X8} ({resolved.Detail}) — cast drain on game-logic tick.");
}
catch (Exception ex)
{
Volatile.Write(ref _installed, 0);
RynthLog.Compat($"GameTickHooks: install threw {ex.GetType().Name}: {ex.Message}");
}
}
private static int UseTimeDetour(IntPtr thisPtr)
{
// Hang-watchdog beat from the game-logic tick (no frame count): the
// EndScene beat alone left the watchdog blind to a main thread that
// wedges before the new generation's EndScene hook installs.
try { MainThreadHangWatchdog.MainThreadBeatNoFrame(); }
catch { }
// Drain any queued cast BEFORE AC's game-logic tick: SelectItem sets AC's
// selection and the cast initiates, then THIS SAME UseTime call processes it to
// completion — mimicking AC's natural input -> UseTime flow. (Draining AFTER the
// tick landed self-buffs but not targeted casts: the selection set at the end of
// tick N was clobbered before tick N+1 read it.) Alloc-free when no cast is
// pending. Must never throw into AC's native frame.
try { AcMainThreadQueue.DrainCasts(); }
catch { }
// Refresh TeleportStateHooks' main-thread cache every real game tick. This
// detour (unlike EndScene) fires on AC's true main thread in EVERY mode
// including Decal-coexistence (no D3D9 hook there) — without this,
// off-thread callers of IsPortaling in coexistence mode would see a
// perpetually stale cache since nothing else ever reads it on-thread.
// The getter itself does the guarded read + cache write; discard the value.
try { _ = TeleportStateHooks.IsPortaling; }
catch { }
// Run AC's own game-logic + physics + animation pass.
int result;
try { result = _originalUseTime!(thisPtr); }
catch { result = 0; }
// ── Game loop is exiting — quiesce BEFORE AC's teardown ──────────────
// AC's main loop is `do { } while (UseTime() != 0)`; a 0 return means
// this was the LAST tick and AC tears its world down next (DBCache::
// DestroyObjectCaches frees every DBObj). This is the only close signal
// that covers ALL exit paths: the in-game exit / logout-quit flow never
// delivers WM_CLOSE, so the Win32Backend/AvaloniaOverlay WM_CLOSE
// quiesce never ran and the ~63 Hz pump kept firing Move/SetAutoRun/
// object reads into freed objects -> the on-close AV at acclient
// 0x00416C86 (DBOCache::DestroyObj reading [null+0x28]). We are still
// INSIDE the final UseTime call here — AC objects are all valid — so
// the pump's in-flight frame finishes safely during the bounded join.
if (result == 0 && Interlocked.Exchange(ref _exitLatch, 1) == 0)
{
try { RynthLog.Compat("GameTickHooks: Client::UseTime returned 0 — game loop exiting; quiescing plugin pump + late input before AC teardown."); }
catch { }
// Drop the busy watchdog's cached ClientUISystem ptr (freed next).
try { BusyCountHooks.ResetSession(); }
catch { }
// Arm the late mouse/cursor swallow in BOTH game-window subclasses
// (the 0x0056547B UpdateCursorState close-AV trigger) — WM_CLOSE
// never fired on this path, so neither latch is set yet.
try { ImGuiBackend.Win32Backend.MarkCloseInFlight(); }
catch { }
try { UI.RynthOverlayWindow.MarkCloseInFlight(); }
catch { }
try { EntryPoint.StopTickPumpAndJoin(); }
catch { }
// Skip the post-tick drains/watchdog below — no engine-issued
// mutation may run once the loop has decided to exit.
return 0;
}
// Drain the marshalled-action ring AFTER AC's tick, NOT before.
// ⚠ Issuing a UseObject (corpse open) / movement / stance change starts
// or REPLACES the player's CSequence motion — and AC's animation update
// (CPhysicsObj::update_object -> CSequence::update_internal ->
// AnimSequenceNode::get_high_frame) runs inside _originalUseTime above.
// Draining BEFORE that call meant the SAME tick walked the sequence we
// had just perturbed, hitting a freed/null anim node -> hard AV at
// acclient 0x5263xx/0x5264xx (null+0xC). Live-diagnosed 2026-06-11
// during a rapid corpse-open grind (AC-only crash stack, no engine
// frames). Draining after lets AC install the new gesture's node and
// walk it cleanly on its NEXT tick. The EndScene drain (the other call
// site) is already post-physics in the frame, so it was never the
// trigger. (Casts stay PRE-tick above — their selection-timing
// requirement, and they go through the separate cast slot.)
try { AcMainThreadQueue.Drain(); }
catch { }
// Busy watchdog: also post-tick now. Its decrement / cursor-refresh
// touch m_cBusy, not the motion sequence, so order is immaterial here;
// keeping all engine-issued mutations after AC's pass is the invariant.
try { BusyCountHooks.CheckWatchdog(); }
catch { }
// MUST return Client::UseTime's own bool — AC loops do/while on it.
return result;
}
}

View file

@ -0,0 +1,138 @@
using System;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Writes one short "hb #N" line to the unified log every second from a
/// background thread. Purpose: when AC dies and no termination hook fires,
/// the heartbeat gives a hard upper-bound timestamp for when the process
/// went silent — so external traces (Procmon, Application Event Log,
/// network captures) can be correlated to the second.
///
/// Cheap (one log line / second). Background thread, won't keep the
/// process alive on its own. One-shot start; safe to call from
/// pre-resume early-init.
/// </summary>
internal static class HeartbeatLogger
{
private const int IntervalMs = 1000;
private static int _started;
private static int _stopRequested;
private static int _exited;
private static Thread? _thread;
public static void Start()
{
if (Interlocked.CompareExchange(ref _started, 1, 0) != 0)
return;
_thread = new Thread(Run)
{
Name = "RynthCore.Heartbeat",
IsBackground = true,
Priority = ThreadPriority.BelowNormal
};
_thread.Start();
RynthLog.Info("HeartbeatLogger: started (1s cadence).");
}
/// <summary>
/// Signals the heartbeat thread to exit and waits up to <paramref name="timeoutMs"/>
/// for it to do so. Called from EngineLifecycle.Shutdown — without this, the
/// thread keeps running past loader FreeLibrary of the engine, executing code
/// pages that have been unmapped → CLR exception / FAIL_FAST during hot reload.
/// </summary>
public static bool StopAndJoin(int timeoutMs = 1500)
{
if (_thread == null) return true;
Interlocked.Exchange(ref _stopRequested, 1);
long deadline = Environment.TickCount64 + timeoutMs;
while (Volatile.Read(ref _exited) == 0 && Environment.TickCount64 < deadline)
Thread.Sleep(10);
bool exited = Volatile.Read(ref _exited) != 0;
if (!exited)
RynthLog.Info($"HeartbeatLogger: did NOT exit within {timeoutMs}ms.");
return exited;
}
private static void Run()
{
long tick = 0;
int lastFrames = 0;
int lastPlugTicks = 0;
long lastMs = Environment.TickCount64;
long startMs = lastMs;
try
{
while (Volatile.Read(ref _stopRequested) == 0)
{
tick++;
// Rich beat: a silent-death log tail now shows WHAT the client
// was doing — render rate (0 fps = render dead, process alive),
// plugin pump rate (0 = wedged pump), memory trend, and in-world
// state — not just "alive at T". All cheap, engine-side reads.
try
{
long nowMs = Environment.TickCount64;
long dtMs = nowMs - lastMs; if (dtMs <= 0) dtMs = 1;
int frames = MainThreadHangWatchdog.FrameCount;
int plug = Plugins.PluginManager.TickCount;
int fps = (int)((frames - lastFrames) * 1000L / dtMs);
int pps = (int)((plug - lastPlugTicks) * 1000L / dtMs);
lastFrames = frames; lastPlugTicks = plug; lastMs = nowMs;
long wsMb = 0;
try { wsMb = Environment.WorkingSet / (1024 * 1024); } catch { }
int login = 0;
try { login = LoginLifecycleHooks.HasObservedLoginComplete ? 1 : 0; } catch { }
// qd = marshalled actions silently dropped (ring full). A
// climbing qd with healthy fps means the consumer phase is
// dead — exactly the silent blackhole class the review found.
long dropped = 0;
try { dropped = AcMainThreadQueue.DroppedCount; } catch { }
// rec = busy reconciles (cast/item-action), fcl = force-clears.
// Soak health: rec climbs during combat/loot; fcl stays flat.
long rec = 0, fcl = 0;
try { rec = BusyCountHooks.ReconcileCount; fcl = BusyCountHooks.ForceClearCount; } catch { }
RynthLog.Info($"hb #{tick} up={(nowMs - startMs) / 1000}s fps={fps} plug={pps}/s ws={wsMb}MB login={login} qd={dropped} rec={rec} fcl={fcl}");
// Cache this client's live metrics so the GetEngineStatusJson host bridge can serve
// them to a plugin (the RynthRemote status export). No file write, no networking.
EngineStatusMetrics.UpdateMetrics((nowMs - startMs) / 1000, fps, pps, wsMb,
login == 1, dropped, rec, fcl);
}
catch { /* never let the heartbeat itself bring anything down */ }
// Self-healing: clear a stuck floating-panel click-through
// (DockedPanelPointerCaptureActive whose disarm was lost ->
// every floating panel left WS_EX_TRANSPARENT). Runs here on
// purpose: independent of the input path that strands it.
try { RynthCore.Engine.UI.AvaloniaOverlay.WatchdogClearStuckClickThrough(); }
catch { /* never let the heartbeat itself bring anything down */ }
// Mid-session log rotation (~once/minute): without it a long
// soak grows RynthCore.<pid>.log without bound (startup-only
// rotation never fires mid-session and is skipped on reload).
if (tick % 60 == 0)
{
try { LogPaths.RotateIfOversized(); }
catch { /* never let the heartbeat itself bring anything down */ }
}
// Sleep in short slices so a stop signal is observed within <100ms,
// not up to a full IntervalMs after request.
int slept = 0;
while (slept < IntervalMs && Volatile.Read(ref _stopRequested) == 0)
{
try { Thread.Sleep(50); } catch { return; }
slept += 50;
}
}
}
finally
{
Interlocked.Exchange(ref _exited, 1);
}
}
}

View file

@ -0,0 +1,190 @@
// ============================================================================
// RynthCore.Engine - Compatibility/HookResolver.cs
//
// Shared helper that resolves an acclient.exe function address by:
// 1. Pattern scanning the .text section for a unique byte signature.
// 2. Falling back to a hardcoded VA only if the pattern misses, with loud
// logging so we know the next time the binary diverges.
// 3. Reporting failure with full diagnostics so the failing hook can be
// identified from the log alone.
//
// Every site that previously hardcoded `int funcOff = TargetVa - text.TextBaseVa`
// should funnel through Resolve() so the install log line tells us exactly
// how the address was found — pattern (good), fallback (suspect), or
// unavailable (definitely the wrong build).
// ============================================================================
using System;
namespace RynthCore.Engine.Compatibility;
internal static class HookResolver
{
public enum ResolveSource { Failed, PatternScan, FallbackVa }
public readonly struct ResolveResult
{
public ResolveResult(IntPtr address, ResolveSource source, string detail)
{
Address = address;
Source = source;
Detail = detail;
}
public IntPtr Address { get; }
public ResolveSource Source { get; }
public string Detail { get; }
public bool Success => Source != ResolveSource.Failed;
}
/// <summary>
/// Locate <paramref name="functionName"/> in the loaded acclient.exe text
/// section. Pattern is the source of truth; <paramref name="fallbackVa"/>
/// is a last-resort safety net if pattern matching fails (e.g. a tiny
/// build delta we haven't anticipated).
///
/// Logs at every outcome so the install-time log line names which hook
/// resolved how — when a crash happens, the *previous* successful resolve
/// log entry tells you which hook was the most recent thing patched.
/// </summary>
public static ResolveResult Resolve(
AcClientTextSection text,
string functionName,
byte?[] pattern,
int fallbackVa)
{
try
{
int firstMatch = PatternScanner.FindPattern(text.Bytes, pattern);
if (firstMatch >= 0)
{
// Deep-audit finding #30 (2026-06-18): this used to find only
// the first and the immediately-next match, so a 3rd+
// occurrence was never considered and the multimatch log
// claimed to have examined only 2 of N. Not reachable on the
// current shipped binary (all patterns verified unique) —
// this is a defensive fallback for future binary drift, but
// "examined 2 of N and picked wrong" is exactly the failure
// mode a defensive fallback shouldn't have. Enumerate every
// match and keep the global-nearest to the fallback VA.
int fallbackOff = fallbackVa - text.TextBaseVa;
int chosen = firstMatch;
int bestDist = Math.Abs(firstMatch - fallbackOff);
int matchCount = 1;
string detail;
if (bestDist != 0) // exact-VA short-circuit — no other match can beat this
{
int searchFrom = firstMatch + 1;
while (true)
{
int next = PatternScanner.FindPatternInRegion(text.Bytes, pattern, searchFrom, text.Bytes.Length);
if (next < 0) break;
matchCount++;
int dist = Math.Abs(next - fallbackOff);
if (dist < bestDist) { bestDist = dist; chosen = next; }
if (bestDist == 0) break;
searchFrom = next + 1;
}
}
if (matchCount == 1)
{
detail = "pattern-unique";
}
else
{
detail = $"pattern-multimatch(near-fallback {chosen:X}, {matchCount} matches)";
RynthLog.Compat(
$"HookResolver[{functionName}]: pattern matched {matchCount} locations — " +
$"chose 0x{text.TextBaseVa + chosen:X8} as nearest to fallback 0x{fallbackVa:X8}.");
}
IntPtr addr = new IntPtr(text.TextBaseVa + chosen);
RynthLog.Info(
$"HookResolver[{functionName}]: RESOLVED via {detail} @ 0x{addr.ToInt32():X8} " +
$"(fallbackVa=0x{fallbackVa:X8}, delta={(addr.ToInt32() - fallbackVa):+#;-#;0}).");
return new ResolveResult(addr, ResolveSource.PatternScan, detail);
}
// Pattern miss — try the hardcoded VA, but only if the bytes there
// look plausible (not padding / interrupt fill / a bare ret).
int vaOff = fallbackVa - text.TextBaseVa;
if (vaOff >= 0 && vaOff < text.Bytes.Length)
{
byte firstByte = text.Bytes[vaOff];
bool prologueLooksValid = firstByte is not (0x00 or 0xCC or 0xC3);
if (prologueLooksValid)
{
IntPtr addr = new IntPtr(fallbackVa);
RynthLog.Compat(
$"HookResolver[{functionName}]: PATTERN MISS — falling back to hardcoded VA 0x{fallbackVa:X8} " +
$"(prologue byte=0x{firstByte:X2}). The binary may have shifted; install proceeds but is RISKY.");
return new ResolveResult(addr, ResolveSource.FallbackVa, $"fallback-va(prologue=0x{firstByte:X2})");
}
RynthLog.Compat(
$"HookResolver[{functionName}]: UNAVAILABLE — pattern not found AND fallback VA 0x{fallbackVa:X8} " +
$"prologue is invalid (byte=0x{firstByte:X2}).");
}
else
{
RynthLog.Compat(
$"HookResolver[{functionName}]: UNAVAILABLE — pattern not found AND fallback VA 0x{fallbackVa:X8} " +
$"is outside the readable .text window.");
}
return new ResolveResult(IntPtr.Zero, ResolveSource.Failed, "unavailable");
}
catch (Exception ex)
{
RynthLog.Compat($"HookResolver[{functionName}]: UNAVAILABLE — exception during resolve: {ex.GetType().Name}: {ex.Message}");
return new ResolveResult(IntPtr.Zero, ResolveSource.Failed, $"exception:{ex.GetType().Name}");
}
}
/// <summary>
/// Resolve a DATA/global address (.data/.rdata — singleton ptr, selection id, string
/// null-buffer, fn-ptr slot, …) by CODE-XREF: pattern-scan .text for a unique instruction
/// that references the address as an absolute operand (the 4 operand bytes wildcarded in
/// <paramref name="codePattern"/>), then read the address back from that operand at
/// <paramref name="operandOffset"/>. Robust if the global relocates across builds.
///
/// Unlike function resolution this does NOT fail closed: the data VA is read/written by the
/// caller, which assumes it always has one, so a miss falls back to the hardcoded VA (== old
/// behavior) with a loud log rather than returning Zero.
/// </summary>
public static ResolveResult ResolveData(
AcClientTextSection text, string name, byte?[] codePattern, int operandOffset, int fallbackVa)
{
try
{
int first = PatternScanner.FindPattern(text.Bytes, codePattern);
if (first >= 0 && first + operandOffset + 4 <= text.Bytes.Length)
{
int next = PatternScanner.FindPatternInRegion(text.Bytes, codePattern, first + 1, text.Bytes.Length);
if (next < 0)
{
int operand = BitConverter.ToInt32(text.Bytes, first + operandOffset);
RynthLog.Info(
$"HookResolver[{name}]: RESOLVED via data-xref @ 0x{operand:X8} " +
$"(fallbackVa=0x{fallbackVa:X8}, delta={(operand - fallbackVa):+#;-#;0}).");
return new ResolveResult(new IntPtr(operand), ResolveSource.PatternScan, "data-xref");
}
RynthLog.Compat(
$"HookResolver[{name}]: data-xref matched MULTIPLE .text sites — falling back to hardcoded VA 0x{fallbackVa:X8} (RISKY).");
}
else
{
RynthLog.Compat(
$"HookResolver[{name}]: data-xref pattern not found — falling back to hardcoded VA 0x{fallbackVa:X8} (RISKY).");
}
return new ResolveResult(new IntPtr(fallbackVa), ResolveSource.FallbackVa, "data-fallback");
}
catch (Exception ex)
{
RynthLog.Compat($"HookResolver[{name}]: data-xref exception {ex.GetType().Name}: {ex.Message} — fallback VA 0x{fallbackVa:X8}.");
return new ResolveResult(new IntPtr(fallbackVa), ResolveSource.FallbackVa, "data-fallback-exc");
}
}
}

View file

@ -0,0 +1,73 @@
using System;
using System.IO;
using System.Text.Json;
namespace RynthCore.Engine.Compatibility;
internal static class LauncherSettings
{
private static readonly object Sync = new();
private static bool _loaded;
private static bool _allowMultipleClients;
private static string _statusMessage = "Launcher settings not loaded.";
public static bool AllowMultipleClientsEnabled
{
get
{
EnsureLoaded();
return _allowMultipleClients;
}
}
public static string StatusMessage
{
get
{
EnsureLoaded();
return _statusMessage;
}
}
private static void EnsureLoaded()
{
lock (Sync)
{
if (_loaded)
return;
_loaded = true;
try
{
string settingsPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"RynthCore",
"appsettings.json");
if (!File.Exists(settingsPath))
{
_statusMessage = $"Launcher settings file not found ({settingsPath}).";
return;
}
using JsonDocument document = JsonDocument.Parse(File.ReadAllBytes(settingsPath));
if (!document.RootElement.TryGetProperty("AllowMultipleClients", out JsonElement property) ||
(property.ValueKind != JsonValueKind.True && property.ValueKind != JsonValueKind.False))
{
_statusMessage = "AllowMultipleClients not present in launcher settings.";
return;
}
_allowMultipleClients = property.GetBoolean();
_statusMessage = _allowMultipleClients
? "AllowMultipleClients enabled in launcher settings."
: "AllowMultipleClients disabled in launcher settings.";
}
catch (Exception ex)
{
_statusMessage = $"Failed to read launcher settings - {ex.Message}";
}
}
}
}

View file

@ -0,0 +1,154 @@
using System;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
namespace RynthCore.Engine.Compatibility;
internal static class LoginLifecycleHooks
{
private const int ExpectedImageSize = 0x56D000;
private static readonly byte?[] SendLoginCompletePattern =
[
0x6A, 0x01, 0xC6, 0x86, null, null, null, null,
0x01, 0xE8, null, null, null, null, 0x8B, 0x0D,
null, null, null, null, 0x83, 0xC4, 0x04, 0x6A,
0x00, 0x6A, 0x0B, 0xE8
];
private static readonly byte[] SendLoginCompletePrologue = [0x56, 0x8B, 0xF1];
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void SendLoginCompleteNotificationDelegate(IntPtr thisPtr);
private static SendLoginCompleteNotificationDelegate? _originalSendLoginCompleteNotification;
private static SendLoginCompleteNotificationDelegate? _sendLoginCompleteNotificationDetour;
private static IntPtr _targetAddress;
private static string _statusMessage = "Not probed yet.";
private static long _nextStatusLogTick;
private static bool _waitingLogged;
public static bool IsInstalled { get; private set; }
public static bool HasObservedLoginComplete { get; private set; }
public static string StatusMessage => _statusMessage;
public static event Action? LoginComplete;
public static void Initialize()
{
if (IsInstalled)
return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
{
_statusMessage = "acclient.exe not available.";
return;
}
try
{
int imageSize = textSection.ImageSize;
if (imageSize != ExpectedImageSize)
RynthLog.Verbose($"Compat: login lifecycle hook using unverified acclient image size 0x{imageSize:X} (expected 0x{ExpectedImageSize:X}).");
int callSiteOff = PatternScanner.FindPattern(textSection.Bytes, SendLoginCompletePattern);
if (callSiteOff < 0)
{
_statusMessage = "SendLoginCompleteNotification call site pattern not found.";
RynthLog.Compat($"Compat: login lifecycle hook failed - {_statusMessage}");
return;
}
int funcOff = PatternScanner.FindPrologueBefore(
textSection.Bytes,
callSiteOff,
SendLoginCompletePrologue,
maxDistance: 0x100);
if (funcOff < 0)
{
_statusMessage = "SendLoginCompleteNotification prologue not found.";
RynthLog.Compat($"Compat: login lifecycle hook failed - {_statusMessage}");
return;
}
_targetAddress = new IntPtr(textSection.TextBaseVa + funcOff);
_sendLoginCompleteNotificationDetour = SendLoginCompleteNotificationDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_sendLoginCompleteNotificationDetour);
_originalSendLoginCompleteNotification = Marshal.GetDelegateForFunctionPointer<SendLoginCompleteNotificationDelegate>(MinHook.HookCreate(_targetAddress, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(_targetAddress);
IsInstalled = true;
_statusMessage = $"Hooked SendLoginCompleteNotification @ 0x{_targetAddress.ToInt32():X8}.";
_nextStatusLogTick = Environment.TickCount64 + 3000;
RynthLog.Info(
$"LoginLifecycleHooks: target=0x{_targetAddress.ToInt32():X8} (funcOff=0x{funcOff:X8}, callSite=0x{textSection.TextBaseVa + callSiteOff:X8}, prologueDistance={(textSection.TextBaseVa + callSiteOff) - _targetAddress.ToInt32()} bytes).");
}
catch (Exception ex)
{
_statusMessage = ex.Message;
RynthLog.Compat($"Compat: login lifecycle hook failed - {ex.Message}");
}
}
/// <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)
return;
long now = Environment.TickCount64;
if (now < _nextStatusLogTick)
return;
_nextStatusLogTick = now + 3000;
if (!_waitingLogged)
{
_waitingLogged = true;
RynthLog.Verbose("Compat: login lifecycle awaiting SendLoginCompleteNotification.");
}
}
private static void SendLoginCompleteNotificationDetour(IntPtr thisPtr)
{
RecursionGuard.Tick("LoginLifecycleHooks.SendLoginCompleteNotification");
_originalSendLoginCompleteNotification!(thisPtr);
SignalLoginComplete("CPlayerSystem::SendLoginCompleteNotification");
}
private static void SignalLoginComplete(string source)
{
if (HasObservedLoginComplete)
return;
HasObservedLoginComplete = true;
_statusMessage = $"Login complete observed via {source}.";
RynthLog.Verbose($"Compat: login complete observed via {source}.");
LoginComplete?.Invoke();
}
/// <summary>
/// Mark login as already complete and fire the <see cref="LoginComplete"/>
/// event without waiting for the AC client's
/// <c>SendLoginCompleteNotification</c>. Used by the hot-reload path: the
/// new engine instance starts after the game is already in-world, so the
/// notification will never fire again — we synthesize it so subscribers
/// (PluginManager, D3D9 bootstrapper) reach their post-login state.
/// </summary>
public static void MarkAlreadyComplete(string source)
{
SignalLoginComplete(source);
}
}

View file

@ -0,0 +1,320 @@
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Waits for the post-connect pre-character signal, then sends the same dismiss
/// clicks Thwarg uses to advance past the startup logo screens. This must be
/// started early so the client window is available before the login sequence runs.
/// </summary>
internal static class LogoBypassHooks
{
private const int IdlePollMs = 50;
private const int TimeoutSeconds = 30;
private const int HwndPollMs = 200;
private const int HwndPollMaxMs = 10_000;
private const int ScheduledDismissClicks = 2;
private const int PostConnectDismissStartDelayMs = 1000;
private const int CharacterListDismissStartDelayMs = 300;
private const int DismissRepeatDelayMs = 300;
private const int AutoLoginAfterDismissDelayMs = 900;
private const int DismissClickX = 350;
private const int DismissClickY = 100;
// Early-burst dismiss: covers the pre-connect splash/EULA/Turbine logo
// screens. Those screens appear before AC contacts the server, so the
// packet-driven NotifyPostConnect / NotifyCharacterList triggers can never
// catch them. As soon as we find a window of our PID, fire a series of
// clicks at the splash hotspot to dismiss whatever shows up. Decal sidesteps
// this by directly patching AC's splash code; we don't have that path, so
// we brute-force it with PostMessage spam.
private const int EarlyBurstClicks = 12;
private const int EarlyBurstIntervalMs = 400;
private const uint WM_MOUSEMOVE = 0x0200;
private const uint WM_LBUTTONDOWN = 0x0201;
private const uint WM_LBUTTONUP = 0x0202;
[DllImport("kernel32.dll")]
private static extern uint GetCurrentProcessId();
[DllImport("user32.dll")]
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsWindowVisible(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
private static volatile bool _started;
private static readonly object StateLock = new();
private static int _pendingDismissClicks;
private static long _nextDismissTick;
private static long _recommendedAutoLoginTick;
/// <summary>
/// Call early in InitWorker, before D3D9/Win32Backend are initialized.
/// Reads <c>SkipLoginLogos</c> from <c>launch_context.json</c>; does nothing if false or missing.
/// </summary>
public static void Start()
{
if (_started)
return;
if (!ReadSkipLogosFromContext())
return;
if (LoginLifecycleHooks.HasObservedLoginComplete)
{
RynthLog.Compat("LogoBypass: Login already complete at start - skipping.");
return;
}
_started = true;
lock (StateLock)
{
_pendingDismissClicks = 0;
_nextDismissTick = 0;
_recommendedAutoLoginTick = 0;
}
var thread = new Thread(BypassThread)
{
Name = "RynthCore.LogoBypass",
IsBackground = true
};
thread.Start();
RynthLog.Compat("LogoBypass: Started - waiting for post-connect or character-list signal before dismiss clicks.");
}
public static void NotifyCharacterListObserved()
{
ScheduleDismissClicks("Character-list signal", CharacterListDismissStartDelayMs);
}
public static void NotifyPostConnectObserved()
{
ScheduleDismissClicks("Post-connect signal", PostConnectDismissStartDelayMs);
}
public static int GetRecommendedAutoLoginDelayMs()
{
lock (StateLock)
{
if (_recommendedAutoLoginTick == 0)
return 0;
long remaining = _recommendedAutoLoginTick - Environment.TickCount64;
return remaining > 0 ? (int)Math.Min(remaining, int.MaxValue) : 0;
}
}
private static void BypassThread()
{
IntPtr hwnd = PollForGameWindow();
if (hwnd == IntPtr.Zero)
{
RynthLog.Compat("LogoBypass: Could not find game HWND - giving up.");
return;
}
RynthLog.Compat($"LogoBypass: Found game HWND 0x{hwnd:X8} - firing {EarlyBurstClicks} early dismiss clicks before awaiting packet signals.");
EarlyBurstDismiss(hwnd);
BypassLoop(hwnd);
}
/// <summary>
/// Fires a burst of dismiss clicks immediately, covering the pre-connect
/// splash/EULA screens that the packet-driven triggers can't catch.
/// Stops early if the client transitions out of the pre-login state
/// (LoginComplete or auto-login-already-fired). Cheap to call into a
/// post-splash window: the clicks just become spurious viewport clicks
/// that AC's pre-connect UI ignores.
/// </summary>
private static void EarlyBurstDismiss(IntPtr hwnd)
{
for (int i = 0; i < EarlyBurstClicks; i++)
{
if (LoginLifecycleHooks.HasObservedLoginComplete)
return;
SendDismissInput(hwnd);
Thread.Sleep(EarlyBurstIntervalMs);
}
}
private static void ScheduleDismissClicks(string triggerName, int startDelayMs)
{
if (!_started)
return;
long now = Environment.TickCount64;
bool scheduled = false;
lock (StateLock)
{
if (_pendingDismissClicks <= 0 && (_recommendedAutoLoginTick == 0 || now >= _recommendedAutoLoginTick))
{
_pendingDismissClicks = ScheduledDismissClicks;
_nextDismissTick = now + startDelayMs;
_recommendedAutoLoginTick = _nextDismissTick
+ ((ScheduledDismissClicks - 1L) * DismissRepeatDelayMs)
+ AutoLoginAfterDismissDelayMs;
scheduled = true;
}
}
if (scheduled)
{
RynthLog.Compat(
$"LogoBypass: {triggerName} observed - scheduling {ScheduledDismissClicks} dismiss click(s) at ({DismissClickX}, {DismissClickY}) with {startDelayMs}ms start delay.");
}
}
private static IntPtr PollForGameWindow()
{
uint pid = GetCurrentProcessId();
int elapsed = 0;
while (elapsed < HwndPollMaxMs)
{
IntPtr found = IntPtr.Zero;
EnumWindows((hWnd, _) =>
{
GetWindowThreadProcessId(hWnd, out uint windowPid);
if (windowPid == pid && IsWindowVisible(hWnd))
{
found = hWnd;
return false;
}
return true;
}, IntPtr.Zero);
if (found != IntPtr.Zero)
return found;
Thread.Sleep(HwndPollMs);
elapsed += HwndPollMs;
}
return IntPtr.Zero;
}
private static void BypassLoop(IntPtr hwnd)
{
DateTime deadline = DateTime.UtcNow.AddSeconds(TimeoutSeconds);
try
{
while (!LoginLifecycleHooks.HasObservedLoginComplete &&
DateTime.UtcNow < deadline)
{
if (TryTakeDueDismissClick())
SendDismissInput(hwnd);
else
Thread.Sleep(IdlePollMs);
}
}
finally
{
string reason = LoginLifecycleHooks.HasObservedLoginComplete ? "login complete" : "timeout";
RynthLog.Verbose($"LogoBypass: Stopped ({reason}).");
}
}
private static bool TryTakeDueDismissClick()
{
lock (StateLock)
{
if (_pendingDismissClicks <= 0)
return false;
long now = Environment.TickCount64;
if (now < _nextDismissTick)
return false;
_pendingDismissClicks--;
_nextDismissTick = _pendingDismissClicks > 0 ? now + DismissRepeatDelayMs : 0;
return true;
}
}
private static void SendDismissInput(IntPtr hwnd)
{
IntPtr lParam = MakeLParam(DismissClickX, DismissClickY);
PostMessage(hwnd, WM_MOUSEMOVE, IntPtr.Zero, lParam);
PostMessage(hwnd, WM_LBUTTONDOWN, (IntPtr)0x0001, lParam);
PostMessage(hwnd, WM_LBUTTONUP, IntPtr.Zero, lParam);
RynthLog.Compat($"LogoBypass: Sent dismiss click at ({DismissClickX}, {DismissClickY}) to hwnd=0x{hwnd.ToInt64():X8}.");
}
private static IntPtr MakeLParam(int x, int y) =>
(IntPtr)unchecked((uint)((y << 16) | (x & 0xFFFF)));
private static bool ReadSkipLogosFromContext()
{
string rootDir = "(unresolved)";
try
{
rootDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"RynthCore");
string processPath = Path.Combine(rootDir, "launch_contexts", $"launch_context_{Environment.ProcessId}.json");
RynthLog.Compat($"LogoBypass: ReadSkipLogosFromContext processId={Environment.ProcessId} processPath='{processPath}'");
bool? processValue = ReadSkipLogosFromFile(processPath, "process");
if (processValue.HasValue)
{
RynthLog.Compat($"LogoBypass: process-scoped context resolved SkipLoginLogos={processValue.Value}.");
return processValue.Value;
}
string rootPath = Path.Combine(rootDir, "launch_context.json");
RynthLog.Compat($"LogoBypass: process file did not yield value, falling back to rootPath='{rootPath}'");
bool? rootValue = ReadSkipLogosFromFile(rootPath, "root");
bool resolved = rootValue ?? false;
RynthLog.Compat($"LogoBypass: root context resolved SkipLoginLogos={(rootValue.HasValue ? rootValue.Value.ToString() : "MISSING")} (effective={resolved}).");
return resolved;
}
catch (Exception ex)
{
RynthLog.Compat($"LogoBypass: ReadSkipLogosFromContext threw {ex.GetType().Name}: {ex.Message} (rootDir='{rootDir}'). Treating as SkipLoginLogos=false.");
return false;
}
}
private static bool? ReadSkipLogosFromFile(string path, string label)
{
if (!File.Exists(path))
{
RynthLog.Compat($"LogoBypass: {label} context file missing at '{path}'.");
return null;
}
try
{
using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(path));
if (!doc.RootElement.TryGetProperty("SkipLoginLogos", out JsonElement el))
{
RynthLog.Compat($"LogoBypass: {label} context at '{path}' has no SkipLoginLogos property.");
return null;
}
return el.GetBoolean();
}
catch (Exception ex)
{
RynthLog.Compat($"LogoBypass: {label} context at '{path}' read/parse failed: {ex.GetType().Name}: {ex.Message}.");
return null;
}
}
}

View file

@ -0,0 +1,171 @@
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.
///
/// - <c>CPlayerSystem::ExecuteLogOff(void)</c> — fires when the player has confirmed
/// the logoff prompt and the actual logoff begins.
/// - <c>gmGamePlayUI::RecvNotice_Logoff(void)</c> — server-driven full logoff notice.
///
/// Either one raises <see cref="LogoutComplete"/> once per logout cycle.
///
/// Both addresses are now resolved via HookResolver — pattern-scan first,
/// fallback VA second, UNAVAILABLE if neither works.
/// </summary>
internal static class LogoutLifecycleHooks
{
// Fallback VAs (4,841,472-byte client). Pattern-scan is the source of truth.
private const int ExecuteLogOffFallbackVa = 0x0055E4A0;
private const int RecvNoticeLogoffFallbackVa = 0x004ECBA0;
// CPlayerSystem::ExecuteLogOff(void)
// Two consecutive 'mov byte ptr [esi+0x213],bl' / 'mov byte ptr [esi+0x221],bl'
// — those CPlayerSystem flags clears are unique anchor.
private static readonly byte?[] ExecuteLogOffPattern =
[
0x53, 0x56, 0x8B, 0xF1, 0x33, 0xDB, 0x88, 0x9E,
0x13, 0x02, 0x00, 0x00, 0x88, 0x9E, 0x21, 0x02,
0x00, 0x00,
0x8B, 0x0D, null, null, null, null, // mov ecx, ds:[imm32]
0xA1, null, null, null, null, // mov eax, ds:[imm32]
0x89, 0x86, 0x00, 0x02, 0x00, 0x00
];
// gmGamePlayUI::RecvNotice_Logoff(void)
// 0x90 stack frame, sets two booleans at +0x2D / +0x2E, then E8 to a helper.
private static readonly byte?[] RecvNoticeLogoffPattern =
[
0x81, 0xEC, 0x90, 0x00, 0x00, 0x00, 0x56, 0x8B,
0xF1, 0xB0, 0x01, 0x8D, 0x4C, 0x24, 0x04, 0x88,
0x46, 0x2D, 0x88, 0x46, 0x2E,
0xE8, null, null, null, null, // call rel32
0xA1, null, null, null, null, // mov eax, ds:[imm32]
0x68, 0x01, 0x00, 0x00, 0x10
];
[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;
public static event Action? LogoutComplete;
public static void Initialize()
{
if (IsInstalled)
return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
{
_statusMessage = "acclient.exe not available.";
return;
}
bool anyHooked = false;
anyHooked |= TryInstall(textSection, "LogoutLifecycle.ExecuteLogOff",
ExecuteLogOffPattern, ExecuteLogOffFallbackVa, ExecuteLogOffDetour,
out _executeLogOffAddress, out _executeLogOffDetour, out _originalExecuteLogOff);
anyHooked |= TryInstall(textSection, "LogoutLifecycle.RecvNotice_Logoff",
RecvNoticeLogoffPattern, RecvNoticeLogoffFallbackVa, RecvNoticeLogoffDetour,
out _logoffAddress, out _recvNoticeLogoffDetour, out _originalRecvNoticeLogoff);
if (anyHooked)
{
IsInstalled = true;
RynthLog.Compat($"LogoutLifecycleHooks: ready (ExecuteLogOff=0x{_executeLogOffAddress.ToInt32():X8}, RecvNotice_Logoff=0x{_logoffAddress.ToInt32():X8}).");
}
}
private static bool TryInstall(
AcClientTextSection textSection, string name,
byte?[] pattern, int fallbackVa, ThisCallVoidDelegate detour,
out IntPtr address, out ThisCallVoidDelegate detourField, out ThisCallVoidDelegate? original)
{
address = IntPtr.Zero;
detourField = detour;
original = null;
var resolved = HookResolver.Resolve(textSection, name, pattern, fallbackVa);
if (!resolved.Success)
return false;
try
{
address = resolved.Address;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(detourField);
original = Marshal.GetDelegateForFunctionPointer<ThisCallVoidDelegate>(
MinHook.HookCreate(address, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(address);
return true;
}
catch (Exception ex)
{
_statusMessage = ex.Message;
RynthLog.Compat($"LogoutLifecycleHooks: {name} install threw {ex.GetType().Name}: {ex.Message}");
return false;
}
}
public static void ResetObservation()
{
HasObservedLogout = false;
}
private static void ExecuteLogOffDetour(IntPtr thisPtr)
{
RecursionGuard.Tick("LogoutLifecycleHooks.ExecuteLogOff");
if (!HasObservedLogout)
RynthLog.Compat("LogoutLifecycleHooks: ExecuteLogOff detour entered.");
try { _originalExecuteLogOff!(thisPtr); }
catch (Exception ex) { try { RynthLog.Compat($"LogoutLifecycleHooks: ExecuteLogOff original threw {ex.GetType().Name}: {ex.Message}"); } catch { } }
RaiseLogoutCompleteOnce("CPlayerSystem::ExecuteLogOff");
}
private static void RecvNoticeLogoffDetour(IntPtr thisPtr)
{
RecursionGuard.Tick("LogoutLifecycleHooks.RecvNoticeLogoff");
if (!HasObservedLogout)
RynthLog.Compat("LogoutLifecycleHooks: RecvNotice_Logoff detour entered.");
try { _originalRecvNoticeLogoff!(thisPtr); }
catch (Exception ex) { try { RynthLog.Compat($"LogoutLifecycleHooks: RecvNotice_Logoff original threw {ex.GetType().Name}: {ex.Message}"); } catch { } }
RaiseLogoutCompleteOnce("gmGamePlayUI::RecvNotice_Logoff");
}
private static void RaiseLogoutCompleteOnce(string source)
{
if (HasObservedLogout)
return;
HasObservedLogout = true;
_statusMessage = $"Logout observed via {source}.";
RynthLog.Compat($"LogoutLifecycleHooks: logout observed via {source} — raising LogoutComplete.");
try { LogoutComplete?.Invoke(); }
catch (Exception ex)
{
RynthLog.Compat($"LogoutLifecycleHooks: handler threw {ex.GetType().Name}: {ex.Message}");
}
}
}

View file

@ -0,0 +1,62 @@
using System.Runtime.InteropServices;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Tracks which OS thread is AC's main thread, so RynthCore code that's about
/// to call into AC's internals (CACQualities accessors, etc.) can refuse the
/// call from any other thread.
///
/// AC's client is not thread-safe: its internal data structures (qualities
/// hash tables, enchantment lists, object tables) are mutated by the main
/// thread without locking. Reading them from another thread can observe a
/// sub-pointer in the middle of being reassigned, which appears as null and
/// AVs three frames deep inside AC (consistent crash at 0x00416C86 reading
/// [null+0x28] from the DecalCoexistence plugin-tick thread, 2026-05-14).
///
/// Capture: any of our [UnmanagedCallersOnly] detours runs on the thread that
/// called the detoured function. AC's main thread is what invokes
/// SetCombatMode, BusyCount updates, SmartBox/GameEvent dispatch, etc. The
/// first detour to fire after install latches that thread ID; everything
/// after compares against it.
/// </summary>
internal static class MainThreadGuard
{
private static uint _acMainNativeTid;
[DllImport("kernel32.dll")]
private static extern uint GetCurrentThreadId();
/// <summary>
/// Latch the current native thread ID as AC's main thread. Idempotent;
/// only the first caller wins. Safe to call from any [UnmanagedCallersOnly]
/// detour body — those run on whichever thread invoked the detoured AC
/// function, which is AC's main thread for the detours we install.
/// </summary>
public static void RecordIfFirst()
{
if (_acMainNativeTid != 0) return;
uint tid = GetCurrentThreadId();
Interlocked.CompareExchange(ref _acMainNativeTid, tid, 0);
}
/// <summary>
/// True if AC's main thread has been observed AND the calling thread is
/// that thread. Returns false before the main thread is known, so any
/// cross-thread caller fails closed (refuses to enter AC) during early
/// init too.
/// </summary>
public static bool IsOnMainThread()
{
uint mainTid = _acMainNativeTid;
if (mainTid == 0) return false;
return GetCurrentThreadId() == mainTid;
}
/// <summary>
/// Diagnostic accessor — for logging the captured thread ID at startup
/// or in crash reports. Zero if not yet captured.
/// </summary>
public static uint MainThreadId => _acMainNativeTid;
}

View file

@ -0,0 +1,249 @@
using System;
using System.Runtime.InteropServices;
namespace RynthCore.Engine.Compatibility;
internal static class MovementActionHooks
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool DoMovementCommandDelegate(uint motion, float speed, int holdKey);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool StopMovementCommandDelegate(uint motion, int holdKey);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool JumpNonAutonomousDelegate(float extent);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate bool AutonomyLevelDelegate(uint level);
public const uint MotionWalkForward = 0x45000005;
public const uint MotionWalkBackward = 0x45000006;
public const uint MotionRunForward = 0x41000003;
public const uint MotionTurnRight = 0x6500000D;
public const uint MotionTurnLeft = 0x6500000E;
public const uint MotionSidestepRight = 0x6500000F;
public const uint MotionSidestepLeft = 0x65000010;
public const int HoldKeyNone = 0;
public const int HoldKeyRun = 1;
public const int HoldKeyAutorun = 2;
private static readonly byte[] MovementPrologue = [0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8];
private static DoMovementCommandDelegate? _doMovement;
private static StopMovementCommandDelegate? _stopMovement;
private static JumpNonAutonomousDelegate? _jumpNonAutonomous;
private static AutonomyLevelDelegate? _autonomyLevel;
private static string _statusMessage = "Not probed yet.";
public static bool IsInitialized { get; private set; }
public static bool HasDoMovement => _doMovement != null;
public static bool HasStopMovement => _stopMovement != null;
public static bool HasJumpNonAutonomous => _jumpNonAutonomous != null;
public static bool HasAutonomyLevel => _autonomyLevel != null;
public static string StatusMessage => _statusMessage;
public static bool Probe()
{
Reset();
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
{
_statusMessage = "acclient.exe not available.";
return false;
}
try
{
byte[] text = textSection.Bytes;
byte[] stopOpcode = [0xC7, 0x02, 0x61, 0xF6, 0x00, 0x00];
int stopOpcodeOff = PatternScanner.FindPattern(text, stopOpcode);
if (stopOpcodeOff < 0)
{
_statusMessage = "StopMovement opcode 0xF661 not found.";
RynthLog.Compat("Compat: movement probe failed - StopMovement opcode 0xF661 not found.");
return false;
}
int stopFuncOff = PatternScanner.FindPrologueBefore(text, stopOpcodeOff, MovementPrologue);
if (stopFuncOff < 0)
{
_statusMessage = "StopMovement prologue not found.";
RynthLog.Compat("Compat: movement probe failed - StopMovement prologue not found.");
return false;
}
int regionStart = Math.Max(0, stopOpcodeOff - 0x700);
int regionEnd = Math.Min(text.Length, stopOpcodeOff + 0x300);
byte[] doOpcode = [0xC7, 0x02, 0x1E, 0xF6, 0x00, 0x00];
int doOpcodeOff = PatternScanner.FindPatternInRegion(text, doOpcode, regionStart, regionEnd);
int doFuncOff = doOpcodeOff >= 0
? PatternScanner.FindPrologueBefore(text, doOpcodeOff, MovementPrologue)
: -1;
byte[] jumpOpcode = [0xC7, 0x02, 0xC9, 0xF7, 0x00, 0x00];
int jumpOpcodeOff = PatternScanner.FindPatternInRegion(text, jumpOpcode, regionStart, regionEnd);
int jumpFuncOff = jumpOpcodeOff >= 0
? PatternScanner.FindPrologueBefore(text, jumpOpcodeOff, MovementPrologue)
: -1;
byte[] autonomyOpcode = [0xC7, 0x02, 0x52, 0xF7, 0x00, 0x00];
int autonomyOpcodeOff = PatternScanner.FindPatternInRegion(text, autonomyOpcode, regionStart, regionEnd);
int autonomyFuncOff = autonomyOpcodeOff >= 0
? PatternScanner.FindPrologueBefore(text, autonomyOpcodeOff, MovementPrologue)
: -1;
if (doFuncOff < 0)
{
_statusMessage = "DoMovement opcode 0xF61E not found.";
RynthLog.Compat("Compat: movement probe incomplete - DoMovement opcode 0xF61E not found.");
return false;
}
int stopVa = textSection.TextBaseVa + stopFuncOff;
int doVa = textSection.TextBaseVa + doFuncOff;
_stopMovement = Marshal.GetDelegateForFunctionPointer<StopMovementCommandDelegate>(new IntPtr(stopVa));
_doMovement = Marshal.GetDelegateForFunctionPointer<DoMovementCommandDelegate>(new IntPtr(doVa));
if (jumpFuncOff >= 0)
{
int jumpVa = textSection.TextBaseVa + jumpFuncOff;
_jumpNonAutonomous = Marshal.GetDelegateForFunctionPointer<JumpNonAutonomousDelegate>(new IntPtr(jumpVa));
RynthLog.Verbose($"Compat: movement jump hook ready - jump=0x{jumpVa:X8}");
}
if (autonomyFuncOff >= 0)
{
int autonomyVa = textSection.TextBaseVa + autonomyFuncOff;
_autonomyLevel = Marshal.GetDelegateForFunctionPointer<AutonomyLevelDelegate>(new IntPtr(autonomyVa));
RynthLog.Verbose($"Compat: movement autonomy hook ready - autonomy=0x{autonomyVa:X8}");
}
IsInitialized = true;
_statusMessage = jumpFuncOff >= 0 && autonomyFuncOff >= 0
? "Ready."
: $"Partial. jump={jumpFuncOff >= 0}, autonomy={autonomyFuncOff >= 0}.";
RynthLog.Verbose($"Compat: movement hooks ready - stop=0x{stopVa:X8}, move=0x{doVa:X8}");
return true;
}
catch (Exception ex)
{
Reset();
_statusMessage = ex.Message;
RynthLog.Compat($"Compat: movement probe failed - {ex.Message}");
return false;
}
}
// Light counters so we can see in the log that the bot's movement
// commands are actually reaching AC and what AC says about each call.
// Logged at Compat every 8th call after the first 3, so a busy patrol
// loop doesn't flood the log but a one-shot test still shows up.
private static int _doMovementCalls;
private static int _stopMovementCalls;
private static int _jumpCalls;
private static int _autonomyCalls;
private static bool ShouldLog(int n) => n <= 3 || (n & 0x7) == 0;
public static bool DoMovement(uint motion, float speed = 1.0f, int holdKey = HoldKeyRun)
{
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueDoMovement(motion, speed, holdKey);
int n = System.Threading.Interlocked.Increment(ref _doMovementCalls);
if (_doMovement == null)
{
if (ShouldLog(n))
RynthLog.Compat($"Move: DoMovement(motion=0x{motion:X8}, speed={speed:0.00}, holdKey={holdKey}) #{n} — delegate null (probe failed).");
return false;
}
try
{
bool ok = _doMovement(motion, speed, holdKey);
if (ShouldLog(n))
RynthLog.Compat($"Move: DoMovement(motion=0x{motion:X8}, speed={speed:0.00}, holdKey={holdKey}) #{n} -> {ok}");
return ok;
}
catch (Exception ex)
{
if (ShouldLog(n))
RynthLog.Compat($"Move: DoMovement(motion=0x{motion:X8}) #{n} threw {ex.GetType().Name}: {ex.Message}");
return false;
}
}
public static bool StopMovement(uint motion, int holdKey = HoldKeyRun)
{
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueStopMovement(motion, holdKey);
int n = System.Threading.Interlocked.Increment(ref _stopMovementCalls);
if (_stopMovement == null)
{
if (ShouldLog(n))
RynthLog.Compat($"Move: StopMovement(motion=0x{motion:X8}, holdKey={holdKey}) #{n} — delegate null.");
return false;
}
try
{
bool ok = _stopMovement(motion, holdKey);
if (ShouldLog(n))
RynthLog.Compat($"Move: StopMovement(motion=0x{motion:X8}, holdKey={holdKey}) #{n} -> {ok}");
return ok;
}
catch (Exception ex)
{
if (ShouldLog(n))
RynthLog.Compat($"Move: StopMovement(motion=0x{motion:X8}) #{n} threw {ex.GetType().Name}: {ex.Message}");
return false;
}
}
public static bool JumpNonAutonomous(float extent)
{
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueJump(extent);
if (_jumpNonAutonomous == null)
return false;
try
{
return _jumpNonAutonomous(Math.Clamp(extent, 0f, 1f));
}
catch
{
return false;
}
}
public static bool SetAutonomyLevel(uint level)
{
if (_autonomyLevel == null)
return false;
try
{
return _autonomyLevel(level);
}
catch
{
return false;
}
}
private static void Reset()
{
_doMovement = null;
_stopMovement = null;
_jumpNonAutonomous = null;
_autonomyLevel = null;
IsInitialized = false;
}
}

View file

@ -0,0 +1,185 @@
using System;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
namespace RynthCore.Engine.Compatibility;
internal static class MultiClientHooks
{
private const int ExpectedImageSize = 0x56D000;
private const int IsAlreadyRunningFallbackVa = 0x004122A0;
private const int OpenDataFileFallbackVa = 0x00675920;
// OpenDataFile's prologue tests bit 1 (value 0x2) of openFlags:
// and cl, 2
// cmp cl, 2
// That's the bit AC's code dispatches on for "shared access" — the prior
// value 0x4 was a misread of the byte sequence. Decal's coexisting clients
// open with bit 1 set; matching that lets us share with their handles.
private const uint OpenDataFileSharedAccessFlag = 0x2;
private static readonly byte?[] IsAlreadyRunningSignature =
[
0x56, 0x68, 0x30, 0x58, 0x79, 0x00, 0x6A, 0x01,
0x6A, 0x00, 0x6A, 0x00, 0x8B, 0xF1, 0xFF, 0x15
];
private static readonly byte?[] OpenDataFileSignature =
[
0x8B, 0x44, 0x24, 0x10, 0x53, 0x55, 0x8B, 0x6C,
0x24, 0x0C, 0x56, 0x57, 0x8B, 0xF1, 0x50, 0x8B,
0xC8, 0x8B, 0x44, 0x24, 0x20, 0x6A, 0x00, 0x80,
0xE1, 0x02, 0x80, 0xF9, 0x02, 0x50, 0x6A, 0x00
];
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate byte IsAlreadyRunningDelegate(IntPtr thisPtr);
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate uint OpenDataFileDelegate(
IntPtr allocator,
IntPtr fileInfo,
IntPtr fileName,
IntPtr pathToUse,
uint openFlags,
IntPtr transactionInfo);
private static IsAlreadyRunningDelegate? _detour;
private static IsAlreadyRunningDelegate? _originalIsAlreadyRunning;
private static OpenDataFileDelegate? _openDataFileDetour;
private static OpenDataFileDelegate? _originalOpenDataFile;
private static IntPtr _targetAddress;
private static IntPtr _openDataFileAddress;
private static string _statusMessage = "Not probed yet.";
public static bool IsEnabled { get; private set; }
public static bool IsAlreadyRunningInstalled { get; private set; }
public static bool OpenDataFileInstalled { get; private set; }
public static bool IsInstalled => IsAlreadyRunningInstalled && OpenDataFileInstalled;
public static string StatusMessage => _statusMessage;
public static void Initialize()
{
if (IsAlreadyRunningInstalled && OpenDataFileInstalled)
return;
bool allowMultipleClients = LauncherSettings.AllowMultipleClientsEnabled;
IsEnabled = allowMultipleClients;
_statusMessage = LauncherSettings.StatusMessage;
if (!allowMultipleClients)
{
RynthLog.Verbose($"Compat: multi-client bypass skipped - {_statusMessage}");
return;
}
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
{
_statusMessage = "acclient.exe not available.";
RynthLog.Compat($"Compat: multi-client hook failed - {_statusMessage}");
return;
}
try
{
if (textSection.ImageSize != ExpectedImageSize)
RynthLog.Verbose($"Compat: multi-client hook using unverified acclient image size 0x{textSection.ImageSize:X} (expected 0x{ExpectedImageSize:X}).");
TryInstallIsAlreadyRunningHook(textSection);
TryInstallOpenDataFileHook(textSection);
if (!IsAlreadyRunningInstalled && !OpenDataFileInstalled)
{
_statusMessage = "No multi-client compatibility hooks installed.";
RynthLog.Compat($"Compat: multi-client hook failed - {_statusMessage}");
return;
}
if (IsInstalled)
_statusMessage = $"Hooked Client::IsAlreadyRunning @ 0x{_targetAddress.ToInt32():X8} and CLBlockAllocator::OpenDataFile @ 0x{_openDataFileAddress.ToInt32():X8} (share flag 0x2).";
else
_statusMessage = $"Partial install. alreadyRunning={IsAlreadyRunningInstalled}, dataFile={OpenDataFileInstalled}.";
}
catch (Exception ex)
{
_statusMessage = ex.Message;
RynthLog.Compat($"Compat: multi-client hook failed - {ex.Message}");
}
}
private static void TryInstallIsAlreadyRunningHook(AcClientTextSection textSection)
{
var resolved = HookResolver.Resolve(textSection, "MultiClientHooks.Client::IsAlreadyRunning",
IsAlreadyRunningSignature, IsAlreadyRunningFallbackVa);
if (!resolved.Success)
return;
try
{
_targetAddress = resolved.Address;
_detour = IsAlreadyRunningDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_detour);
_originalIsAlreadyRunning = Marshal.GetDelegateForFunctionPointer<IsAlreadyRunningDelegate>(
MinHook.HookCreate(_targetAddress, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(_targetAddress);
IsAlreadyRunningInstalled = true;
RynthLog.Compat($"MultiClientHooks: IsAlreadyRunning hook ready @ 0x{_targetAddress.ToInt32():X8}.");
}
catch (Exception ex)
{
RynthLog.Compat($"MultiClientHooks: IsAlreadyRunning install threw {ex.GetType().Name}: {ex.Message}");
}
}
private static void TryInstallOpenDataFileHook(AcClientTextSection textSection)
{
var resolved = HookResolver.Resolve(textSection, "MultiClientHooks.CLBlockAllocator::OpenDataFile",
OpenDataFileSignature, OpenDataFileFallbackVa);
if (!resolved.Success)
return;
try
{
_openDataFileAddress = resolved.Address;
_openDataFileDetour = OpenDataFileDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_openDataFileDetour);
_originalOpenDataFile = Marshal.GetDelegateForFunctionPointer<OpenDataFileDelegate>(
MinHook.HookCreate(_openDataFileAddress, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(_openDataFileAddress);
OpenDataFileInstalled = true;
RynthLog.Compat($"MultiClientHooks: OpenDataFile hook ready @ 0x{_openDataFileAddress.ToInt32():X8}.");
}
catch (Exception ex)
{
RynthLog.Compat($"MultiClientHooks: OpenDataFile install threw {ex.GetType().Name}: {ex.Message}");
}
}
private static byte IsAlreadyRunningDetour(IntPtr thisPtr)
{
// Skip the original entirely: it has a side-effect MessageBox path
// that surfaces the "client is already running on this machine" dialog
// even when we'd later override its return value, so calling it makes
// things worse. Returning 0 unconditionally was the original design.
return 0;
}
private static uint OpenDataFileDetour(
IntPtr allocator,
IntPtr fileInfo,
IntPtr fileName,
IntPtr pathToUse,
uint openFlags,
IntPtr transactionInfo)
{
return _originalOpenDataFile!(
allocator,
fileInfo,
fileName,
pathToUse,
openFlags | OpenDataFileSharedAccessFlag,
transactionInfo);
}
}

View file

@ -0,0 +1,60 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Engine.Compatibility;
internal readonly record struct CreatureVitals(
uint Health, uint MaxHealth,
uint Stamina, uint MaxStamina,
uint Mana, uint MaxMana);
/// <summary>
/// Lightweight cache for creature vitals keyed by CWeenieObject pointer.
/// Populated from IdentifyObject (0xC9) CreatureProfile responses so that
/// QueryHealthResponse can resolve absolute health values, and plugins can
/// query target stamina/mana.
/// </summary>
internal static class ObjectQualityCache
{
// NOTE: a former _maxHealthByPtr (keyed by reusable CWeenieObject heap
// pointers, populated per stat-update from an UnmanagedCallersOnly detour)
// was removed 2026-06-11: it was write-only — zero readers — pure
// allocation churn in a detour plus an unbounded pointer-keyed dictionary.
private static readonly Dictionary<uint, CreatureVitals> _vitalsByObjectId = new();
private static readonly object _lock = new();
// Bound the cache: ids accumulate for the whole session otherwise. The
// cache is advisory (resolvers fall back to ratio-only); a rare wholesale
// clear is cheaper and safer than LRU bookkeeping inside detour paths.
private const int MaxEntries = 4096;
public static void SetCreatureVitals(uint objectId, CreatureVitals vitals)
{
if (objectId == 0)
return;
lock (_lock)
{
if (_vitalsByObjectId.Count >= MaxEntries && !_vitalsByObjectId.ContainsKey(objectId))
_vitalsByObjectId.Clear();
_vitalsByObjectId[objectId] = vitals;
}
}
/// <summary>Drop all cached vitals at logout — object ids don't survive the session.</summary>
public static void ClearSession()
{
lock (_lock)
_vitalsByObjectId.Clear();
}
public static bool TryGetCreatureVitals(uint objectId, out CreatureVitals vitals)
{
if (objectId == 0)
{
vitals = default;
return false;
}
lock (_lock)
return _vitalsByObjectId.TryGetValue(objectId, out vitals);
}
}

View file

@ -0,0 +1,154 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Reads per-character OnLogin chat commands from the launcher's
/// LaunchContextRecord (written per-PID under
/// %APPDATA%\RynthCore\launch_contexts\) and dispatches them via
/// <see cref="ChatCommandDispatcher"/> after AC's
/// <c>SendLoginCompleteNotification</c> fires.
///
/// Timing model mirrors Thwargle's:
/// 1. Wait for the engine's LoginComplete signal.
/// 2. Sleep <c>OnLoginWaitMs</c> (default 3000 ms — the Thwargle default).
/// 3. Dispatch each command in order with a small inter-command gap so AC's
/// chat parser has time to finish processing before the next arrives.
///
/// Single-shot per process: subscribes once, fires once. Logout/relogin within
/// the same client process is not handled here yet (would require
/// re-subscribing after LoginLifecycleHooks.ResetObservation).
/// </summary>
internal static class OnLoginCommandRunner
{
/// <summary>Inter-command delay. AC's chat parser is synchronous on the
/// main thread but the underlying network handlers benefit from breathing
/// room; 250 ms keeps things human-paced and avoids any chance of the
/// parser dropping a command queued behind a still-processing one.</summary>
private const int InterCommandGapMs = 250;
/// <summary>Fallback wait if the launcher provides 0 / unset value.</summary>
private const int DefaultWaitMs = 3000;
private static int _scheduled;
private static string _statusMessage = "Not initialized.";
public static string StatusMessage => _statusMessage;
public static void Initialize()
{
// One-shot subscription. If LoginLifecycleHooks.ResetObservation gets
// called (logout pipeline), the next LoginComplete will still fire
// through this handler and we'll re-arm via Interlocked.Exchange.
LoginLifecycleHooks.LoginComplete += OnLoginComplete;
_statusMessage = "OnLogin command runner armed.";
RynthLog.Verbose($"Compat: {_statusMessage}");
}
private static void OnLoginComplete()
{
// Guard: only schedule once per LoginComplete edge. If we ever support
// mid-session relogin, ResetForRelogin should clear this flag.
if (Interlocked.Exchange(ref _scheduled, 1) != 0)
return;
try
{
(List<string> commands, int waitMs) = ReadLaunchCommands();
if (commands.Count == 0)
{
RynthLog.Verbose("OnLogin: no commands queued for this PID — skipping dispatch.");
return;
}
int effectiveWait = waitMs > 0 ? waitMs : DefaultWaitMs;
RynthLog.Info($"OnLogin: {commands.Count} command(s) scheduled, first dispatch in {effectiveWait}ms.");
// Fire-and-forget background task. ChatCommandDispatcher.Dispatch
// is safe to call from this ThreadPool thread — NOT because AC's
// chat layer tolerates off-thread calls (it doesn't; that was the
// deep-audit finding #4 bug this comment used to claim), but
// because Dispatch() now self-marshals: an off-thread call
// enqueues onto AcMainThreadQueue and the real native dispatch
// runs on AC's main thread from the EndScene drain.
_ = Task.Run(async () => await DispatchAsync(commands, effectiveWait));
}
catch (Exception ex)
{
RynthLog.Compat($"OnLogin: scheduling failed - {ex.GetType().Name}: {ex.Message}");
}
}
private static async Task DispatchAsync(List<string> commands, int waitMs)
{
try
{
await Task.Delay(waitMs);
for (int i = 0; i < commands.Count; i++)
{
string line = commands[i];
if (string.IsNullOrWhiteSpace(line))
continue;
// Plugin-first dispatch lives inside ChatCommandDispatcher
// itself — see its plugin pre-dispatch step. So we just call
// the unified entry point here.
bool ok = ChatCommandDispatcher.Dispatch(line);
RynthLog.Info($"OnLogin: [{i + 1}/{commands.Count}] '{line}' dispatched={ok}.");
if (i + 1 < commands.Count)
await Task.Delay(InterCommandGapMs);
}
}
catch (Exception ex)
{
RynthLog.Compat($"OnLogin: dispatch loop failed - {ex.GetType().Name}: {ex.Message}");
}
}
private static (List<string> commands, int waitMs) ReadLaunchCommands()
{
string path = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"RynthCore",
"launch_contexts",
$"launch_context_{Environment.ProcessId}.json");
if (!File.Exists(path))
return (new List<string>(), 0);
try
{
using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(path));
JsonElement root = doc.RootElement;
int waitMs = 0;
if (root.TryGetProperty("OnLoginWaitMs", out JsonElement wEl) && wEl.ValueKind == JsonValueKind.Number)
waitMs = wEl.GetInt32();
var commands = new List<string>();
if (root.TryGetProperty("OnLoginCommands", out JsonElement cmdEl) && cmdEl.ValueKind == JsonValueKind.Array)
{
foreach (JsonElement entry in cmdEl.EnumerateArray())
{
string? line = entry.GetString();
if (!string.IsNullOrWhiteSpace(line))
commands.Add(line);
}
}
return (commands, waitMs);
}
catch (Exception ex)
{
RynthLog.Compat($"OnLogin: launch context parse failed - {ex.Message}");
return (new List<string>(), 0);
}
}
}

View file

@ -0,0 +1,73 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Engine.Compatibility;
// Stores per-object ObjDesc subpalette data captured in CreateObjectDetour.
// ObjDesc (x86 layout, all 4-byte fields):
// +0 vtable ptr (VisualDesc.packObj)
// +4 paletteID
// +8 firstSubpal*
// +12 lastSubpal*
// +16 num_subpalettes
// Subpalette (x86):
// +0 vtable ptr (PackObj)
// +4 subID ← palette DID
// +8 offset ← range start (sorted key)
// +12 numcolors
// +16 prev*
// +20 next*
internal static unsafe class PaletteCache
{
private static readonly Dictionary<uint, (uint SubId, uint Offset)[]> _data = new();
private static readonly object _lock = new();
public static void ReadFromObjDesc(uint objectId, IntPtr objDescPtr)
{
if (objDescPtr == IntPtr.Zero) return;
try
{
byte* p = (byte*)objDescPtr;
int numSubs = *(int*)(p + 16);
if (numSubs <= 0 || numSubs > 128) return;
var list = new (uint SubId, uint Offset)[numSubs];
IntPtr node = *(IntPtr*)(p + 8);
int idx = 0;
while (node != IntPtr.Zero && idx < numSubs)
{
byte* s = (byte*)node;
list[idx++] = (*(uint*)(s + 4), *(uint*)(s + 8));
node = *(IntPtr*)(s + 20);
}
if (idx != numSubs)
Array.Resize(ref list, idx);
Array.Sort(list, (a, b) => a.Offset.CompareTo(b.Offset));
lock (_lock)
_data[objectId] = list;
}
catch { }
}
public static void Remove(uint objectId)
{
lock (_lock)
_data.Remove(objectId);
}
public static int Fill(uint objectId, uint* subIds, uint* offsets, int maxCount)
{
(uint SubId, uint Offset)[]? list;
lock (_lock)
{
if (!_data.TryGetValue(objectId, out list)) return -1;
}
int count = Math.Min(list.Length, maxCount);
for (int i = 0; i < count; i++)
{
subIds[i] = list[i].SubId;
offsets[i] = list[i].Offset;
}
return list.Length;
}
}

View file

@ -0,0 +1,109 @@
using System;
namespace RynthCore.Engine.Compatibility;
internal static class PatternScanner
{
public static int FindPattern(byte[] data, byte[] pattern)
{
return FindPatternInRegion(data, pattern, 0, data.Length);
}
public static int FindPattern(byte[] data, byte?[] pattern)
{
return FindPatternInRegion(data, pattern, 0, data.Length);
}
public static int FindPatternInRegion(byte[] data, byte[] pattern, int start, int end)
{
int limit = Math.Min(end, data.Length) - pattern.Length;
for (int i = Math.Max(0, start); i <= limit; i++)
{
bool match = true;
for (int j = 0; j < pattern.Length; j++)
{
if (data[i + j] == pattern[j])
continue;
match = false;
break;
}
if (match)
return i;
}
return -1;
}
public static int FindPatternInRegion(byte[] data, byte?[] pattern, int start, int end)
{
int limit = Math.Min(end, data.Length) - pattern.Length;
for (int i = Math.Max(0, start); i <= limit; i++)
{
bool match = true;
for (int j = 0; j < pattern.Length; j++)
{
byte? expected = pattern[j];
if (expected.HasValue && data[i + j] != expected.Value)
{
match = false;
break;
}
}
if (match)
return i;
}
return -1;
}
public static int FindPrologueBefore(byte[] data, int opcodeOffset, byte[] prologue, int maxDistance = 300)
{
for (int back = 1; back < maxDistance; back++)
{
int pos = opcodeOffset - back;
if (pos < 1 || pos + prologue.Length > data.Length)
continue;
if (!VerifyBytes(data, pos, prologue))
continue;
byte prev = data[pos - 1];
if (prev == 0xCC || prev == 0x90 || prev == 0xC3)
return pos;
}
return -1;
}
public static bool VerifyBytes(byte[] data, int offset, byte[] expected)
{
if (offset < 0 || offset + expected.Length > data.Length)
return false;
for (int i = 0; i < expected.Length; i++)
{
if (data[offset + i] != expected[i])
return false;
}
return true;
}
public static bool VerifyPattern(byte[] data, int offset, byte?[] expected)
{
if (offset < 0 || offset + expected.Length > data.Length)
return false;
for (int i = 0; i < expected.Length; i++)
{
byte? value = expected[i];
if (value.HasValue && data[offset + i] != value.Value)
return false;
}
return true;
}
}

View file

@ -0,0 +1,535 @@
using System;
using System.Runtime.InteropServices;
namespace RynthCore.Engine.Compatibility;
internal static class PlayerPhysicsHooks
{
private const int PhysicsPositionOffset = 0x48;
private const int PositionObjCellIdOffset = 0x04;
private const int PositionQwOffset = 0x08;
private const int PositionQxOffset = 0x0C;
private const int PositionQyOffset = 0x10;
private const int PositionQzOffset = 0x14;
private const int PositionOriginXOffset = 0x3C;
private const int PositionOriginYOffset = 0x40;
private const int PositionOriginZOffset = 0x44;
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 +0x80 = head of the sequenced/one-shot motion node list
// (singly-linked, head=+0x80 / tail=+0x84; nodes popped+heap-freed as each
// motion completes — confirmed via offline RE of acclient.exe: ctor 0x529810
// zeroes it, pop sites 0x528AD0/0x528B40, stop-all 0x528A50). A spell-cast
// wind-up/release gesture is queued here while it animates and the list
// empties when it finishes. Locomotion uses the +0x4C/+0x54 channels
// directly and does NOT enqueue here, so a non-empty list is a clean
// "an action gesture is in progress" signal. We read ONLY the head pointer
// value and never dereference it, so this is safe against AC freeing nodes
// on its own thread.
private const int CMotionPendingMotionsHeadOffset = 0x80;
// 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;
public static bool HasSetHeading => _setHeading != null;
public static string StatusMessage => _statusMessage;
public static bool Probe()
{
bool ready = SmartBoxLocator.Probe();
IsInitialized = ready;
_statusMessage = ready ? "Ready." : SmartBoxLocator.StatusMessage;
if (ready)
{
BindPhysicsDelegates();
RynthLog.Verbose($"Compat: player physics ready - smartbox candidates={SmartBoxLocator.CandidateCount}");
}
return ready;
}
public static bool TryGetPlayerPose(
out uint objCellId,
out float x,
out float y,
out float z,
out float qw,
out float qx,
out float qy,
out float qz)
{
objCellId = 0;
x = y = z = 0;
qw = 1f;
qx = qy = qz = 0;
if (!SmartBoxLocator.TryGetPlayer(out IntPtr player, out _, out string failure))
{
_statusMessage = failure;
return false;
}
try
{
// Deep-audit finding #3/#14/#15 pattern (2026-06-18): this is called
// off-thread (plugin/UI, e.g. RynthVision's InspectTerrain from the
// Avalonia UI thread) as well as from the main-thread render path, so
// a torn/freed player pointer must fail closed instead of risking an
// uncatchable NativeAOT AV. Probe every dereference with
// IsReadablePointer before reading it; try/catch alone is not enough.
IntPtr pos = player + PhysicsPositionOffset;
if (!ClientObjectHooks.IsReadablePointer(pos + PositionObjCellIdOffset) ||
!ClientObjectHooks.IsReadablePointer(pos + PositionQwOffset) ||
!ClientObjectHooks.IsReadablePointer(pos + PositionQxOffset) ||
!ClientObjectHooks.IsReadablePointer(pos + PositionQyOffset) ||
!ClientObjectHooks.IsReadablePointer(pos + PositionQzOffset) ||
!ClientObjectHooks.IsReadablePointer(pos + PositionOriginXOffset) ||
!ClientObjectHooks.IsReadablePointer(pos + PositionOriginYOffset) ||
!ClientObjectHooks.IsReadablePointer(pos + PositionOriginZOffset))
{
_statusMessage = "Player position struct not readable.";
return false;
}
objCellId = unchecked((uint)Marshal.ReadInt32(pos + PositionObjCellIdOffset));
qw = ReadFloat(pos + PositionQwOffset);
qx = ReadFloat(pos + PositionQxOffset);
qy = ReadFloat(pos + PositionQyOffset);
qz = ReadFloat(pos + PositionQzOffset);
x = ReadFloat(pos + PositionOriginXOffset);
y = ReadFloat(pos + PositionOriginYOffset);
z = ReadFloat(pos + PositionOriginZOffset);
IsInitialized = true;
_statusMessage = "Ready.";
return true;
}
catch (Exception ex)
{
_statusMessage = ex.Message;
return false;
}
}
public static bool TryGetPlayerHeading(out float headingDegrees)
{
headingDegrees = 0;
if (!EnsurePhysicsDelegates())
return false;
if (!SmartBoxLocator.TryGetPlayer(out IntPtr player, out _, out string failure))
{
_statusMessage = failure;
return false;
}
try
{
headingDegrees = NormalizeDecalHeading(_getHeading!(player));
IsInitialized = true;
_statusMessage = "Ready.";
return true;
}
catch (Exception ex)
{
_statusMessage = ex.Message;
return false;
}
}
public static bool SetPlayerHeading(float headingDegrees)
{
if (!EnsurePhysicsDelegates() || _setHeading == null)
return false;
if (!SmartBoxLocator.TryGetPlayer(out IntPtr player, out _, out string failure))
{
_statusMessage = failure;
return false;
}
try
{
_setHeading(player, NormalizePhysicsHeading(headingDegrees), 1);
IsInitialized = true;
_statusMessage = "Ready.";
return true;
}
catch (Exception ex)
{
_statusMessage = ex.Message;
return false;
}
}
/// <summary>
/// Sets the player heading by directly writing the orientation quaternion
/// in the player's CPhysicsObj position struct. This is an instant snap —
/// equivalent to old Decal <c>Actions.Heading = value</c>.
///
/// Uses the same SmartBox memory offsets we read from in TryGetPlayerPose,
/// so it's reliable whenever pose reads work. Does not depend on any
/// hardcoded function VAs.
/// </summary>
private static int _setHeadingCalls;
private static bool ShouldLogHeading(int n) => n <= 3 || (n & 0xF) == 0;
public static bool SetPlayerHeadingDirect(float decalHeadingDeg)
{
int n = System.Threading.Interlocked.Increment(ref _setHeadingCalls);
if (!SmartBoxLocator.TryGetPlayer(out IntPtr player, out _, out string failure))
{
_statusMessage = failure;
if (ShouldLogHeading(n))
RynthLog.Compat($"Move: SetPlayerHeadingDirect({decalHeadingDeg:0.0}) #{n} — no player: {failure}");
return false;
}
try
{
// Convert Decal heading (0°=N, clockwise) to physics yaw (0°=N, counter-clockwise)
double physYawDeg = -decalHeadingDeg;
double physYawRad = physYawDeg * (Math.PI / 180.0);
// Yaw-only quaternion: q = (cos(yaw/2), 0, 0, sin(yaw/2))
float newQw = (float)Math.Cos(physYawRad * 0.5);
float newQz = (float)Math.Sin(physYawRad * 0.5);
IntPtr pos = player + PhysicsPositionOffset;
WriteFloat(pos + PositionQwOffset, newQw);
WriteFloat(pos + PositionQzOffset, newQz);
IsInitialized = true;
_statusMessage = "Ready.";
if (ShouldLogHeading(n))
RynthLog.Compat($"Move: SetPlayerHeadingDirect({decalHeadingDeg:0.0}) #{n} -> qw={newQw:0.000} qz={newQz:0.000} (player=0x{player.ToInt32():X8})");
return true;
}
catch (Exception ex)
{
_statusMessage = ex.Message;
if (ShouldLogHeading(n))
RynthLog.Compat($"Move: SetPlayerHeadingDirect({decalHeadingDeg:0.0}) #{n} threw {ex.GetType().Name}: {ex.Message}");
return false;
}
}
public static bool HasLaunchJumpWithMotion => SmartBoxLocator.IsPointerInModule(new(ReferenceGetMaxSpeed));
/// <summary>
/// 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.
/// </summary>
public static bool LaunchJumpWithMotion(bool shift, bool holdW, bool holdX, bool holdZ, bool holdC)
{
// Deep-audit finding #2 (2026-06-18): this Marshal.WriteInt32's
// directly into CMotionInterp's forward/strafe/turn fields with NO
// thread gate at all — worse than the CommandInterpreterHooks jump
// trio (which at least goes through a thiscall try/catch), since a
// raw write racing AC's own motion-graph tick is a guaranteed torn
// write, not just an AV risk. Reachable off-thread via Jumper.cs's
// ReleaseJump on the Decal-coexistence pump thread.
if (!MainThreadGuard.IsOnMainThread())
return AcMainThreadQueue.EnqueueLaunchJumpWithMotion(shift, holdW, holdX, holdZ, 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;
}
}
/// <summary>
/// AC's local cast gate. True when CMotionInterp has a sequenced/one-shot
/// motion queued — i.e. a spell-cast (or other action) gesture is currently
/// animating. Empty queue = idle/ready. Returns the read success (false when
/// the player/CMotionInterp isn't reachable yet — pre-login / between
/// worlds); callers should treat "couldn't read" as "no opinion" and fall
/// back to their own throttle. Reads only the list-head pointer value and
/// never walks it, so it cannot fault on nodes AC frees concurrently.
/// </summary>
public static bool TryGetCastGestureInProgress(out bool inProgress)
{
inProgress = false;
if (!TryGetCMotionInterp(out IntPtr cmi) || cmi == IntPtr.Zero)
return false;
try
{
IntPtr head = Marshal.ReadIntPtr(cmi + CMotionPendingMotionsHeadOffset);
inProgress = head != IntPtr.Zero;
return true;
}
catch
{
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)
{
_getMaxSpeed = ResolveBind<GetMaxSpeedDelegate>("PlayerPhysics.GetMaxSpeed", PatGetMaxSpeed, ReferenceGetMaxSpeed);
if (_getMaxSpeed == null)
return false;
}
try
{
maxSpeed = _getMaxSpeed(cmotionInterp);
return true;
}
catch
{
return false;
}
}
private static void WriteFloat(IntPtr address, float value)
{
Marshal.WriteInt32(address, BitConverter.SingleToInt32Bits(value));
}
private static float ReadFloat(IntPtr address)
{
int bits = Marshal.ReadInt32(address);
return BitConverter.Int32BitsToSingle(bits);
}
// CPhysicsObj heading is rotated 90 degrees from the Decal/VTank basis
// used by old RynthAi Actions.Heading. Normalize here so plugins can stay
// on the original T1 heading math.
private static float NormalizeDecalHeading(float physicsHeading)
{
return NormalizeDegrees(90f - physicsHeading);
}
private static float NormalizePhysicsHeading(float decalHeading)
{
return NormalizeDegrees(90f - decalHeading);
}
private static float NormalizeDegrees(float heading)
{
while (heading < 0f)
heading += 360f;
while (heading >= 360f)
heading -= 360f;
return heading;
}
/// <summary>
/// Computes live NS/EW coordinates from the player's physics pose
/// (objCellId + local x,y) using the classic in-game coordinate basis.
/// This keeps steering and overlays on the same source of truth and
/// avoids stale cached coordinate reads while running.
/// </summary>
public static bool TryGetLiveCoords(out double northSouth, out double eastWest)
{
northSouth = 0;
eastWest = 0;
if (!TryGetPlayerPose(out uint objCellId, out float x, out float y, out _, out _, out _, out _, out _))
return false;
int lbX = (int)((objCellId >> 24) & 0xFF);
int lbY = (int)((objCellId >> 16) & 0xFF);
// Match the classic radar/coordinates basis exactly:
// EW = ((Landcell >> 24) * 8 + X / 24 - 1019.5) / 10
// NS = (((Landcell >> 16) & 0xFF) * 8 + Y / 24 - 1019.5) / 10
eastWest = (lbX * 8.0 + x / 24.0 - 1019.5) / 10.0;
northSouth = (lbY * 8.0 + y / 24.0 - 1019.5) / 10.0;
return true;
}
private static bool EnsurePhysicsDelegates()
{
if (_getHeading != null && _setHeading != null)
return true;
if (!SmartBoxLocator.Probe())
{
_statusMessage = SmartBoxLocator.StatusMessage;
return false;
}
return BindPhysicsDelegates();
}
// ── Pattern-resolved binding (1a hardening, 2026-06-05) ──────────────
// *Va consts above are FALLBACKs; these signatures (verified unique + landing at the VA
// offline via tools/pe_pattern.py) are the source of truth. GetHeading is a tail-call
// thunk (add ecx,0x50; jmp impl) — 4 bytes suffice for uniqueness. null = wildcard.
private static readonly byte?[] PatGetHeading = [ 0x83, 0xC1, 0x50, 0xE9 ];
private static readonly byte?[] PatSetHeading = [ 0x83, 0xEC, 0x40, 0x56, 0x8B, 0xF1, 0x8D, 0x46 ];
private static readonly byte?[] PatGetMaxSpeed = [ 0x51, 0x56, 0x8B, 0xF1, 0x8B, 0x4E, 0x04, 0x85, 0xC9, 0xC7 ];
private static T? ResolveBind<T>(string name, byte?[] pattern, int fallbackVa) where T : Delegate
{
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
return null;
HookResolver.ResolveResult r = HookResolver.Resolve(text, name, pattern, fallbackVa);
return r.Success ? Marshal.GetDelegateForFunctionPointer<T>(r.Address) : null;
}
private static bool BindPhysicsDelegates()
{
if (_getHeading != null && _setHeading != null)
return true;
_getHeading = ResolveBind<PhysicsGetHeadingDelegate>("PlayerPhysics.GetHeading", PatGetHeading, ReferencePhysicsGetHeading);
_setHeading = ResolveBind<PhysicsSetHeadingDelegate>("PlayerPhysics.SetHeading", PatSetHeading, ReferencePhysicsSetHeading);
if (_getHeading == null || _setHeading == null)
{
_getHeading = null;
_setHeading = null;
_statusMessage = "Physics heading addresses failed to resolve.";
RynthLog.Compat($"Compat: player physics heading bind failed - {_statusMessage}");
return false;
}
RynthLog.Verbose("Compat: player heading hooks ready (pattern-resolved).");
return true;
}
}

View file

@ -0,0 +1,766 @@
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.Engine.Hooking;
namespace RynthCore.Engine.Compatibility;
internal readonly record struct PlayerVitalsSnapshot(
uint Health,
uint MaxHealth,
uint Stamina,
uint MaxStamina,
uint Mana,
uint MaxMana);
internal static class PlayerVitalsHooks
{
/// <summary>
/// The player's CACQualities* (== PlayerDesc*), set when SendNoticePlayerDescReceived fires.
/// Used by EnchantmentHooks to filter UpdateEnchantment/RemoveEnchantment to the player only.
/// </summary>
internal static IntPtr KnownPlayerQualitiesPtr { get; private set; }
/// <summary>
/// Allows other internal hooks to populate the qualities ptr when discovered
/// via an alternative path (e.g. mid-session injection before the login hook fires).
/// </summary>
internal static void SetKnownPlayerQualitiesPtr(IntPtr ptr)
{
if (ptr != IntPtr.Zero)
KnownPlayerQualitiesPtr = ptr;
}
/// <summary>
/// Drops the cached qualities ptr on logout so the next buffed-max inq
/// call can't dereference a freed allocation. Called by PluginManager's
/// logout dispatch.
/// </summary>
internal static void ResetSession()
{
KnownPlayerQualitiesPtr = IntPtr.Zero;
// Creature health is keyed by object id — ids don't survive the
// session, and without this clear the 1024-entry cap filled over a
// long session and every NEW creature was silently never tracked.
lock (_creatureHpLock)
_creatureHp.Clear();
ObjectQualityCache.ClearSession();
}
/// <summary>
/// Re-seed the qualities ptr and the vital snapshot from the live player object
/// without waiting for SendNoticePlayerDescReceived. Used by the engine's
/// hot-reload path: after a reload the new engine's static state is fresh,
/// so KnownPlayerQualitiesPtr starts at zero and AC won't fire the
/// notification again until the player relogs. Returns true if a non-zero
/// qualities ptr was found and applied.
/// </summary>
public static bool TryReseedFromCurrentPlayer()
{
if (!ClientObjectHooks.TryGetPlayerQualitiesPtr(out IntPtr qualitiesPtr) || qualitiesPtr == IntPtr.Zero)
return false;
KnownPlayerQualitiesPtr = qualitiesPtr;
ClientObjectHooks.SetKnownPlayerQualitiesPtr(qualitiesPtr);
try
{
// Struct path first — gives us current health/stamina/mana plus
// a baseline max (treated as a floor, not the truth).
SeedSnapshotFromQualities(qualitiesPtr);
}
catch (Exception ex)
{
RynthLog.Compat($"PlayerVitalsHooks: TryReseedFromCurrentPlayer struct seed threw {ex.GetType().Name}: {ex.Message}");
}
try
{
// Buffed-uint path — what AC actually shows on the vital bars.
// This OVERRIDES the max values from the struct path.
ReseedBuffedMaxFromQualities(qualitiesPtr);
}
catch (Exception ex)
{
RynthLog.Compat($"PlayerVitalsHooks: TryReseedFromCurrentPlayer buffed-max threw {ex.GetType().Name}: {ex.Message}");
}
return true;
}
private static unsafe void ReseedBuffedMaxFromQualities(IntPtr qualitiesPtr)
{
if (qualitiesPtr == IntPtr.Zero || _inqAttribute2ndUint == null)
return;
if (!TryInqUint(qualitiesPtr, MaxHealthType, out uint maxHealth) ||
!TryInqUint(qualitiesPtr, MaxStaminaType, out uint maxStamina) ||
!TryInqUint(qualitiesPtr, MaxManaType, out uint maxMana))
{
return;
}
bool changed = false;
lock (CacheLock)
{
PlayerVitalsSnapshot current = _snapshot;
PlayerVitalsSnapshot updated = current with
{
MaxHealth = maxHealth != 0 ? maxHealth : current.MaxHealth,
MaxStamina = maxStamina != 0 ? maxStamina : current.MaxStamina,
MaxMana = maxMana != 0 ? maxMana : current.MaxMana,
};
if (!EqualityComparer<PlayerVitalsSnapshot>.Default.Equals(current, updated))
{
_snapshot = updated;
changed = true;
}
}
if (changed)
RynthLog.Compat($"Compat: player vitals buffed-max re-seed hp_max={maxHealth} st_max={maxStamina} mn_max={maxMana}");
}
private static unsafe bool TryInqUint(IntPtr qualitiesPtr, uint stype, out uint value)
{
value = 0;
try
{
uint result = 0;
// raw=0 → buffed effective (the same number AC renders on the bars).
int rc = _inqAttribute2ndUint!(qualitiesPtr, stype, &result, 0);
if (rc == 0) return false;
value = result;
return true;
}
catch
{
return false;
}
}
private const int UpdateAttribute2ndVa = 0x00559900;
private const int UpdateAttribute2ndLevelVa = 0x00559920;
private const int PrivateUpdateAttribute2ndVa = 0x00559B20;
private const int PrivateUpdateAttribute2ndLevelVa = 0x00559B50;
private const int OnStatUpdatedIntVa = 0x0058ED50;
private const int InqAttribute2ndStructVa = 0x005927F0;
private const int SendNoticePlayerDescReceivedVa = 0x0047A200;
private const int MaxUpdateLogs = 18;
// ── Pattern-resolved binding (1a hardening, 2026-06-05) ─────────────
// *Va consts above are FALLBACKs; signatures verified unique + landing at the VA offline
// (tools/pe_pattern.py). The 4 Update*Attribute2nd thunks are near-identical templates
// differing only in their call target, so they use LITERAL patterns (trailing byte pins
// the rel32 low byte to stay unique); the rest are wildcarded (null = rel32 operand).
private static readonly byte?[] PatUpdateAttribute2nd = [ 0x8B, 0x44, 0x24, 0x10, 0x8B, 0x54, 0x24, 0x08, 0x50, 0x8B, 0x44, 0x24, 0x08, 0x52, 0x8B, 0x54, 0x24, 0x14, 0x50, 0x52, 0xE8, 0xA7 ];
private static readonly byte?[] PatUpdateAttribute2ndLevel = [ 0x8B, 0x44, 0x24, 0x10, 0x8B, 0x54, 0x24, 0x08, 0x50, 0x8B, 0x44, 0x24, 0x08, 0x52, 0x8B, 0x54, 0x24, 0x14, 0x50, 0x52, 0xE8, 0x07, 0xF1 ];
private static readonly byte?[] PatPrivateUpdateAttribute2nd = [ 0xA1, 0x58, 0xDA, 0x83, 0x00, 0x85, 0xC0, 0x74, 0x08, 0x8B, 0x80, 0xF4, 0x00, 0x00, 0x00, 0xEB, 0x02, 0x33, 0xC0, 0x8B, 0x54, 0x24, 0x0C, 0x52, 0x8B, 0x54, 0x24, 0x0C, 0x50, 0x8B, 0x44, 0x24, 0x0C, 0x50, 0x52, 0xE8, 0x78 ];
private static readonly byte?[] PatPrivateUpdateAttribute2ndLevel = [ 0xA1, 0x58, 0xDA, 0x83, 0x00, 0x85, 0xC0, 0x74, 0x08, 0x8B, 0x80, 0xF4, 0x00, 0x00, 0x00, 0xEB, 0x02, 0x33, 0xC0, 0x8B, 0x54, 0x24, 0x0C, 0x52, 0x8B, 0x54, 0x24, 0x0C, 0x50, 0x8B, 0x44, 0x24, 0x0C, 0x50, 0x52, 0xE8, 0xC8 ];
private static readonly byte?[] PatOnStatUpdatedInt = [ 0x8B, 0x44, 0x24, 0x04, 0x48, 0x3D, 0x97, 0x00 ];
private static readonly byte?[] PatInqAttribute2ndStruct = [ 0x8B, 0x49, 0x60, 0x85, 0xC9, 0x74, 0x13, 0x8B, 0x44, 0x24, 0x08, 0x8B, 0x54, 0x24, 0x04, 0x50, 0x52, 0xE8, null, null, null, null, 0x85, 0xC0, 0x75, 0x05, 0x33, 0xC0, 0xC2, 0x08, 0x00, 0xB8, 0x01, 0x00, 0x00, 0x00, 0xC2, 0x08, 0x00, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x68 ];
private static readonly byte?[] PatSendNoticePlayerDescReceived = [ 0xE8, null, null, null, null, 0x8B, 0x10, 0x68, 0xF0 ];
private static readonly byte?[] PatInqAttribute2ndUint = [ 0x51, 0x53, 0x55, 0x57, 0x8B, 0x7C, 0x24, 0x14 ];
private static IntPtr Resolve(AcClientTextSection text, string name, byte?[] pattern, int fallbackVa)
{
HookResolver.ResolveResult r = HookResolver.Resolve(text, name, pattern, fallbackVa);
return r.Success ? r.Address : IntPtr.Zero;
}
private const uint MaxHealthType = 1;
private const uint HealthType = 2;
private const uint MaxStaminaType = 3;
private const uint StaminaType = 4;
private const uint MaxManaType = 5;
private const uint ManaType = 6;
private static readonly object CacheLock = new();
private static IntPtr _originalUpdateAttribute2ndPtr;
private static IntPtr _originalUpdateAttribute2ndLevelPtr;
private static IntPtr _originalPrivateUpdateAttribute2ndPtr;
private static IntPtr _originalPrivateUpdateAttribute2ndLevelPtr;
private static IntPtr _originalOnStatUpdatedIntPtr;
private static IntPtr _originalSendNoticePlayerDescReceivedPtr;
private static string _statusMessage = "Not probed yet.";
private static int _updateLogCount;
private static int _seedLogCount;
private static PlayerVitalsSnapshot _snapshot;
private static InqAttribute2ndStructDelegate? _inqAttribute2ndStruct;
// Raw address of InqAttribute2nd(struct) — passed to the SEH trampoline so a
// monster's partial qualities table can be read without crashing on an AV.
private static IntPtr _inqAttribute2ndStructFnPtr;
public static bool IsInstalled { get; private set; }
public static string StatusMessage => _statusMessage;
public static void Initialize()
{
if (IsInstalled)
return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
{
_statusMessage = "acclient.exe not available.";
return;
}
try
{
IntPtr updateAttributePtr = Resolve(text, "PlayerVitals.UpdateAttribute2nd", PatUpdateAttribute2nd, UpdateAttribute2ndVa);
IntPtr updatePtr = Resolve(text, "PlayerVitals.UpdateAttribute2ndLevel", PatUpdateAttribute2ndLevel, UpdateAttribute2ndLevelVa);
IntPtr privateUpdateAttributePtr = Resolve(text, "PlayerVitals.PrivateUpdateAttribute2nd", PatPrivateUpdateAttribute2nd, PrivateUpdateAttribute2ndVa);
IntPtr privateUpdatePtr = Resolve(text, "PlayerVitals.PrivateUpdateAttribute2ndLevel", PatPrivateUpdateAttribute2ndLevel, PrivateUpdateAttribute2ndLevelVa);
IntPtr onStatUpdatedIntPtr = Resolve(text, "PlayerVitals.OnStatUpdatedInt", PatOnStatUpdatedInt, OnStatUpdatedIntVa);
IntPtr inqAttribute2ndStructPtr = Resolve(text, "PlayerVitals.InqAttribute2nd_struct", PatInqAttribute2ndStruct, InqAttribute2ndStructVa);
IntPtr sendNoticePlayerDescReceivedPtr = Resolve(text, "PlayerVitals.SendNotice_PlayerDescReceived", PatSendNoticePlayerDescReceived, SendNoticePlayerDescReceivedVa);
if (updateAttributePtr == IntPtr.Zero || updatePtr == IntPtr.Zero ||
privateUpdateAttributePtr == IntPtr.Zero || privateUpdatePtr == IntPtr.Zero ||
onStatUpdatedIntPtr == IntPtr.Zero || inqAttribute2ndStructPtr == IntPtr.Zero ||
sendNoticePlayerDescReceivedPtr == IntPtr.Zero)
{
_statusMessage = "One or more Attribute2nd handlers failed to resolve (pattern + fallback VA both missed).";
RynthLog.Compat($"Compat: player vitals hooks failed - {_statusMessage}");
return;
}
_inqAttribute2ndStruct = Marshal.GetDelegateForFunctionPointer<InqAttribute2ndStructDelegate>(inqAttribute2ndStructPtr);
_inqAttribute2ndStructFnPtr = inqAttribute2ndStructPtr;
// Buffed-uint overload — used by hot-reload re-seed and any path
// that needs the same number AC's vital bars render. The struct
// overload returns base values; this one returns buffed.
IntPtr inqAttribute2ndUintPtr = Resolve(text, "PlayerVitals.InqAttribute2nd_uint", PatInqAttribute2ndUint, InqAttribute2ndUintVa);
if (inqAttribute2ndUintPtr != IntPtr.Zero)
_inqAttribute2ndUint = Marshal.GetDelegateForFunctionPointer<InqAttribute2ndUintDelegate>(inqAttribute2ndUintPtr);
unsafe
{
delegate* unmanaged[Thiscall]<IntPtr, byte, uint, uint, SecondaryAttributeNative*, uint> updateAttributeDetour = &HandleUpdateAttribute2ndDetour;
delegate* unmanaged[Thiscall]<IntPtr, byte, uint, uint, int, uint> updateDetour = &HandleUpdateAttribute2ndLevelDetour;
delegate* unmanaged[Thiscall]<IntPtr, byte, uint, SecondaryAttributeNative*, uint> privateUpdateAttributeDetour = &HandlePrivateUpdateAttribute2ndDetour;
delegate* unmanaged[Thiscall]<IntPtr, byte, uint, int, uint> privateUpdateDetour = &HandlePrivateUpdateAttribute2ndLevelDetour;
delegate* unmanaged[Thiscall]<IntPtr, uint, int, void> onStatUpdatedIntDetour = &HandleOnStatUpdatedIntDetour;
delegate* unmanaged[Cdecl]<IntPtr, IntPtr, byte> sendNoticePlayerDescReceivedDetour = &HandleSendNoticePlayerDescReceivedDetour;
MinHook.Hook(updateAttributePtr, (IntPtr)updateAttributeDetour, out _originalUpdateAttribute2ndPtr);
MinHook.Hook(updatePtr, (IntPtr)updateDetour, out _originalUpdateAttribute2ndLevelPtr);
MinHook.Hook(privateUpdateAttributePtr, (IntPtr)privateUpdateAttributeDetour, out _originalPrivateUpdateAttribute2ndPtr);
MinHook.Hook(privateUpdatePtr, (IntPtr)privateUpdateDetour, out _originalPrivateUpdateAttribute2ndLevelPtr);
MinHook.Hook(onStatUpdatedIntPtr, (IntPtr)onStatUpdatedIntDetour, out _originalOnStatUpdatedIntPtr);
MinHook.Hook(sendNoticePlayerDescReceivedPtr, (IntPtr)sendNoticePlayerDescReceivedDetour, out _originalSendNoticePlayerDescReceivedPtr);
}
IsInstalled = true;
_statusMessage = "Hooks installed.";
RynthLog.Verbose($"Compat: player vitals hooks ready - update=0x{UpdateAttribute2ndVa:X8}, level=0x{UpdateAttribute2ndLevelVa:X8}, private=0x{PrivateUpdateAttribute2ndVa:X8}, privateLevel=0x{PrivateUpdateAttribute2ndLevelVa:X8}, stat=0x{OnStatUpdatedIntVa:X8}, playerDesc=0x{SendNoticePlayerDescReceivedVa:X8}");
}
catch (Exception ex)
{
_statusMessage = ex.Message;
RynthLog.Compat($"Compat: player vitals hooks failed - {ex.Message}");
}
}
/// <summary>
/// Reads MaxHealth from any CWeenieObject via InqAttribute2ndStruct.
/// Must be called from the game thread (detours, not render thread).
/// </summary>
public static unsafe bool TryReadObjectMaxHealth(IntPtr weeniePtr, out uint maxHealth)
{
maxHealth = 0;
if (_inqAttribute2ndStruct == null || weeniePtr == IntPtr.Zero)
return false;
SecondaryAttributeNative maxValue = default;
if (_inqAttribute2ndStruct(weeniePtr, MaxHealthType, &maxValue) != 0 && maxValue._currentLevel > 0)
{
maxHealth = maxValue._currentLevel;
return true;
}
return false;
}
/// <summary>
/// Read a creature's REAL MaxHealth from its qualities (2nd-level attribute
/// table) via InqAttribute2nd, routed through the SEH trampoline so a
/// partial/null MONSTER sub-table AVs into a safe failure instead of killing
/// the client. This is the appraisal-free path to a mob's true HP (appraisal
/// returns a 50 stub for mobs the char's Assess skill can't read). MAIN
/// THREAD ONLY — AC isn't thread-safe. Returns false if the trampoline is
/// unavailable, the read AVs, or the value is 0.
/// </summary>
public static unsafe bool TryReadCreatureMaxHealthSafe(IntPtr weeniePtr, out uint maxHealth)
{
maxHealth = 0;
if (weeniePtr == IntPtr.Zero || _inqAttribute2ndStructFnPtr == IntPtr.Zero)
return false;
if (!SehTrampoline.IsAvailable)
return false; // never call InqAttribute2nd unguarded on a non-player weenie
SecondaryAttributeNative result = default;
int rc = SehTrampoline.ThiscallIntUintPtr(
_inqAttribute2ndStructFnPtr, weeniePtr, MaxHealthType, &result, out bool avCaught);
if (avCaught || rc == 0 || result._currentLevel == 0)
return false;
maxHealth = result._currentLevel;
return true;
}
/// <summary>
/// Returns the unbuffed base maximum vitals (base training + gear + augmentations, no spell enchantments).
/// Uses _initLevel + _levelFromCp from InqAttribute2ndStruct on the current-vital stypes (2/4/6).
/// This formula is confirmed "unbuffed base max" by the TryReadSecondary fallback path.
/// Must be called after SendNoticePlayerDescReceived has fired (KnownPlayerQualitiesPtr set).
/// </summary>
public static unsafe bool TryGetPlayerBaseVitals(out uint baseMaxHp, out uint baseMaxStam, out uint baseMaxMana)
{
baseMaxHp = baseMaxStam = baseMaxMana = 0;
if (_inqAttribute2ndStruct == null)
return false;
IntPtr ptr = KnownPlayerQualitiesPtr;
if (ptr == IntPtr.Zero)
return false;
try
{
SecondaryAttributeNative v = default;
if (_inqAttribute2ndStruct(ptr, HealthType, &v) != 0)
baseMaxHp = v._initLevel + v._levelFromCp;
if (_inqAttribute2ndStruct(ptr, StaminaType, &v) != 0)
baseMaxStam = v._initLevel + v._levelFromCp;
if (_inqAttribute2ndStruct(ptr, ManaType, &v) != 0)
baseMaxMana = v._initLevel + v._levelFromCp;
return baseMaxHp > 0 || baseMaxStam > 0 || baseMaxMana > 0;
}
catch
{
return false;
}
}
public static bool TryGetSnapshot(out PlayerVitalsSnapshot snapshot)
{
lock (CacheLock)
{
snapshot = _snapshot;
return snapshot.Health > 0 || snapshot.MaxHealth > 0 ||
snapshot.Stamina > 0 || snapshot.MaxStamina > 0 ||
snapshot.Mana > 0 || snapshot.MaxMana > 0;
}
}
/// <summary>
/// Called when the player's own IdentifyObject (0xC9) response arrives,
/// providing exact max vitals from the CreatureProfile section.
/// </summary>
public static void SeedMaxVitalsFromIdentify(uint maxHealth, uint maxStamina, uint maxMana)
{
if (maxHealth == 0 && maxStamina == 0 && maxMana == 0)
return;
lock (CacheLock)
{
_snapshot = _snapshot with
{
MaxHealth = maxHealth > 0 ? maxHealth : _snapshot.MaxHealth,
MaxStamina = maxStamina > 0 ? maxStamina : _snapshot.MaxStamina,
MaxMana = maxMana > 0 ? maxMana : _snapshot.MaxMana
};
RynthLog.Verbose($"Compat: player max vitals from identify hp={maxHealth} st={maxStamina} mn={maxMana}");
}
}
/// <summary>
/// Called from QueryHealthResponseDetour when the player's own health ratio arrives.
/// Computes trueMax = currentHealth / ratio, giving an accurate max immediately
/// instead of waiting for regen to converge.
/// </summary>
public static void UpdateMaxFromHealthRatio(float healthRatio)
{
if (healthRatio <= 0f || healthRatio > 1f)
return;
lock (CacheLock)
{
if (_snapshot.Health == 0)
return;
uint derivedMax = (uint)Math.Round(_snapshot.Health / (double)healthRatio);
if (derivedMax > _snapshot.MaxHealth)
{
_snapshot = _snapshot with { MaxHealth = derivedMax };
RynthLog.Verbose($"Compat: player MaxHealth derived from ratio={healthRatio:0.000} hp={_snapshot.Health} → max={derivedMax}");
}
}
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
private static unsafe uint HandleUpdateAttribute2ndDetour(IntPtr thisPtr, byte wts, uint sender, uint stype, SecondaryAttributeNative* val)
{
var original = (delegate* unmanaged[Thiscall]<IntPtr, byte, uint, uint, SecondaryAttributeNative*, uint>)_originalUpdateAttribute2ndPtr;
uint result = original(thisPtr, wts, sender, stype, val);
UpdateCacheFromAttribute(sender, stype, val, isPrivate: false);
return result;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
private static unsafe uint HandleUpdateAttribute2ndLevelDetour(IntPtr thisPtr, byte wts, uint sender, uint stype, int val)
{
var original = (delegate* unmanaged[Thiscall]<IntPtr, byte, uint, uint, int, uint>)_originalUpdateAttribute2ndLevelPtr;
uint result = original(thisPtr, wts, sender, stype, val);
UpdateCache(sender, stype, val, isPrivate: false);
ForwardCreatureHealth(sender, stype, val);
return result;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
private static unsafe uint HandlePrivateUpdateAttribute2ndDetour(IntPtr thisPtr, byte wts, uint stype, SecondaryAttributeNative* val)
{
var original = (delegate* unmanaged[Thiscall]<IntPtr, byte, uint, SecondaryAttributeNative*, uint>)_originalPrivateUpdateAttribute2ndPtr;
uint result = original(thisPtr, wts, stype, val);
UpdateCacheFromAttribute(0, stype, val, isPrivate: true);
return result;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
private static unsafe uint HandlePrivateUpdateAttribute2ndLevelDetour(IntPtr thisPtr, byte wts, uint stype, int val)
{
var original = (delegate* unmanaged[Thiscall]<IntPtr, byte, uint, int, uint>)_originalPrivateUpdateAttribute2ndLevelPtr;
uint result = original(thisPtr, wts, stype, val);
UpdateCache(0, stype, val, isPrivate: true);
return result;
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
private static unsafe void HandleOnStatUpdatedIntDetour(IntPtr thisPtr, uint stype, int val)
{
var original = (delegate* unmanaged[Thiscall]<IntPtr, uint, int, void>)_originalOnStatUpdatedIntPtr;
original(thisPtr, stype, val);
// (A per-object MaxHealth-by-pointer cache write used to live here —
// removed 2026-06-11: nothing ever read it, and it allocated on
// dictionary growth inside this UnmanagedCallersOnly detour.)
if (!SmartBoxLocator.TryGetPlayer(out IntPtr player, out uint playerId, out _))
return;
if (player == IntPtr.Zero || thisPtr != player)
return;
UpdateCache(playerId, stype, val, isPrivate: false);
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static unsafe byte HandleSendNoticePlayerDescReceivedDetour(IntPtr playerDescPtr, IntPtr playerModulePtr)
{
var original = (delegate* unmanaged[Cdecl]<IntPtr, IntPtr, byte>)_originalSendNoticePlayerDescReceivedPtr;
byte result = original(playerDescPtr, playerModulePtr);
SeedSnapshotFromQualities(playerDescPtr);
ClientObjectHooks.SetKnownPlayerQualitiesPtr(playerDescPtr);
KnownPlayerQualitiesPtr = playerDescPtr;
return result;
}
private static unsafe void UpdateCacheFromAttribute(uint sender, uint stype, SecondaryAttributeNative* val, bool isPrivate)
{
if (val == null)
return;
UpdateCache(sender, stype, unchecked((int)val->_currentLevel), isPrivate);
if (!isPrivate)
ForwardCreatureHealth(sender, stype, unchecked((int)val->_currentLevel));
// For max-vital types (MaxHealth=1, MaxStamina=3, MaxMana=5), _currentLevel is the
// effective buffed maximum — that's already handled by the UpdateCache call above.
//
// For current-vital types (Health=2, Stamina=4, Mana=6), do NOT derive max from
// _initLevel + _levelFromCp — that's the unbuffed base max and would overwrite the
// correct buffed value set by the seed or a direct MaxHealth update.
}
// Live monster (non-player) health, captured from the broadcast vital-update
// stream that UpdateCache discards. The server pushes a creature's current
// (stype=Health) and max (stype=MaxHealth) attribute levels here for combat
// mobs in awareness — NO appraisal needed (so it works on high-level mobs
// whose Assess skill we lack) and NO Inq* read (so no non-player-qualities AV).
// Pre-sized + capped so the per-creature add can't realloc inside this
// main-thread detour. Packed (current<<32 | max) to avoid per-entry alloc.
private static readonly Dictionary<uint, ulong> _creatureHp = new(1024);
private static readonly object _creatureHpLock = new();
private static int _creatureHpLogCount;
private static void ForwardCreatureHealth(uint sender, uint stype, int val)
{
if (sender == 0 || val < 0) return;
if (stype != HealthType && stype != MaxHealthType) return;
uint playerId = ClientHelperHooks.GetPlayerId();
if (playerId == 0 || sender == playerId) return; // player handled by UpdateCache
// Packed entry: bit 63 = "current seen", bit 62 = "max seen",
// bits 32-61 = current, bits 0-31 = max. Both halves must be observed
// before a ratio is forwarded — fabricating the missing half reported
// a near-dead mob as FULL (Health-only: max := cur → 1.0) or a fresh
// mob as DEAD (MaxHealth-only: cur = 0 → 0.0), corrupting plugin
// combat decisions.
const ulong SeenCur = 1UL << 63;
const ulong SeenMax = 1UL << 62;
const ulong CurMask = 0x3FFF_FFFFUL;
uint cur, max;
bool complete;
lock (_creatureHpLock)
{
// Bounded with self-healing: the old cap silently stopped tracking
// every NEW creature once 1024 distinct senders had been seen.
// Wholesale clear + reinsert is cheap and recovers within one
// server vital-burst per visible mob. (Also cleared at logout.)
if (_creatureHp.Count >= 1024 && !_creatureHp.ContainsKey(sender))
_creatureHp.Clear();
_creatureHp.TryGetValue(sender, out ulong packed);
cur = (uint)((packed >> 32) & CurMask);
max = (uint)packed;
if (stype == HealthType) { cur = (uint)val & (uint)CurMask; packed |= SeenCur; }
else { max = (uint)val; packed |= SeenMax; }
if (cur > max && (packed & SeenMax) != 0) max = cur; // server can momentarily push cur past a stale max
complete = (packed & SeenCur) != 0 && (packed & SeenMax) != 0;
_creatureHp[sender] = (packed & (SeenCur | SeenMax)) | ((ulong)cur << 32) | max;
}
if (_creatureHpLogCount < 40)
{
_creatureHpLogCount++;
RynthLog.Compat($"Compat: creature vital sender=0x{sender:X8} stype={stype} val={val} -> cur={cur} max={max} complete={complete}");
}
if (complete && max > 0)
Plugins.PluginManager.QueueUpdateHealth(sender, Math.Clamp((float)cur / max, 0f, 1f), cur, max);
}
private static void UpdateCache(uint sender, uint stype, int val, bool isPrivate)
{
uint playerId = ClientHelperHooks.GetPlayerId();
if (playerId == 0)
return;
if (!isPrivate && sender != playerId)
return;
if (val < 0)
return;
uint value = unchecked((uint)val);
bool changed = false;
lock (CacheLock)
{
PlayerVitalsSnapshot current = _snapshot;
PlayerVitalsSnapshot updated = stype switch
{
MaxHealthType => current with { MaxHealth = value },
HealthType => current with { Health = value },
MaxStaminaType => current with { MaxStamina = value },
StaminaType => current with { Stamina = value },
MaxManaType => current with { MaxMana = value },
ManaType => current with { Mana = value },
_ => current
};
// "Highest value seen" — if a current vital exceeds the stored max,
// bump the max. Over time this converges to the true maximum as the
// player regenerates.
if (stype == HealthType && updated.Health > updated.MaxHealth)
updated = updated with { MaxHealth = updated.Health };
if (stype == StaminaType && updated.Stamina > updated.MaxStamina)
updated = updated with { MaxStamina = updated.Stamina };
if (stype == ManaType && updated.Mana > updated.MaxMana)
updated = updated with { MaxMana = updated.Mana };
changed = !EqualityComparer<PlayerVitalsSnapshot>.Default.Equals(current, updated);
if (changed)
_snapshot = updated;
}
if (changed && _updateLogCount < 0)
{
_updateLogCount++;
string scope = isPrivate ? "private" : $"sender=0x{sender:X8}";
RynthLog.Verbose($"Compat: player vital update #{_updateLogCount} {scope} stype={stype} value={value}");
}
// Diagnostic: log every max-vital update so we can see whether the
// UpdateAttribute2nd hook is actually firing for stype 1/3/5 after a
// hot reload, vs being silenced. Cheap (only fires on max changes).
if (changed && (stype == MaxHealthType || stype == MaxStaminaType || stype == MaxManaType))
{
RynthLog.Compat($"PlayerVitals: max update stype={stype} value={value} private={isPrivate}");
}
// Refresh MaxHealth from the live buffed-uint inq. Runs from the
// detour context (game thread, AC just finished an event), so the
// nested-pointer derefs inside InqAttribute2nd are safe. Catches
// god-mode / enchantment-drop cases where the buffed effective max
// changes without a server-pushed UpdateAttribute2nd(MaxHealth) event.
TryRefreshLiveMaxVitals();
}
// Called from every UpdateCache() invocation so buff/vitae changes that don't
// generate an explicit UpdateAttribute2nd packet are still picked up promptly.
private static void TryRefreshLiveMaxVitals()
{
if (_inqAttribute2ndUint == null) return;
IntPtr qualities = KnownPlayerQualitiesPtr;
if (qualities == IntPtr.Zero) return;
if (!LoginLifecycleHooks.HasObservedLoginComplete) return;
if (!ClientObjectHooks.IsReadablePointer(qualities)) return;
TryInqUint(qualities, MaxHealthType, out uint liveHp);
TryInqUint(qualities, MaxStaminaType, out uint liveSt);
TryInqUint(qualities, MaxManaType, out uint liveMn);
lock (CacheLock)
{
PlayerVitalsSnapshot s = _snapshot;
if (liveHp != 0 && s.MaxHealth != liveHp) s = s with { MaxHealth = liveHp };
if (liveSt != 0 && s.MaxStamina != liveSt) s = s with { MaxStamina = liveSt };
if (liveMn != 0 && s.MaxMana != liveMn) s = s with { MaxMana = liveMn };
_snapshot = s;
}
}
private static unsafe void SeedSnapshotFromQualities(IntPtr playerDescPtr)
{
if (playerDescPtr == IntPtr.Zero || _inqAttribute2ndStruct == null)
return;
if (!TryReadSecondary(playerDescPtr, HealthType, out uint health, out uint maxHealth) &&
!TryReadSecondary(playerDescPtr, StaminaType, out uint stamina, out uint maxStamina) &&
!TryReadSecondary(playerDescPtr, ManaType, out uint mana, out uint maxMana))
{
return;
}
TryReadSecondary(playerDescPtr, HealthType, out health, out maxHealth);
TryReadSecondary(playerDescPtr, StaminaType, out stamina, out maxStamina);
TryReadSecondary(playerDescPtr, ManaType, out mana, out maxMana);
bool changed = false;
lock (CacheLock)
{
PlayerVitalsSnapshot current = _snapshot;
// Use "highest seen" for max vitals — seed values from InqAttribute2ndStruct
// return current health as max, so never overwrite a higher known max.
uint bestMaxHealth = maxHealth != 0 ? Math.Max(maxHealth, current.MaxHealth) : current.MaxHealth;
uint bestMaxStamina = maxStamina != 0 ? Math.Max(maxStamina, current.MaxStamina) : current.MaxStamina;
uint bestMaxMana = maxMana != 0 ? Math.Max(maxMana, current.MaxMana) : current.MaxMana;
// Also ensure current vital doesn't exceed max
if (health > bestMaxHealth) bestMaxHealth = health;
if (stamina > bestMaxStamina) bestMaxStamina = stamina;
if (mana > bestMaxMana) bestMaxMana = mana;
PlayerVitalsSnapshot updated = current with
{
Health = health != 0 ? health : current.Health,
MaxHealth = bestMaxHealth,
Stamina = stamina != 0 ? stamina : current.Stamina,
MaxStamina = bestMaxStamina,
Mana = mana != 0 ? mana : current.Mana,
MaxMana = bestMaxMana
};
changed = !EqualityComparer<PlayerVitalsSnapshot>.Default.Equals(current, updated);
if (changed)
_snapshot = updated;
}
if (changed && _seedLogCount < 1)
{
_seedLogCount++;
RynthLog.Verbose($"Compat: player vitals seeded from player desc #{_seedLogCount} hp={health}/{maxHealth} st={stamina}/{maxStamina} mn={mana}/{maxMana}");
}
}
private static unsafe bool TryReadSecondary(IntPtr playerDescPtr, uint stype, out uint current, out uint max)
{
current = 0;
max = 0;
if (_inqAttribute2ndStruct == null)
return false;
SecondaryAttributeNative value = default;
if (_inqAttribute2ndStruct(playerDescPtr, stype, &value) == 0)
return false;
current = value._currentLevel;
// Query the max-vital attribute type (e.g. MaxHealth=1 for Health=2) to get the
// buffed effective maximum via its _currentLevel. Fall back to the base formula
// (_initLevel + _levelFromCp) if the max-vital query fails or returns zero.
uint maxStype = ToMaxStatType(stype);
if (maxStype != stype)
{
SecondaryAttributeNative maxValue = default;
if (_inqAttribute2ndStruct(playerDescPtr, maxStype, &maxValue) != 0 && maxValue._currentLevel != 0)
{
max = maxValue._currentLevel;
return true;
}
}
max = value._initLevel + value._levelFromCp;
return current != 0 || max != 0;
}
private static uint ToMaxStatType(uint stype)
{
return stype switch
{
HealthType => MaxHealthType,
StaminaType => MaxStaminaType,
ManaType => MaxManaType,
_ => stype
};
}
[StructLayout(LayoutKind.Sequential)]
private struct AttributeNative
{
public IntPtr _packObj;
public uint _levelFromCp;
public uint _initLevel;
public uint _cpSpent;
}
[StructLayout(LayoutKind.Sequential)]
private struct SecondaryAttributeNative
{
public AttributeNative _attribute;
public uint _currentLevel;
public uint _levelFromCp => _attribute._levelFromCp;
public uint _initLevel => _attribute._initLevel;
}
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private unsafe delegate int InqAttribute2ndStructDelegate(IntPtr thisPtr, uint stype, SecondaryAttributeNative* retval);
/// <summary>
/// CACQualities::InqAttribute2nd uint overload at 0x00592D20.
/// raw=0 → returns buffed effective value (initLevel + levelFromCp +
/// endurance contribution + EnchantAttribute2nd buffs). raw=1 → unbuffed.
/// This is the function AC itself uses to render the vital bars.
/// </summary>
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private unsafe delegate int InqAttribute2ndUintDelegate(IntPtr thisPtr, uint stype, uint* retval, int raw);
private const int InqAttribute2ndUintVa = 0x00592D20;
private static InqAttribute2ndUintDelegate? _inqAttribute2ndUint;
}

View file

@ -0,0 +1,280 @@
// ============================================================================
// 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.
//
// All three target addresses are now resolved via HookResolver — pattern
// scan first, hardcoded VA fallback (logged as RISKY), or UNAVAILABLE.
// The recv-notice functions all share the +0x600/+0xFA08 ClientCombatSystem
// field offsets which are unique enough to anchor patterns against.
// ============================================================================
using System;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
namespace RynthCore.Engine.Compatibility;
internal static class PowerbarHooks
{
// Fallback VAs for the 4,841,472-byte client. Pattern-scan is now the
// source of truth; these are the safety net.
private const int GmPowerbarUIBeginFallbackVa = 0x004DB390;
private const int GmPowerbarUILevelFallbackVa = 0x004DB1B0;
private const int GmPowerbarUIFinishFallbackVa = 0x004DB1E0;
// gmPowerbarUI::RecvNotice_BeginPowerbar(PowerBarMode) — uses jump-table
// dispatch on the mode argument; the lea-decrement and ja-of-3 are unique.
private static readonly byte?[] BeginPattern =
[
0x83, 0xEC, 0x10, 0x55, 0x8B, 0x6C, 0x24, 0x18,
0x56, 0x8D, 0x45, 0xFF, 0x83, 0xF8, 0x03, 0x57,
0x8B, 0xF1, 0x0F, 0x87, 0xBC, 0x00, 0x00, 0x00,
0xFF, 0x24, 0x85, null, null, null, null // jmp [imm32 + eax*4] — table
];
// gmPowerbarUI::RecvNotice_SetPowerbarLevel(PowerBarMode,float)
// Compares first arg with [ecx+4] then dispatches via push 0x10000034
// (UI element ID) — unique pair.
private static readonly byte?[] LevelPattern =
[
0x8B, 0x44, 0x24, 0x04, 0x3B, 0x41, 0x04, 0x75,
0x23, 0x68, 0x34, 0x00, 0x00, 0x10, 0x81, 0xC1,
0x08, 0xFA, 0xFF, 0xFF,
0xE8, null, null, null, null, // call rel32
0x85, 0xC0, 0x74, 0x0F
];
// gmPowerbarUI::RecvNotice_FinishPowerbar(PowerBarMode)
// Same +0xFA08 anchor as Level, but with `75 33` instead of `75 23` and a
// C7 41 04 zero-write (clears m_active before re-arming with 0x10000034).
private static readonly byte?[] FinishPattern =
[
0x8B, 0x44, 0x24, 0x04, 0x3B, 0x41, 0x04, 0x75,
0x33, 0x56, 0x8D, 0xB1, 0x08, 0xFA, 0xFF, 0xFF,
0xC7, 0x41, 0x04, 0x00, 0x00, 0x00, 0x00, 0x68,
0x34, 0x00, 0x00, 0x10, 0x8B, 0xCE,
0xE8, null, null, null, null // call rel32
];
[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;
// UIElement::SetVisible(bool) — same address as ChatHooks/RadarHooks use.
private const int UIElementSetVisibleFallbackVa = 0x00462390;
private static readonly byte?[] UIElementSetVisiblePattern =
[
0x51, 0x53, 0x56, 0x57,
0x8B, 0x3D, null, null, null, null, // mov edi, ds:[imm32]
0x8B, 0xF1,
0xE8, null, null, null, null, // call rel32
0x8B, 0x9E, 0xA4, 0x00, 0x00, 0x00,
0x88, 0x44, 0x24, 0x0F
];
private static IntPtr _gmPowerbarUIInstance;
private static IntPtr _uiElementSetVisibleAddress;
private static bool _hookInstalled;
private static bool _isHiddenAsserted;
private static string _statusMessage = "Not initialized.";
public static bool IsInstalled => _hookInstalled;
public static string StatusMessage => _statusMessage;
/// <summary>
/// When true, <see cref="TickHide"/> calls UIElement::SetVisible(false) on
/// the captured powerbar singleton each frame, hiding the retail attack/
/// magic power bar. We do NOT skip the original Begin/Level/Finish notices
/// — that pattern leaves AC's powerbar state machine half-initialized
/// (Begin shows, but no Finish to hide it; or Finish without prior Begin),
/// destabilizes its UIElement, and the next UI traversal (e.g. PopOutPanel
/// undock) AVs on the corrupted state. Same fix the chat suppression uses.
/// NOTE: <c>_gmPowerbarUIInstance</c> is captured from the first notice the
/// powerbar dispatches, so SetVisible can only kick in after the player
/// has at least once initiated combat. After that, the suppression sticks.
/// </summary>
public static bool SuppressOriginalDraw;
public static void Initialize()
{
if (_hookInstalled)
return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
{
_statusMessage = "acclient.exe not available.";
return;
}
// Resolve UIElement::SetVisible (used by TickHide). Direct call site,
// not a hook, but treat through HookResolver so we get pattern-scan
// resilience same as the other hooked addresses.
var setVisible = HookResolver.Resolve(textSection, "PowerbarHooks.UIElement::SetVisible",
UIElementSetVisiblePattern, UIElementSetVisibleFallbackVa);
if (setVisible.Success) _uiElementSetVisibleAddress = setVisible.Address;
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($"PowerbarHooks: all three notices hooked.");
}
else
{
_statusMessage = $"Partial install — Begin={beginOk}, Level={levelOk}, Finish={finishOk}.";
RynthLog.Compat($"PowerbarHooks: {_statusMessage}");
}
}
private static bool TryInstallBeginHook(AcClientTextSection textSection)
{
var resolved = HookResolver.Resolve(textSection, "PowerbarHooks.Begin",
BeginPattern, GmPowerbarUIBeginFallbackVa);
if (!resolved.Success) return false;
try
{
_beginDetour = BeginDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_beginDetour);
_originalBegin = Marshal.GetDelegateForFunctionPointer<NoticeBeginDelegate>(
MinHook.HookCreate(resolved.Address, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(resolved.Address);
return true;
}
catch (Exception ex)
{
RynthLog.Compat($"PowerbarHooks: Begin hook install threw {ex.GetType().Name}: {ex.Message}");
return false;
}
}
private static bool TryInstallLevelHook(AcClientTextSection textSection)
{
var resolved = HookResolver.Resolve(textSection, "PowerbarHooks.Level",
LevelPattern, GmPowerbarUILevelFallbackVa);
if (!resolved.Success) return false;
try
{
_levelDetour = LevelDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_levelDetour);
_originalLevel = Marshal.GetDelegateForFunctionPointer<NoticeLevelDelegate>(
MinHook.HookCreate(resolved.Address, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(resolved.Address);
return true;
}
catch (Exception ex)
{
RynthLog.Compat($"PowerbarHooks: Level hook install threw {ex.GetType().Name}: {ex.Message}");
return false;
}
}
private static bool TryInstallFinishHook(AcClientTextSection textSection)
{
var resolved = HookResolver.Resolve(textSection, "PowerbarHooks.Finish",
FinishPattern, GmPowerbarUIFinishFallbackVa);
if (!resolved.Success) return false;
try
{
_finishDetour = FinishDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_finishDetour);
_originalFinish = Marshal.GetDelegateForFunctionPointer<NoticeFinishDelegate>(
MinHook.HookCreate(resolved.Address, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(resolved.Address);
return true;
}
catch (Exception ex)
{
RynthLog.Compat($"PowerbarHooks: Finish hook install threw {ex.GetType().Name}: {ex.Message}");
return false;
}
}
private static int _beginFires, _levelFires, _finishFires;
private static void BeginDetour(IntPtr thisPtr, int powerBarMode)
{
RecursionGuard.Tick("PowerbarHooks.Begin");
if (thisPtr != IntPtr.Zero) _gmPowerbarUIInstance = thisPtr;
if (++_beginFires <= 3)
RynthLog.Compat($"PowerbarHooks: Begin fired #{_beginFires} mode={powerBarMode} suppress={SuppressOriginalDraw}");
// Always call original — see SuppressOriginalDraw comment. TickHide
// hides via SetVisible(false) per frame.
try { _originalBegin!(thisPtr, powerBarMode); }
catch (Exception ex) { try { RynthLog.Compat($"PowerbarHooks: Begin original threw {ex.GetType().Name}: {ex.Message}"); } catch { } throw; }
}
private static void LevelDetour(IntPtr thisPtr, int powerBarMode, float level)
{
RecursionGuard.Tick("PowerbarHooks.Level");
if (thisPtr != IntPtr.Zero) _gmPowerbarUIInstance = thisPtr;
if (++_levelFires <= 3)
RynthLog.Compat($"PowerbarHooks: Level fired #{_levelFires} mode={powerBarMode} level={level:F2} suppress={SuppressOriginalDraw}");
try { _originalLevel!(thisPtr, powerBarMode, level); }
catch (Exception ex) { try { RynthLog.Compat($"PowerbarHooks: Level original threw {ex.GetType().Name}: {ex.Message}"); } catch { } throw; }
}
private static void FinishDetour(IntPtr thisPtr, int powerBarMode)
{
RecursionGuard.Tick("PowerbarHooks.Finish");
if (thisPtr != IntPtr.Zero) _gmPowerbarUIInstance = thisPtr;
if (++_finishFires <= 3)
RynthLog.Compat($"PowerbarHooks: Finish fired #{_finishFires} mode={powerBarMode} suppress={SuppressOriginalDraw}");
try { _originalFinish!(thisPtr, powerBarMode); }
catch (Exception ex) { try { RynthLog.Compat($"PowerbarHooks: Finish original threw {ex.GetType().Name}: {ex.Message}"); } catch { } throw; }
}
/// <summary>
/// Per-frame visibility assertion — currently a no-op.
///
/// Why: <c>gmPowerbarUI</c> doesn't appear to be a UIElement subclass with
/// the UIElement subobject at offset 0 (unlike gmMainChatUI and gmRadarUI).
/// Captured <c>_gmPowerbarUIInstance</c> is the gmPowerbarUI's `this`,
/// which has a different vtable layout. Passing it to UIElement::SetVisible
/// at 0x00462390 caused a NULL function-pointer dereference inside the
/// function (observed crash: "instruction at 0x00000000 referenced memory
/// at 0x00000000" on first combat engage after suppression toggled on).
///
/// Until we resolve the correct UIElement child to hide (likely a member
/// inside gmPowerbarUI at some offset), the suppression flag is wired but
/// has no visual effect. Powerbar remains visible. Detours still always
/// call AC's original notices, so AC's UI state is consistent and stable.
/// </summary>
public static void TickHide()
{
// Intentionally empty until we find the right UIElement to SetVisible on.
}
public static void ResetCachedInstance()
{
_gmPowerbarUIInstance = IntPtr.Zero;
_isHiddenAsserted = false;
}
}

View file

@ -0,0 +1,451 @@
using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using RynthCore.Engine.Hooking;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// MinHook detours on <c>kernel32!ExitProcess</c> and
/// <c>kernel32!TerminateProcess</c> — the two paths every process-shutdown
/// in Windows funnels through (managed FailFast, native AC self-exit on
/// disconnect, runtime AV-induced __fastfail, etc.).
///
/// Purpose: when the AC client dies silently — no popup, no engine VEH
/// banner, no FirstChanceException — neither managed nor SEH machinery
/// catches it. The only chance to see who killed the process is to
/// intercept the kill primitive itself. We capture a native stack
/// backtrace at detour entry, identify the calling module, log it, then
/// forward to the original (process still dies, but we know why).
///
/// Logged information per call:
/// - Function (ExitProcess vs TerminateProcess)
/// - Exit code
/// - Calling thread ID
/// - Top N native return addresses, each annotated with module + RVA
/// so we can pinpoint the exact instruction that decided to kill us.
/// </summary>
internal static class ProcessExitHooks
{
private const int CapturedFrames = 12;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate void ExitProcessDelegate(uint exitCode);
[UnmanagedFunctionPointer(CallingConvention.StdCall, SetLastError = true)]
private delegate bool TerminateProcessDelegate(IntPtr hProcess, uint exitCode);
// ntdll!RtlExitUserProcess(NTSTATUS) — the actual implementation that
// kernel32!ExitProcess wraps. Modern code (and NativeAOT runtime) can
// call this directly, bypassing kernel32.
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate void RtlExitUserProcessDelegate(uint exitStatus);
// ntdll!NtTerminateProcess(HANDLE, NTSTATUS) — the syscall stub. Anything
// that wants to bypass kernel32!TerminateProcess goes through here.
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate uint NtTerminateProcessDelegate(IntPtr processHandle, uint exitStatus);
// kernel32!RaiseFailFastException — what __fastfail() / abort() / FailFast
// route through. Doesn't take an exit code; takes EXCEPTION_RECORD + CONTEXT.
// We don't need the params, just the call-site capture.
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate void RaiseFailFastExceptionDelegate(IntPtr pExceptionRecord, IntPtr pContext, uint dwFlags);
// ntdll!RtlFailFast(NTSTATUS) — internally executes `int 0x29` (the
// __fastfail intrinsic). The kernel handles 0x29 directly and terminates
// the process WITHOUT re-entering user mode through ExitProcess /
// TerminateProcess / RaiseFailFastException. Hooking RtlFailFast itself
// is the only way to capture this path before the kernel takes over.
// Used by: stack-cookie failures (/GS), heap corruption checks, CRT
// abort paths on newer toolchains, NTDLL's own internal asserts.
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate void RtlFailFastDelegate(uint code);
// ntdll!RtlFailFast2(NTSTATUS, EXCEPTION_RECORD*) — newer variant that
// also passes an exception record. Same semantics: the kernel terminates
// the process via int 0x29 without revisiting user mode.
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate void RtlFailFast2Delegate(uint code, IntPtr pExceptionRecord);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr GetModuleHandleW(string? lpModuleName);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern ushort RtlCaptureStackBackTrace(
uint FramesToSkip, uint FramesToCapture, IntPtr[] BackTrace, out uint BackTraceHash);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetModuleHandleExW(uint dwFlags, IntPtr lpModuleName, out IntPtr phModule);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern uint GetModuleFileNameW(IntPtr hModule, [Out] char[] lpFilename, uint nSize);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern uint GetCurrentThreadId();
private const uint GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS = 0x00000004;
private const uint GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT = 0x00000002;
private static readonly uint ModuleFromAddrFlags =
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT;
private static ExitProcessDelegate? _exitDetour;
private static ExitProcessDelegate? _exitOriginal;
private static TerminateProcessDelegate? _terminateDetour;
private static TerminateProcessDelegate? _terminateOriginal;
private static RtlExitUserProcessDelegate? _rtlExitDetour;
private static RtlExitUserProcessDelegate? _rtlExitOriginal;
private static NtTerminateProcessDelegate? _ntTermDetour;
private static NtTerminateProcessDelegate? _ntTermOriginal;
private static RaiseFailFastExceptionDelegate? _failFastDetour;
private static RaiseFailFastExceptionDelegate? _failFastOriginal;
private static RtlFailFastDelegate? _rtlFailFastDetour;
private static RtlFailFastDelegate? _rtlFailFastOriginal;
private static RtlFailFast2Delegate? _rtlFailFast2Detour;
private static RtlFailFast2Delegate? _rtlFailFast2Original;
private static int _installed;
private static int _logged; // ensure we log at most once even if both fire
// Re-entrancy latch for the fail-fast family (RaiseFailFastException,
// RtlFailFast, RtlFailFast2). In the NativeAOT-inside-acclient environment
// a fail-fast does NOT terminate the way it does in a normal process: the
// runtime/AC exception machinery swallows or continues the fail-fast
// exception, so kernel32!RaiseFailFastException RETURNS instead of killing
// the process. Its caller then re-invokes it, hitting our MinHook again →
// detour re-enters → calls the original again → ~190K-deep recursion that
// exhausts the 8 MB stack and AVs in ntdll (the recursing code is this
// exit logger itself, so nothing downstream can ever log it). Latch is
// process-wide and never reset — a fail-fast is terminal by contract;
// there is no "recovery", we only need to die cleanly and once.
private static int _inFailFast;
/// <summary>
/// Terminate without any possibility of re-entering a ProcessExitHooks
/// detour. Each call target is a MinHook *trampoline* (relocated original
/// prologue + jump PAST our hook), so none of them route back through our
/// detours. Used to break the fail-fast bounce.
/// </summary>
private static void HardTerminateNoReentry(uint code)
{
try { _ntTermOriginal?.Invoke(new IntPtr(-1), code); } catch { }
try { _rtlExitOriginal?.Invoke(code); } catch { }
try { _exitOriginal?.Invoke(code); } catch { }
try { Environment.Exit(unchecked((int)code)); } catch { }
}
public static void Initialize()
{
if (Interlocked.CompareExchange(ref _installed, 1, 0) != 0)
return;
try
{
IntPtr kernel32 = GetModuleHandleW("kernel32.dll");
if (kernel32 == IntPtr.Zero)
{
RynthLog.Compat("ProcessExitHooks: kernel32 not found.");
return;
}
HookExport(kernel32, "ExitProcess", out IntPtr exitTarget);
if (exitTarget != IntPtr.Zero)
{
_exitDetour = ExitProcessDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_exitDetour);
IntPtr trampoline = MinHook.HookCreate(exitTarget, detourPtr);
_exitOriginal = Marshal.GetDelegateForFunctionPointer<ExitProcessDelegate>(trampoline);
Thread.MemoryBarrier();
MinHook.Enable(exitTarget);
RynthLog.Info($"ProcessExitHooks: hooked kernel32!ExitProcess @ 0x{exitTarget.ToInt32():X8}.");
}
HookExport(kernel32, "TerminateProcess", out IntPtr terminateTarget);
if (terminateTarget != IntPtr.Zero)
{
_terminateDetour = TerminateProcessDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_terminateDetour);
IntPtr trampoline = MinHook.HookCreate(terminateTarget, detourPtr);
_terminateOriginal = Marshal.GetDelegateForFunctionPointer<TerminateProcessDelegate>(trampoline);
Thread.MemoryBarrier();
MinHook.Enable(terminateTarget);
RynthLog.Info($"ProcessExitHooks: hooked kernel32!TerminateProcess @ 0x{terminateTarget.ToInt32():X8}.");
}
// ── DO NOT HOOK RaiseFailFastException (proven fatal 2026-05-16) ──
// Dump analysis of the every-few-minutes silent crash showed a
// 190K-deep stack overflow whose repeating frame pair is
// <ReverseOpenStaticDelegateStub>...RaiseFailFastExceptionDelegate
// ↔ RhpReversePInvokeAttachOrTrapThread2. The NativeAOT reverse-
// P/Invoke transition that enters a managed detour for this export
// itself re-triggers RaiseFailFastException, so the detour recurses
// through the transition shim BEFORE any managed code (incl. any
// re-entrancy guard) can run. Unfixable from the managed side — the
// only correct action is to not hook it. A real fail-fast then
// terminates cleanly (as designed) instead of our hook converting
// it into the guaranteed stack-overflow crash. Same applies to
// ntdll!RtlFailFast / RtlFailFast2 below. The other exit hooks
// (ExitProcess/TerminateProcess/RtlExitUserProcess/NtTerminate) are
// safe — exiting the process does not re-enter those from within
// the transition, and they log clean interceptions.
// ntdll-level hooks — catch paths that bypass kernel32 entirely.
IntPtr ntdll = GetModuleHandleW("ntdll.dll");
if (ntdll != IntPtr.Zero)
{
HookExport(ntdll, "RtlExitUserProcess", out IntPtr rtlExitTarget);
if (rtlExitTarget != IntPtr.Zero)
{
_rtlExitDetour = RtlExitUserProcessDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_rtlExitDetour);
IntPtr trampoline = MinHook.HookCreate(rtlExitTarget, detourPtr);
_rtlExitOriginal = Marshal.GetDelegateForFunctionPointer<RtlExitUserProcessDelegate>(trampoline);
Thread.MemoryBarrier();
MinHook.Enable(rtlExitTarget);
RynthLog.Info($"ProcessExitHooks: hooked ntdll!RtlExitUserProcess @ 0x{rtlExitTarget.ToInt32():X8}.");
}
HookExport(ntdll, "NtTerminateProcess", out IntPtr ntTermTarget);
if (ntTermTarget != IntPtr.Zero)
{
_ntTermDetour = NtTerminateProcessDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_ntTermDetour);
IntPtr trampoline = MinHook.HookCreate(ntTermTarget, detourPtr);
_ntTermOriginal = Marshal.GetDelegateForFunctionPointer<NtTerminateProcessDelegate>(trampoline);
Thread.MemoryBarrier();
MinHook.Enable(ntTermTarget);
RynthLog.Info($"ProcessExitHooks: hooked ntdll!NtTerminateProcess @ 0x{ntTermTarget.ToInt32():X8}.");
}
// RtlFailFast / RtlFailFast2 — NOT HOOKED. Same NativeAOT
// reverse-P/Invoke re-entry recursion as RaiseFailFastException
// (see the block above). Hooking these with a managed detour
// is the every-few-minutes crash. Leave them alone; a genuine
// fail-fast terminates cleanly. (On this Windows build the
// GetProcAddress for these also failed historically anyway.)
if (false && ntdll != IntPtr.Zero)
{
HookExport(ntdll, "RtlFailFast", out IntPtr rtlFailFastTarget);
if (rtlFailFastTarget != IntPtr.Zero)
{
_rtlFailFastDetour = RtlFailFastDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_rtlFailFastDetour);
IntPtr trampoline = MinHook.HookCreate(rtlFailFastTarget, detourPtr);
_rtlFailFastOriginal = Marshal.GetDelegateForFunctionPointer<RtlFailFastDelegate>(trampoline);
Thread.MemoryBarrier();
MinHook.Enable(rtlFailFastTarget);
RynthLog.Info($"ProcessExitHooks: hooked ntdll!RtlFailFast @ 0x{rtlFailFastTarget.ToInt32():X8}.");
}
HookExport(ntdll, "RtlFailFast2", out IntPtr rtlFailFast2Target);
if (rtlFailFast2Target != IntPtr.Zero)
{
_rtlFailFast2Detour = RtlFailFast2Detour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_rtlFailFast2Detour);
IntPtr trampoline = MinHook.HookCreate(rtlFailFast2Target, detourPtr);
_rtlFailFast2Original = Marshal.GetDelegateForFunctionPointer<RtlFailFast2Delegate>(trampoline);
Thread.MemoryBarrier();
MinHook.Enable(rtlFailFast2Target);
RynthLog.Info($"ProcessExitHooks: hooked ntdll!RtlFailFast2 @ 0x{rtlFailFast2Target.ToInt32():X8}.");
}
}
}
}
catch (Exception ex)
{
RynthLog.Compat($"ProcessExitHooks: install threw {ex.GetType().Name}: {ex.Message}");
}
}
private static void HookExport(IntPtr kernel32, string name, out IntPtr target)
{
target = GetProcAddress(kernel32, name);
if (target == IntPtr.Zero)
RynthLog.Compat($"ProcessExitHooks: GetProcAddress({name}) failed.");
}
private static void ExitProcessDetour(uint exitCode)
{
LogTermination("ExitProcess", IntPtr.Zero, exitCode);
// Run our orderly shutdown BEFORE AC's CRT atexit chain. Without this,
// hooks stay installed, our threads (TickPump, Avalonia STA) keep
// running, and AC's static-destructor LongHash teardown at 0x416B10
// races them on a hash chain → the popup AV at 0x00416C86.
try { EngineLifecycle.Shutdown(); }
catch (Exception ex) { RynthLog.Info($"ProcessExit: EngineLifecycle.Shutdown threw {ex.GetType().Name}: {ex.Message}"); }
try { _exitOriginal!(exitCode); }
catch { /* original never returns; swallow if it somehow does */ }
}
private static bool TerminateProcessDetour(IntPtr hProcess, uint exitCode)
{
// Only log when terminating ourselves — TerminateProcess on other
// process handles is a normal Process.Kill and not what we're hunting.
// hProcess == -1 (pseudo-handle for current process) or == GetCurrentProcess() handle.
bool selfKill = hProcess == new IntPtr(-1) || hProcess == GetCurrentProcessHandle();
if (selfKill)
LogTermination("TerminateProcess", hProcess, exitCode);
try { return _terminateOriginal!(hProcess, exitCode); }
catch { return false; }
}
[DllImport("kernel32.dll")]
private static extern IntPtr GetCurrentProcess();
private static IntPtr GetCurrentProcessHandle() => GetCurrentProcess();
private static void RtlExitUserProcessDetour(uint exitStatus)
{
LogTermination("RtlExitUserProcess", IntPtr.Zero, exitStatus);
try { EngineLifecycle.Shutdown(); }
catch (Exception ex) { RynthLog.Info($"ProcessExit: EngineLifecycle.Shutdown threw {ex.GetType().Name}: {ex.Message}"); }
try { _rtlExitOriginal!(exitStatus); }
catch { }
}
private static uint NtTerminateProcessDetour(IntPtr processHandle, uint exitStatus)
{
bool selfKill = processHandle == new IntPtr(-1) || processHandle == GetCurrentProcessHandle();
if (selfKill)
LogTermination("NtTerminateProcess", processHandle, exitStatus);
try { return _ntTermOriginal!(processHandle, exitStatus); }
catch { return 0xC0000001; /* STATUS_UNSUCCESSFUL */ }
}
private static void RaiseFailFastExceptionDetour(IntPtr pExceptionRecord, IntPtr pContext, uint dwFlags)
{
if (Interlocked.Exchange(ref _inFailFast, 1) != 0)
{
// Re-entered: the original bounced back through our hook instead
// of terminating. Forwarding again is the 190K-deep stack-overflow
// recursion. Break it — die now, non-recursively.
HardTerminateNoReentry(dwFlags);
return;
}
LogTermination("RaiseFailFastException", IntPtr.Zero, dwFlags);
try { _failFastOriginal!(pExceptionRecord, pContext, dwFlags); }
catch { }
// A real fail-fast never returns. In this environment it can — don't
// let the caller spin re-raising it; terminate deterministically.
HardTerminateNoReentry(dwFlags);
}
private static void RtlFailFastDetour(uint code)
{
if (Interlocked.Exchange(ref _inFailFast, 1) != 0)
{
HardTerminateNoReentry(code);
return;
}
LogTermination("RtlFailFast", IntPtr.Zero, code);
try { _rtlFailFastOriginal!(code); }
catch { /* original never returns */ }
HardTerminateNoReentry(code);
}
private static void RtlFailFast2Detour(uint code, IntPtr pExceptionRecord)
{
if (Interlocked.Exchange(ref _inFailFast, 1) != 0)
{
HardTerminateNoReentry(code);
return;
}
LogTermination("RtlFailFast2", IntPtr.Zero, code);
try { _rtlFailFast2Original!(code, pExceptionRecord); }
catch { /* original never returns */ }
HardTerminateNoReentry(code);
}
private static void LogTermination(string func, IntPtr hProcess, uint exitCode)
{
if (Interlocked.Exchange(ref _logged, 1) != 0)
return; // don't double-log if both ExitProcess + TerminateProcess fire
try
{
// Dump RynthCore->AC action trace BEFORE building the termination
// banner so the trace is in the log even if the banner build throws.
// Captures the last ~256 mutating calls — the "too many switches?"
// ring buffer for Class B AVs (AC UIElement faults, no RC stack).
AcActionTrace.DumpToLog();
var sb = new StringBuilder();
sb.AppendLine("==== PROCESS TERMINATION INTERCEPTED ====");
sb.AppendLine($" function: kernel32!{func}");
sb.AppendLine($" exit code: 0x{exitCode:X8} ({(int)exitCode})");
sb.AppendLine($" thread: {GetCurrentThreadId()} (managed name='{Thread.CurrentThread.Name ?? "<unnamed>"}', managed id={Thread.CurrentThread.ManagedThreadId})");
if (hProcess != IntPtr.Zero)
sb.AppendLine($" hProcess: 0x{hProcess.ToInt32():X8}");
var frames = new IntPtr[CapturedFrames];
// FramesToSkip=2 to step past this method + the detour wrapper.
ushort captured = RtlCaptureStackBackTrace(2, (uint)CapturedFrames, frames, out _);
sb.AppendLine($" native back-trace ({captured} frame(s)) — note: x86 EBP-walk, deep frames may be unreliable under FPO:");
for (int i = 0; i < captured; i++)
{
IntPtr addr = frames[i];
if (addr == IntPtr.Zero) break;
string module = ResolveModule(addr, out int rva);
sb.AppendLine($" [{i:00}] 0x{addr.ToInt32():X8} {module}+0x{rva:X}");
}
// Managed stack — the actually useful one. NativeAOT supports
// Environment.StackTrace; this gives us the C# call chain that
// led to ExitProcess being called from inside our engine.
sb.AppendLine(" managed stack (Environment.StackTrace):");
try
{
string mst = Environment.StackTrace ?? "<null>";
foreach (string raw in mst.Split('\n'))
{
string line = raw.TrimEnd('\r');
if (line.Length > 0) sb.AppendLine($" {line}");
}
}
catch (Exception stEx)
{
sb.AppendLine($" <stack capture failed: {stEx.GetType().Name}: {stEx.Message}>");
}
sb.Append("==========================================");
RynthLog.Info(sb.ToString());
}
catch
{
// Logging path must not throw — process is about to die anyway,
// and our detour MUST forward to the original so termination
// actually completes.
}
}
private static string ResolveModule(IntPtr address, out int rva)
{
rva = 0;
try
{
if (!GetModuleHandleExW(ModuleFromAddrFlags, address, out IntPtr hMod) || hMod == IntPtr.Zero)
return "<unknown>";
rva = (int)(address.ToInt64() - hMod.ToInt64());
char[] buf = new char[260];
uint n = GetModuleFileNameW(hMod, buf, (uint)buf.Length);
if (n == 0)
return $"<mod 0x{hMod.ToInt32():X8}>";
string full = new string(buf, 0, (int)n);
int slash = full.LastIndexOfAny(new[] { '\\', '/' });
return slash >= 0 ? full.Substring(slash + 1) : full;
}
catch
{
return "<resolve-failed>";
}
}
}

View file

@ -0,0 +1,335 @@
// ============================================================================
// RynthCore.Engine - Compatibility/PropertyUpdateHooks.cs
//
// Hooks CM_Qualities network message dispatchers to cache property updates
// broadcast by the server. This solves the problem where
// CBaseQualities::InqInt/InqBool fail for static world objects (doors, signs,
// etc.) because m_pQualities is null — those objects never get a qualities
// block allocated in client memory, but the server still sends property
// update messages that are processed and discarded.
//
// Hooked functions (all cdecl, from Chorizite CM.cs):
// CM_Qualities::DispatchUI_UpdateInt @ 0x006B0000
// CM_Qualities::DispatchUI_UpdateBool @ 0x006AFF00
// CM_Qualities::DispatchUI_PrivateUpdateInt @ 0x006AF960
// CM_Qualities::DispatchUI_PrivateUpdateBool@ 0x006AF880
//
// Eviction via:
// ECM_Physics::SendNotice_BeingDeleted @ 0x00693960
//
// Public message buffer layout:
// [0..3] sequence (uint)
// [4..7] objectGUID (uint)
// [8..11] stype (uint)
// [12..15] value (int / int-as-bool)
//
// Private message buffer layout (player implied):
// [0..3] sequence (uint)
// [4..7] stype (uint)
// [8..11] value (int / int-as-bool)
// ============================================================================
using System;
using System.Collections.Concurrent;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
namespace RynthCore.Engine.Compatibility;
internal static class PropertyUpdateHooks
{
// --- Hook target VAs ---
private const int DispatchUI_UpdateIntVa = 0x006B0000;
private const int DispatchUI_UpdateBoolVa = 0x006AFF00;
private const int DispatchUI_PrivateUpdateIntVa = 0x006AF960;
private const int DispatchUI_PrivateUpdateBoolVa= 0x006AF880;
private const int SendNotice_BeingDeletedVa = 0x00693960;
// CWeenieObject object ID offset (vfptr(4) + hash_next*(4) + id(4) = offset 8)
private const int WeenieIdOffset = 8;
// --- Delegate types ---
// CM_Qualities dispatch: uint __cdecl (UIQueueManager* ui, void* buf, uint size)
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate uint DispatchDelegate(IntPtr uiPtr, IntPtr bufPtr, uint size);
// ECM_Physics::SendNotice_BeingDeleted: byte __cdecl (CWeenieObject* obj)
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate byte BeingDeletedDelegate(IntPtr weenieObjPtr);
// --- Original function pointers (for call-through) ---
private static DispatchDelegate? _origUpdateInt;
private static DispatchDelegate? _origUpdateBool;
private static DispatchDelegate? _origPrivateUpdateInt;
private static DispatchDelegate? _origPrivateUpdateBool;
private static BeingDeletedDelegate? _origBeingDeleted;
// --- Prevent GC of detour delegates ---
private static DispatchDelegate? _detourUpdateInt;
private static DispatchDelegate? _detourUpdateBool;
private static DispatchDelegate? _detourPrivateUpdateInt;
private static DispatchDelegate? _detourPrivateUpdateBool;
private static BeingDeletedDelegate? _detourBeingDeleted;
private static bool _hookInstalled;
private static string _statusMessage = "Not initialized.";
private static int _hookCount; // how many of the 5 hooks succeeded
// --- Property caches ---
// guid → (stype → value)
private static readonly ConcurrentDictionary<uint, ConcurrentDictionary<uint, int>> _intCache = new();
private static readonly ConcurrentDictionary<uint, ConcurrentDictionary<uint, int>> _boolCache = new();
public static bool IsInstalled => _hookInstalled;
public static string StatusMessage => _statusMessage;
// --- Public query API ---
public static bool TryGetCachedIntProperty(uint objectId, uint stype, out int value)
{
value = 0;
if (_intCache.TryGetValue(objectId, out var props))
return props.TryGetValue(stype, out value);
return false;
}
public static bool TryGetCachedBoolProperty(uint objectId, uint stype, out bool value)
{
value = false;
if (_boolCache.TryGetValue(objectId, out var props))
{
if (props.TryGetValue(stype, out int raw))
{
value = raw != 0;
return true;
}
}
return false;
}
/// <summary>Evict all cached properties for an object (e.g. when it is destroyed).</summary>
public static void EvictObject(uint objectId)
{
_intCache.TryRemove(objectId, out _);
_boolCache.TryRemove(objectId, out _);
}
// --- Initialization ---
public static void Initialize()
{
if (_hookInstalled)
return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
{
_statusMessage = "acclient.exe not available.";
return;
}
_hookCount = 0;
TryInstallHook(textSection, DispatchUI_UpdateIntVa, "DispatchUI_UpdateInt",
_detourUpdateInt = DetourUpdateInt, out _origUpdateInt);
TryInstallHook(textSection, DispatchUI_UpdateBoolVa, "DispatchUI_UpdateBool",
_detourUpdateBool = DetourUpdateBool, out _origUpdateBool);
TryInstallHook(textSection, DispatchUI_PrivateUpdateIntVa, "DispatchUI_PrivateUpdateInt",
_detourPrivateUpdateInt = DetourPrivateUpdateInt, out _origPrivateUpdateInt);
TryInstallHook(textSection, DispatchUI_PrivateUpdateBoolVa, "DispatchUI_PrivateUpdateBool",
_detourPrivateUpdateBool = DetourPrivateUpdateBool, out _origPrivateUpdateBool);
TryInstallBeingDeletedHook(textSection);
_hookInstalled = _hookCount > 0;
_statusMessage = _hookInstalled
? $"{_hookCount}/5 hooks installed."
: "All hooks failed.";
RynthLog.Verbose($"Compat: property-update hooks — {_statusMessage}");
}
// --- Hook installation helpers ---
private static void TryInstallHook(AcClientTextSection textSection, int va, string name,
DispatchDelegate detour, out DispatchDelegate? original)
{
original = null;
try
{
int funcOff = va - textSection.TextBaseVa;
if (funcOff < 0 || funcOff >= textSection.Bytes.Length)
{
RynthLog.Compat($"Compat: {name} VA out of range @ 0x{va:X8}.");
return;
}
byte firstByte = textSection.Bytes[funcOff];
if (firstByte is 0x00 or 0xCC or 0xC3)
{
RynthLog.Compat($"Compat: {name} looks invalid @ 0x{va:X8} (opcode 0x{firstByte:X2}).");
return;
}
IntPtr target = new IntPtr(textSection.TextBaseVa + funcOff);
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(detour);
original = Marshal.GetDelegateForFunctionPointer<DispatchDelegate>(
MinHook.HookCreate(target, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(target);
_hookCount++;
RynthLog.Verbose($"Compat: {name} hooked @ 0x{target.ToInt32():X8}");
}
catch (Exception ex)
{
RynthLog.Compat($"Compat: {name} hook failed — {ex.Message}");
}
}
private static void TryInstallBeingDeletedHook(AcClientTextSection textSection)
{
try
{
int funcOff = SendNotice_BeingDeletedVa - textSection.TextBaseVa;
if (funcOff < 0 || funcOff >= textSection.Bytes.Length)
{
RynthLog.Compat($"Compat: BeingDeleted VA out of range @ 0x{SendNotice_BeingDeletedVa:X8}.");
return;
}
byte firstByte = textSection.Bytes[funcOff];
if (firstByte is 0x00 or 0xCC or 0xC3)
{
RynthLog.Compat($"Compat: BeingDeleted looks invalid @ 0x{SendNotice_BeingDeletedVa:X8} (opcode 0x{firstByte:X2}).");
return;
}
IntPtr target = new IntPtr(textSection.TextBaseVa + funcOff);
_detourBeingDeleted = DetourBeingDeleted;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_detourBeingDeleted);
_origBeingDeleted = Marshal.GetDelegateForFunctionPointer<BeingDeletedDelegate>(
MinHook.HookCreate(target, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(target);
_hookCount++;
RynthLog.Verbose($"Compat: BeingDeleted hooked @ 0x{target.ToInt32():X8}");
}
catch (Exception ex)
{
RynthLog.Compat($"Compat: BeingDeleted hook failed — {ex.Message}");
}
}
// --- Detour implementations ---
private static uint DetourUpdateInt(IntPtr uiPtr, IntPtr bufPtr, uint size)
{
try
{
// Public: seq(4) + guid(4) + stype(4) + value(4) = 16 bytes minimum
if (bufPtr != IntPtr.Zero && size >= 16)
{
uint guid = (uint)Marshal.ReadInt32(bufPtr + 4);
uint stype = (uint)Marshal.ReadInt32(bufPtr + 8);
int val = Marshal.ReadInt32(bufPtr + 12);
CacheInt(guid, stype, val);
}
}
catch { }
return _origUpdateInt!(uiPtr, bufPtr, size);
}
private static uint DetourUpdateBool(IntPtr uiPtr, IntPtr bufPtr, uint size)
{
try
{
// Public: seq(4) + guid(4) + stype(4) + value(4) = 16 bytes minimum
if (bufPtr != IntPtr.Zero && size >= 16)
{
uint guid = (uint)Marshal.ReadInt32(bufPtr + 4);
uint stype = (uint)Marshal.ReadInt32(bufPtr + 8);
int val = Marshal.ReadInt32(bufPtr + 12);
CacheBool(guid, stype, val);
}
}
catch { }
return _origUpdateBool!(uiPtr, bufPtr, size);
}
private static uint DetourPrivateUpdateInt(IntPtr uiPtr, IntPtr bufPtr, uint size)
{
try
{
// Private: seq(4) + stype(4) + value(4) = 12 bytes minimum
if (bufPtr != IntPtr.Zero && size >= 12)
{
uint playerId = ClientHelperHooks.GetPlayerId();
if (playerId != 0)
{
uint stype = (uint)Marshal.ReadInt32(bufPtr + 4);
int val = Marshal.ReadInt32(bufPtr + 8);
CacheInt(playerId, stype, val);
}
}
}
catch { }
return _origPrivateUpdateInt!(uiPtr, bufPtr, size);
}
private static uint DetourPrivateUpdateBool(IntPtr uiPtr, IntPtr bufPtr, uint size)
{
try
{
// Private: seq(4) + stype(4) + value(4) = 12 bytes minimum
if (bufPtr != IntPtr.Zero && size >= 12)
{
uint playerId = ClientHelperHooks.GetPlayerId();
if (playerId != 0)
{
uint stype = (uint)Marshal.ReadInt32(bufPtr + 4);
int val = Marshal.ReadInt32(bufPtr + 8);
CacheBool(playerId, stype, val);
}
}
}
catch { }
return _origPrivateUpdateBool!(uiPtr, bufPtr, size);
}
private static byte DetourBeingDeleted(IntPtr weenieObjPtr)
{
try
{
if (weenieObjPtr != IntPtr.Zero)
{
IntPtr idAddr = weenieObjPtr + WeenieIdOffset;
if (ClientObjectHooks.IsReadablePointer(idAddr))
{
uint objectId = (uint)Marshal.ReadInt32(idAddr);
if (objectId != 0)
EvictObject(objectId);
}
}
}
catch { }
return _origBeingDeleted!(weenieObjPtr);
}
// --- Cache helpers ---
private static void CacheInt(uint guid, uint stype, int value)
{
var props = _intCache.GetOrAdd(guid, _ => new ConcurrentDictionary<uint, int>());
props[stype] = value;
}
private static void CacheBool(uint guid, uint stype, int value)
{
var props = _boolCache.GetOrAdd(guid, _ => new ConcurrentDictionary<uint, int>());
props[stype] = value;
}
}

View file

@ -0,0 +1,338 @@
// ============================================================================
// RynthCore.Engine - Compatibility/RadarHooks.cs
//
// 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.
//
// All four target addresses are now resolved via HookResolver.Resolve:
// pattern-scan first, hardcoded VA fallback, or UNAVAILABLE — the install
// log line tells us exactly how each one resolved on the live binary.
// ============================================================================
using System;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
namespace RynthCore.Engine.Compatibility;
internal static class RadarHooks
{
// Fallback VAs (validated against the 4,841,472-byte client recorded in
// docs/ACCLIENT_HOOK_INVENTORY.md). Only used if pattern-scan misses.
private const int GmRadarUIDrawObjectsFallbackVa = 0x004D9FE0;
private const int GmRadarUIDrawChildrenFallbackVa = 0x004DA380;
private const int UIElementGetSurfaceBoxFallbackVa = 0x00462220;
private const int UIElementSetVisibleFallbackVa = 0x00462390;
// gmRadarUI::DrawObjects(UISurface*) — large 0xDC stack frame, fld of
// a Single field at +0x600, fmul against a global float in .data.
private static readonly byte?[] DrawObjectsPattern =
[
0x81, 0xEC, 0xDC, 0x00, 0x00, 0x00, 0x53, 0x55,
0x56, 0x8B, 0xF1, 0xD9, 0x86, 0x00, 0x06, 0x00,
0x00, 0x8B, 0x86, 0x0C, 0x06, 0x00, 0x00,
0xD8, 0x25, null, null, null, null, // fmul dword ptr [imm32] — global float
0x33, 0xDB, 0x3B, 0xC3
];
// gmRadarUI::DrawChildren(Box2D&,Box2D&,SmartArray&,UISurface*)
private static readonly byte?[] DrawChildrenPattern =
[
0x8B, 0x44, 0x24, 0x0C, 0x8B, 0x54, 0x24, 0x04,
0x53, 0x55, 0x56, 0x8B, 0x74, 0x24, 0x1C, 0x57,
0x56, 0x8B, 0xF9, 0x8B, 0x4C, 0x24, 0x1C, 0x50,
0x51, 0x52, 0x8B, 0xCF,
0xE8, null, null, null, null, // call rel32
0x56
];
// UIElement::SetVisible(bool) — entry uses [global vftable cache] + virtual call.
private static readonly byte?[] UIElementSetVisiblePattern =
[
0x51, 0x53, 0x56, 0x57,
0x8B, 0x3D, null, null, null, null, // mov edi, ds:[imm32]
0x8B, 0xF1,
0xE8, null, null, null, null, // call rel32
0x8B, 0x9E, 0xA4, 0x00, 0x00, 0x00,
0x88, 0x44, 0x24, 0x0F
];
// UIElement::GetSurfaceBox(Box2D*) — 'test byte ptr [ecx+0x556], 1' is
// the unique fingerprint (UIElement-specific flags field).
private static readonly byte?[] UIElementGetSurfaceBoxPattern =
[
0xF6, 0x81, 0x56, 0x05, 0x00, 0x00, 0x01,
0x74, 0x11, 0x56, 0x8B, 0x74, 0x24, 0x08, 0x56,
0xE8, null, null, null, null, // call rel32
0x8B, 0xC6, 0x5E, 0xC2, 0x04, 0x00
];
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void GmRadarUIDrawObjectsDelegate(IntPtr thisPtr, IntPtr uiSurface);
[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 IntPtr _uiElementSetVisibleAddress;
private static IntPtr _uiElementGetSurfaceBoxAddress;
private static bool _hookInstalled;
private static string _statusMessage = "Not initialized.";
public static bool IsInstalled => _hookInstalled;
public static string StatusMessage => _statusMessage;
private static bool _suppressOriginalDraw;
public static bool SuppressOriginalDraw
{
get => _suppressOriginalDraw;
set
{
if (_suppressOriginalDraw == value) return;
_suppressOriginalDraw = value;
RynthLog.Info($"RadarHooks: SuppressOriginalDraw -> {value}. _gmRadarUIInstance=0x{_gmRadarUIInstance.ToInt32():X8}, drawObjectsHits={_drawObjectsHits}, drawChildrenHits={_drawChildrenHits}.");
}
}
private static int _drawObjectsHits;
private static bool _isHiddenAsserted;
private static int _drawChildrenHits;
/// <summary>
/// The captured gmRadarUI singleton. Zero until the radar has rendered at
/// least once this session (usually within the first frame after login).
/// </summary>
public static IntPtr GmRadarUIInstance => _gmRadarUIInstance;
public static void Initialize()
{
if (_hookInstalled)
return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
{
_statusMessage = "acclient.exe not available.";
return;
}
// Resolve the two helper function pointers used by TryGetRadarRect /
// any future SetVisible call. These are direct-call sites, not hooks,
// but if their VAs are wrong we'd AV inside acclient.exe just like a
// bad hook would — so resolve them through the same gate.
var setVisible = HookResolver.Resolve(textSection, "RadarHooks.UIElement::SetVisible",
UIElementSetVisiblePattern, UIElementSetVisibleFallbackVa);
if (setVisible.Success) _uiElementSetVisibleAddress = setVisible.Address;
var getSurfaceBox = HookResolver.Resolve(textSection, "RadarHooks.UIElement::GetSurfaceBox",
UIElementGetSurfaceBoxPattern, UIElementGetSurfaceBoxFallbackVa);
if (getSurfaceBox.Success) _uiElementGetSurfaceBoxAddress = getSurfaceBox.Address;
bool drawObjectsOk = TryInstallDrawObjectsHook(textSection);
bool drawChildrenOk = TryInstallDrawChildrenHook(textSection);
if (drawObjectsOk && drawChildrenOk)
{
_hookInstalled = true;
_statusMessage = "Hooked gmRadarUI::DrawObjects + DrawChildren.";
RynthLog.Info($"RadarHooks: {_statusMessage}");
}
else
{
_statusMessage = $"Partial install — DrawObjects={drawObjectsOk}, DrawChildren={drawChildrenOk}.";
RynthLog.Compat($"RadarHooks: {_statusMessage}");
}
}
private static bool TryInstallDrawObjectsHook(AcClientTextSection textSection)
{
var resolved = HookResolver.Resolve(textSection, "RadarHooks.DrawObjects",
DrawObjectsPattern, GmRadarUIDrawObjectsFallbackVa);
if (!resolved.Success)
return false;
try
{
_drawObjectsDetour = DrawObjectsDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_drawObjectsDetour);
_originalDrawObjects = Marshal.GetDelegateForFunctionPointer<GmRadarUIDrawObjectsDelegate>(
MinHook.HookCreate(resolved.Address, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(resolved.Address);
return true;
}
catch (Exception ex)
{
RynthLog.Compat($"RadarHooks: DrawObjects hook install threw {ex.GetType().Name}: {ex.Message}");
return false;
}
}
private static bool TryInstallDrawChildrenHook(AcClientTextSection textSection)
{
var resolved = HookResolver.Resolve(textSection, "RadarHooks.DrawChildren",
DrawChildrenPattern, GmRadarUIDrawChildrenFallbackVa);
if (!resolved.Success)
return false;
try
{
_drawChildrenDetour = DrawChildrenDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_drawChildrenDetour);
_originalDrawChildren = Marshal.GetDelegateForFunctionPointer<GmRadarUIDrawChildrenDelegate>(
MinHook.HookCreate(resolved.Address, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(resolved.Address);
return true;
}
catch (Exception ex)
{
RynthLog.Compat($"RadarHooks: DrawChildren hook install threw {ex.GetType().Name}: {ex.Message}");
return false;
}
}
private static void DrawObjectsDetour(IntPtr thisPtr, IntPtr uiSurface)
{
RecursionGuard.Tick("RadarHooks.DrawObjects");
if (thisPtr != IntPtr.Zero)
_gmRadarUIInstance = thisPtr;
int hit = Interlocked.Increment(ref _drawObjectsHits);
if (hit <= 3)
RynthLog.Info($"RadarHooks: DrawObjects detour fired #{hit} this=0x{thisPtr.ToInt32():X8} suppress={_suppressOriginalDraw}.");
// Always call original — see SuppressOriginalDraw comment. Hiding is
// done via TickHide / SetVisible(false) per frame, NOT by skipping
// the draw. Skipping leaves AC's downstream UI state inconsistent
// (the SmartArray& boxArray output param, etc.) and crashes the
// client when the next UI traversal (e.g. PopOutPanel) walks it.
try
{
_originalDrawObjects!(thisPtr, uiSurface);
}
catch (Exception ex)
{
try { RynthLog.Compat($"RadarHooks: DrawObjects original threw {ex.GetType().Name}: {ex.Message}"); } catch { }
throw;
}
}
private static void DrawChildrenDetour(IntPtr thisPtr, IntPtr clipRect, IntPtr clipInside, IntPtr boxArray, IntPtr uiSurface)
{
RecursionGuard.Tick("RadarHooks.DrawChildren");
if (thisPtr != IntPtr.Zero)
_gmRadarUIInstance = thisPtr;
int hit = Interlocked.Increment(ref _drawChildrenHits);
if (hit <= 3)
RynthLog.Info($"RadarHooks: DrawChildren detour fired #{hit} this=0x{thisPtr.ToInt32():X8} suppress={_suppressOriginalDraw}.");
try
{
_originalDrawChildren!(thisPtr, clipRect, clipInside, boxArray, uiSurface);
}
catch (Exception ex)
{
try { RynthLog.Compat($"RadarHooks: DrawChildren original threw {ex.GetType().Name}: {ex.Message}"); } catch { }
throw;
}
}
/// <summary>
/// Per-frame visibility assertion — called from EndSceneHook every frame.
/// While <see cref="SuppressOriginalDraw"/> is on, calls SetVisible(false)
/// on the captured radar singleton each frame so AC can't sneak the
/// radar back on. When the flag flips off, calls SetVisible(true) once
/// to restore. Mirrors the same pattern <see cref="ChatHooks.TickHide"/>
/// uses for the retail chatbox. Confirmed working in production.
/// </summary>
public static unsafe void TickHide()
{
// Don't touch the singleton between in-world sessions — AC frees the
// UIElement during the logout-to-charselect transition and a stale
// pointer dereference inside UIElement::IsVisible AVs the client.
if (!LoginLifecycleHooks.HasObservedLoginComplete)
return;
IntPtr inst = _gmRadarUIInstance;
IntPtr setVisible = _uiElementSetVisibleAddress;
if (inst == IntPtr.Zero || setVisible == IntPtr.Zero)
return;
if (_suppressOriginalDraw)
{
try
{
((delegate* unmanaged[Thiscall]<IntPtr, int, void>)setVisible)(inst, 0);
}
catch { /* best-effort */ }
_isHiddenAsserted = true;
return;
}
if (_isHiddenAsserted)
{
try
{
((delegate* unmanaged[Thiscall]<IntPtr, int, void>)setVisible)(inst, 1);
}
catch { /* best-effort */ }
_isHiddenAsserted = false;
}
}
public static void ResetCachedInstance()
{
_gmRadarUIInstance = IntPtr.Zero;
_isHiddenAsserted = false;
}
/// <summary>
/// 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.
/// </summary>
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;
if (_uiElementGetSurfaceBoxAddress == 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]<IntPtr, int*, int*>)_uiElementGetSurfaceBoxAddress)(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;
}
}

View file

@ -0,0 +1,95 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Thread-safe store for raw opcode observations captured by RawPacketHooks.
/// Populated on the network receive thread; read on the ImGui render thread.
/// </summary>
internal static class RawOpcodeTracker
{
public struct OpcodeEntry
{
public int Count;
public int LastPayloadLen;
public byte[] LastSample; // up to 16 bytes of the most recent payload
}
// Opcodes already handled by SmartBoxHooks — shown only when ShowKnown is true.
private static readonly HashSet<ushort> KnownOpcodes =
[
0xF74B, 0xF74C, 0xF74E, 0xF7DB, 0xF7B0, 0xF658
];
private static readonly object _lock = new();
private static readonly Dictionary<ushort, OpcodeEntry> _entries = new();
public static bool Frozen;
public static bool ShowKnown = false;
public static bool ShowUnknown = true;
// Deep-audit finding #25 (2026-06-18): Track allocates a fresh byte[] for
// every non-zero-opcode blob of every inbound packet, called from
// RecvFromDetour (a reverse-P/Invoke detour) with no gate on whether the
// Packet Sniffer panel is even open — only Frozen. Sustained per-packet
// managed allocation on a reverse-P/Invoke transition is the documented
// RhpReversePInvokeAttachOrTrapThread2 fail-fast hazard; on a busy
// multibox it's constant GC churn for a diagnostic feature nobody is
// looking at. RynthCoreShell sets this to the panel's actual visibility
// every frame (open OR closed) — Track short-circuits before any
// allocation while it's false, which is the overwhelming common case.
public static volatile bool Active;
public static bool IsKnown(ushort opcode) => KnownOpcodes.Contains(opcode);
public static unsafe void Track(ushort opcode, byte* payload, int payloadLen)
{
if (Frozen || !Active) return;
int sampleLen = payloadLen < 16 ? payloadLen : 16;
byte[] sample = new byte[sampleLen];
for (int i = 0; i < sampleLen; i++)
sample[i] = payload[i];
lock (_lock)
{
if (_entries.TryGetValue(opcode, out OpcodeEntry existing))
{
existing.Count++;
existing.LastPayloadLen = payloadLen;
existing.LastSample = sample;
_entries[opcode] = existing;
}
else
{
_entries[opcode] = new OpcodeEntry
{
Count = 1,
LastPayloadLen = payloadLen,
LastSample = sample
};
}
}
}
public static void Clear()
{
lock (_lock)
_entries.Clear();
}
/// <summary>Returns a snapshot of all tracked entries sorted by opcode for rendering.</summary>
public static (ushort Opcode, OpcodeEntry Entry)[] GetSnapshot()
{
lock (_lock)
{
var result = new (ushort, OpcodeEntry)[_entries.Count];
int i = 0;
foreach (var kv in _entries)
result[i++] = (kv.Key, kv.Value);
Array.Sort(result, (a, b) => a.Item1.CompareTo(b.Item1));
return result;
}
}
}

View file

@ -0,0 +1,95 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.Engine.Hooking;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Hooks the game's recvfrom socket function to intercept all S2C UDP packets.
///
/// The acclient.exe data segment holds a pointer to the recvfrom implementation:
/// RecvFrom @ *(int*)0x007935AC
/// SendTo @ *(int*)0x007935A4 (not hooked — S2C discovery only)
///
/// We read the function address, install a MinHook detour, call through to the
/// original on every receive, then hand the buffer to RawPacketParser for
/// opcode extraction. The hook is purely read-only and never modifies traffic.
/// </summary>
internal static class RawPacketHooks
{
private const int RecvFromPtrAddr = unchecked((int)0x007935AC);
// Phase B: resolve the RecvFrom fn-ptr slot's address by code-xref ("call [slot]" =
// FF 15 <addr>), operand at offset 2; the VA stays as fallback.
private static readonly byte?[] PatXrefRecvFromSlot = [ 0xFF, 0x15, null, null, null, null, 0x8B, 0xF0, 0x85, 0xF6, 0x7E, 0x67 ];
private static IntPtr _originalRecvFromPtr;
public static bool IsInstalled { get; private set; }
public static void Initialize()
{
if (IsInstalled) return;
int slotAddr = RecvFromPtrAddr;
if (AcClientModule.TryReadTextSection(out AcClientTextSection text))
slotAddr = HookResolver.ResolveData(text, "RawPacket.RecvFromSlot", PatXrefRecvFromSlot, 2, RecvFromPtrAddr).Address.ToInt32();
unsafe
{
IntPtr fnPtrAddr = new IntPtr(slotAddr);
if (!SmartBoxLocator.IsMemoryReadable(fnPtrAddr, 4))
{
RynthLog.Compat($"RawPacket: RecvFrom pointer address 0x{slotAddr:X8} not readable — skipping.");
return;
}
IntPtr recvFromAddr = Marshal.ReadIntPtr(fnPtrAddr);
if (recvFromAddr == IntPtr.Zero)
{
RynthLog.Compat("RawPacket: RecvFrom pointer is null — skipping.");
return;
}
try
{
delegate* unmanaged[Stdcall]<IntPtr, IntPtr, int, int, IntPtr, IntPtr, int> pDetour = &RecvFromDetour;
MinHook.Hook(recvFromAddr, (IntPtr)pDetour, out _originalRecvFromPtr);
IsInstalled = true;
RynthLog.Verbose($"RawPacket: RecvFrom hook installed @ 0x{recvFromAddr.ToInt32():X8}");
}
catch (Exception ex)
{
RynthLog.Compat($"RawPacket: MinHook failed — {ex.Message}");
}
}
}
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvStdcall)])]
private static unsafe int RecvFromDetour(
IntPtr s, IntPtr buf, int len, int flags, IntPtr from, IntPtr fromlen)
{
RecursionGuard.Tick("RawPacketHooks.RecvFrom");
delegate* unmanaged[Stdcall]<IntPtr, IntPtr, int, int, IntPtr, IntPtr, int> original =
(delegate* unmanaged[Stdcall]<IntPtr, IntPtr, int, int, IntPtr, IntPtr, int>)_originalRecvFromPtr;
int bytesRead = original(s, buf, len, flags, from, fromlen);
if (bytesRead > 0)
{
// Managed exceptions (bounds errors, etc.) CAN be caught in NativeAOT.
// This guard prevents any parser bug from crashing the client.
try
{
RawPacketParser.Parse((byte*)buf, bytesRead);
}
catch
{
// silently swallow — never affect game traffic
}
}
return bytesRead;
}
}

View file

@ -0,0 +1,64 @@
using System;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Minimal parser for Asheron's Call S2C UDP packets.
///
/// Packet layout:
/// [Header — 20 bytes]
/// +0 SeqNo uint32
/// +4 RecID uint32
/// +8 Checksum uint32
/// +12 Flags uint32
/// +16 Time uint16
/// +18 Size uint16
///
/// [One or more BlobFragments follow, contiguously]
/// BlobFragHeader (16 bytes):
/// +0 BlobId uint64
/// +8 NumFrags uint16
/// +10 FragSize uint16 ← payload bytes immediately following this header
/// +12 FragIndex uint16
/// +14 QueueID uint16 ← THIS IS THE OPCODE
///
/// [FragSize bytes of payload]
/// [Next BlobFragHeader starts immediately after]
///
/// Checksum validation is intentionally skipped — we are read-only observers.
/// </summary>
internal static class RawPacketParser
{
private const int PacketHeaderSize = 20;
private const int BlobHeaderSize = 16;
private const int FragSizeOffset = 10;
private const int QueueIdOffset = 14;
private const int MaxBlobsPerPacket = 64; // guard against malformed packets
public static unsafe void Parse(byte* data, int length)
{
if (length < PacketHeaderSize)
return;
int offset = PacketHeaderSize;
int blobCount = 0;
while (offset + BlobHeaderSize <= length && blobCount++ < MaxBlobsPerPacket)
{
ushort fragSize = (ushort)(data[offset + FragSizeOffset] | (data[offset + FragSizeOffset + 1] << 8));
ushort queueId = (ushort)(data[offset + QueueIdOffset] | (data[offset + QueueIdOffset + 1] << 8));
int payloadStart = offset + BlobHeaderSize;
int payloadEnd = payloadStart + fragSize;
// Bounds check before touching any payload bytes
if (payloadEnd > length || payloadEnd < payloadStart)
break;
if (queueId != 0)
RawOpcodeTracker.Track(queueId, data + payloadStart, fragSize);
offset = payloadEnd;
}
}
}

View file

@ -0,0 +1,39 @@
// ============================================================================
// RynthCore.Engine - Compatibility/RecursionGuard.cs
//
// Deep-audit finding #27 (2026-06-18): PERMANENTLY DISABLED, not
// temporarily. This used to sample Environment.StackTrace on a fraction of
// calls to detect runaway same-thread recursion across the ~24 detour call
// sites that still call Tick(name) on entry. It was switched off while
// ruling out whether the StackTrace allocation itself was contributing to a
// second recursive AV (full budget + D3D9-off + ImGui-off) — that
// investigation never re-enabled it, and the "TEMPORARILY DISABLED /
// re-enable by removing this early-return" comment it carried was
// misleading: nobody had, and the dead sampling body below it was never
// going to run again without someone reading this exact comment.
//
// Deliberately NOT re-enabled here: re-adding Environment.StackTrace
// sampling on a hot per-detour path reintroduces the exact allocation this
// was disabled to rule out, and a proper allocation-free depth counter
// needs a paired enter/exit at all ~24 call sites (Tick() today is
// entry-only) — too invasive for a diagnostic that only ever logged, never
// prevented anything (this project already triages it as P3/cosmetic).
// The sibling ThreadStackSampler.SampleAll() (cross-thread, EBP-walk based,
// no per-call allocation) is a safer design for the same goal, but it
// SuspendThreads every thread in the process on each call — wiring it to
// run unattended on a timer is a real behavioral risk (a live gaming
// client hitching, or worse, one AC thread suspended mid critical-section)
// that deserves its own deliberate decision, not a drive-by from this
// finding. Tick() stays a real, honest no-op — call sites keep compiling
// unchanged, and no allocation or new risk is introduced anywhere.
// ============================================================================
namespace RynthCore.Engine.Compatibility;
internal static class RecursionGuard
{
public static void Tick(string detourName)
{
// No-op by design — see the file-header comment above.
}
}

View file

@ -0,0 +1,71 @@
using System;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Engine-level <c>/rc ...</c> chat commands. Intercepted on every chat-entry
/// path BEFORE plugin pre-dispatch and before the line reaches AC's chat:
/// <list type="bullet">
/// <item>typed in-game — <see cref="ChatCallbackHooks"/> OutgoingChatDetour</item>
/// <item>dispatch.txt / OnLoginCommandRunner / Host.InvokeChatParser —
/// <see cref="ChatCommandDispatcher.Dispatch"/></item>
/// </list>
/// Commands:
/// <list type="bullet">
/// <item><c>/rc resetbar</c> — recover the RynthCore overlay bar when it has
/// been dragged off the visible client area (its in-overlay "Rs" reset
/// button rides the bar itself, so it's unreachable once the bar is).
/// The launcher button writes this to dispatch.txt as the out-of-band
/// recovery.</item>
/// <item><c>/rc vitals</c> (alias <c>/rc hud</c>) — toggle the custom D3D9
/// Health/Stamina/Mana HUD on/off (persisted to engine.json).</item>
/// </list>
/// </summary>
internal static class RynthCoreChatCommands
{
private const string Prefix = "/rc ";
/// <summary>
/// True if <paramref name="line"/> was a RynthCore engine command and has
/// been handled — the caller must consume it (do NOT forward to AC chat
/// or to plugins).
/// </summary>
public static bool TryHandle(string? line)
{
if (string.IsNullOrWhiteSpace(line))
return false;
string trimmed = line.Trim();
if (!trimmed.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase))
return false;
string sub = trimmed.Substring(Prefix.Length).Trim();
switch (sub.ToLowerInvariant())
{
case "resetbar":
case "barreset":
RynthLog.Compat("RynthCoreChatCommands: /rc resetbar — resetting overlay bar position.");
ImGuiBackend.RynthCoreShell.RequestExternalReset();
return true;
case "vitals":
case "hud":
{
// Toggle the custom D3D9 vital HUD. Setter persists to engine.json
// so it survives relaunch. (No AC-chat echo — the AddTextToScroll
// path has a known AV risk; the HUD appearing/vanishing confirms.)
bool now = !Plugins.EngineSettings.DrawCustomVitalBars;
Plugins.EngineSettings.DrawCustomVitalBars = now;
RynthLog.Compat($"RynthCoreChatCommands: /rc vitals — custom vital HUD {(now ? "ON" : "OFF")}.");
return true;
}
default:
// Consume anything else under the /rc namespace so a typo
// does not leak into world chat.
RynthLog.Compat($"RynthCoreChatCommands: unknown subcommand '/rc {sub}'.");
return true;
}
}
}

View file

@ -0,0 +1,99 @@
// ============================================================================
// RynthCore.Engine - Compatibility/SalvageHooks.cs
//
// Hooks gmSalvageUI::OpenSalvagePanel to capture the singleton 'this' pointer.
// The captured instance is used by ClientHelperHooks for SalvagePanelAddItem
// and SalvagePanelExecute, which call the thiscall instance methods directly.
// ============================================================================
using System;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
namespace RynthCore.Engine.Compatibility;
internal static class SalvageHooks
{
private const int OpenSalvagePanelFallbackVa = 0x004CBF70;
// gmSalvageUI::OpenSalvagePanel(uint toolId)
// Reads the salvage UI element from [esi+0x600], pushes it as 'this' to
// call the +0x608 lookup. The two `[esi+0x600]` accesses + the two E8 calls
// are very specific to this function.
private static readonly byte?[] OpenSalvagePanelPattern =
[
0x8B, 0x44, 0x24, 0x04, 0x56, 0x8B, 0xF1, 0x8B,
0x8E, 0x00, 0x06, 0x00, 0x00, 0x51, 0x8B, 0xCE,
0x89, 0x86, 0x08, 0x06, 0x00, 0x00,
0xE8, null, null, null, null, // call rel32
0x8B, 0x8E, 0x00, 0x06, 0x00, 0x00,
0xE8, null, null, null, null // call rel32
];
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void GmSalvageUIOpenSalvagePanelDelegate(IntPtr thisPtr, uint toolId);
private static GmSalvageUIOpenSalvagePanelDelegate? _originalOpenSalvagePanel;
private static GmSalvageUIOpenSalvagePanelDelegate? _openSalvagePanelDetour;
private static IntPtr _gmSalvageUIInstance;
private static bool _hookInstalled;
private static string _statusMessage = "Not initialized.";
public static bool IsInstalled => _hookInstalled;
public static string StatusMessage => _statusMessage;
public static IntPtr GmSalvageUIInstance => _gmSalvageUIInstance;
public static void Initialize()
{
if (_hookInstalled)
return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
{
_statusMessage = "acclient.exe not available.";
return;
}
var resolved = HookResolver.Resolve(textSection, "SalvageHooks.OpenSalvagePanel",
OpenSalvagePanelPattern, OpenSalvagePanelFallbackVa);
if (!resolved.Success)
{
_statusMessage = $"Resolve failed ({resolved.Detail}).";
return;
}
try
{
_openSalvagePanelDetour = OpenSalvagePanelDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_openSalvagePanelDetour);
_originalOpenSalvagePanel = Marshal.GetDelegateForFunctionPointer<GmSalvageUIOpenSalvagePanelDelegate>(
MinHook.HookCreate(resolved.Address, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(resolved.Address);
_hookInstalled = true;
_statusMessage = $"Hooked gmSalvageUI::OpenSalvagePanel @ 0x{resolved.Address.ToInt32():X8}.";
RynthLog.Compat($"SalvageHooks: install ok.");
}
catch (Exception ex)
{
_statusMessage = ex.Message;
RynthLog.Compat($"SalvageHooks: install threw {ex.GetType().Name}: {ex.Message}");
}
}
private static int _fires;
private static void OpenSalvagePanelDetour(IntPtr thisPtr, uint toolId)
{
if (thisPtr != IntPtr.Zero)
_gmSalvageUIInstance = thisPtr;
if (++_fires <= 3)
RynthLog.Compat($"SalvageHooks: OpenSalvagePanel fired #{_fires} this=0x{thisPtr.ToInt32():X8} toolId=0x{toolId:X}");
try { _originalOpenSalvagePanel!(thisPtr, toolId); }
catch (Exception ex) { try { RynthLog.Compat($"SalvageHooks: original threw {ex.GetType().Name}: {ex.Message}"); } catch { } throw; }
}
}

View file

@ -0,0 +1,194 @@
// ============================================================================
// RynthCore.Engine - SehTrampoline.cs
// Managed P/Invoke bridge to RynthCore.SehTrampoline.dll.
//
// NativeAOT managed try/catch cannot catch access violations (hardware
// exceptions / corrupted-state exceptions on .NET 5+). When AC's native
// code AVs while we call an AC API during object teardown, the managed
// catch { } is a no-op and the process dies.
//
// The trampoline DLL provides __try/__except wrappers compiled with MSVC.
// Each export wraps exactly one native call. If the call AVs, the SEH
// handler catches it, sets the out-parameter to a safe default, and
// returns 0. Return 1 means the call completed normally.
//
// This is per-callsite SEH, NOT process-wide (unlike VEH/SUEF which are
// proven fatal in NativeAOT-injected acclient — see CrashLogger.cs).
//
// Usage pattern at each call site:
// if (SehTrampoline.IsAvailable) {
// IntPtr fnPtr = Marshal.GetFunctionPointerForDelegate(_delegate!);
// T result = SehTrampoline.SomeWrapper(fnPtr, args, out bool avCaught);
// if (avCaught) { log; return safeDefault; }
// // use result normally
// } else {
// // direct delegate call (same as before this fix)
// }
// ============================================================================
using System;
using System.Runtime.InteropServices;
namespace RynthCore.Engine.Compatibility;
internal static class SehTrampoline
{
private static volatile bool _available;
/// <summary>Called by EntryPoint after RynthCore.SehTrampoline.dll loads successfully.</summary>
public static void MarkAvailable() => _available = true;
/// <summary>
/// Installs the native VEH crash logger inside the trampoline DLL. 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. Writes the faulting 32-bit context + a module-resolved stack
/// sweep to <paramref name="logPath"/> for the 0xC0000005 (AV/CSE) and 0xC0000602
/// (RaiseFailFast) classes that bypass managed handlers. Observes only.
/// </summary>
public static void InstallCrashLogger(string logPath)
{
try { _InstallCrashLogger(logPath); }
catch (Exception ex) { RynthLog.Compat($"SehTrampoline: InstallCrashLogger failed - {ex.GetType().Name}: {ex.Message}"); }
}
// ── Tag-parser guard (native detour) ───────────────────────────────────
/// <summary>Address of the native tag-parser null-guard detour (RC_TagParserGuard),
/// for the engine to pass to MinHook as the detour target.</summary>
public static IntPtr GetTagParserGuardAddress() => _GetTagParserGuardAddress();
/// <summary>Hands the native guard the MinHook trampoline (the original
/// FUN_0067D3C0). MUST be called BEFORE the hook is enabled.</summary>
public static void SetTagParserOriginal(IntPtr original) => _SetTagParserOriginal(original);
/// <summary>Count of null-context parse runs the native guard has dropped (diag).</summary>
public static uint TagParserSkipCount { get { try { return _TagParserSkipCount(); } catch { return 0; } } }
/// <summary>
/// True when the trampoline DLL is loaded. Call sites should check this
/// and fall back to direct delegate calls when false.
/// </summary>
public static bool IsAvailable => _available;
// ── P/Invoke declarations ──────────────────────────────────────────────
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "SEH_CdeclPtrUint",
CallingConvention = CallingConvention.Cdecl)]
private static extern unsafe int _CdeclPtrUint(IntPtr fn, uint arg, void** outResult);
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "SEH_CdeclPtrVoid",
CallingConvention = CallingConvention.Cdecl)]
private static extern unsafe int _CdeclPtrVoid(IntPtr fn, void** outResult);
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "SEH_CdeclVoidUintByte",
CallingConvention = CallingConvention.Cdecl)]
private static extern int _CdeclVoidUintByte(IntPtr fn, uint arg1, byte arg2);
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "SEH_FreeHandsCast",
CallingConvention = CallingConvention.Cdecl)]
private static extern int _FreeHandsCast(IntPtr fn, IntPtr thisPtr, uint spellId, uint targetId);
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "SEH_ThiscallByteUint",
CallingConvention = CallingConvention.Cdecl)]
private static extern unsafe int _ThiscallByteUint(IntPtr fn, IntPtr thisPtr, uint arg, byte* outResult);
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "SEH_ThiscallUintNoArg",
CallingConvention = CallingConvention.Cdecl)]
private static extern unsafe int _ThiscallUintNoArg(IntPtr fn, IntPtr thisPtr, uint* outResult);
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "SEH_ThiscallIntUintPtr",
CallingConvention = CallingConvention.Cdecl)]
private static extern unsafe int _ThiscallIntUintPtr(IntPtr fn, IntPtr thisPtr, uint arg1, void* arg2, int* outResult);
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "RC_InstallCrashLogger",
CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
private static extern void _InstallCrashLogger([MarshalAs(UnmanagedType.LPWStr)] string logPath);
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "RC_GetTagParserGuardAddress",
CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr _GetTagParserGuardAddress();
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "RC_SetTagParserOriginal",
CallingConvention = CallingConvention.Cdecl)]
private static extern void _SetTagParserOriginal(IntPtr original);
[DllImport("RynthCore.SehTrampoline.dll", EntryPoint = "RC_TagParserSkipCount",
CallingConvention = CallingConvention.Cdecl)]
private static extern uint _TagParserSkipCount();
// ── Typed call-through wrappers ────────────────────────────────────────
// Each returns the native result; sets avCaught=true if AV was intercepted.
// Callers MUST check IsAvailable before calling these.
/// <summary>void* __cdecl fn(uint) — e.g. GetWeenieObject(objectId)</summary>
public static IntPtr CdeclPtrUint(IntPtr fn, uint arg, out bool avCaught)
{
unsafe
{
void* result;
avCaught = _CdeclPtrUint(fn, arg, &result) == 0;
return (IntPtr)result;
}
}
/// <summary>void* __cdecl fn() — e.g. GetCombatSystem()</summary>
public static IntPtr CdeclPtrVoid(IntPtr fn, out bool avCaught)
{
unsafe
{
void* result;
avCaught = _CdeclPtrVoid(fn, &result) == 0;
return (IntPtr)result;
}
}
/// <summary>
/// void __cdecl fn(uint, byte) — e.g. CastSpell(spellId, targetIsSelected).
/// Returns false if AV was caught.
/// </summary>
public static bool CdeclVoidUintByte(IntPtr fn, uint arg1, byte arg2)
=> _CdeclVoidUintByte(fn, arg1, arg2) != 0;
/// <summary>
/// void __thiscall fn(this, uint spellId, uint targetId) — ClientMagicSystem::
/// FreeHandsAndCastSpell. Explicit-target cast (no global selection / UI state).
/// 'this' is the GetMagicSystem() singleton. Returns false if an AV was caught.
/// </summary>
public static bool FreeHandsCast(IntPtr fn, IntPtr thisPtr, uint spellId, uint targetId)
=> _FreeHandsCast(fn, thisPtr, spellId, targetId) != 0;
/// <summary>byte __thiscall fn(uint) — e.g. ObjectIsAttackable(objectId)</summary>
public static byte ThiscallByteUint(IntPtr fn, IntPtr thisPtr, uint arg, out bool avCaught)
{
unsafe
{
byte result;
avCaught = _ThiscallByteUint(fn, thisPtr, arg, &result) == 0;
return result;
}
}
/// <summary>uint __thiscall fn() — e.g. InqType()</summary>
public static uint ThiscallUintNoArg(IntPtr fn, IntPtr thisPtr, out bool avCaught)
{
unsafe
{
uint result;
avCaught = _ThiscallUintNoArg(fn, thisPtr, &result) == 0;
return result;
}
}
/// <summary>
/// int __thiscall fn(this, uint arg1, void* outStruct) — e.g.
/// InqAttribute2nd(stype, &SecondaryAttribute). Returns the native int result
/// (nonzero = success); avCaught=true (and result 0) if an AV was intercepted.
/// outStruct points at caller-owned memory the callee fills on success.
/// </summary>
public static unsafe int ThiscallIntUintPtr(IntPtr fn, IntPtr thisPtr, uint arg1, void* outStruct, out bool avCaught)
{
int result;
avCaught = _ThiscallIntUintPtr(fn, thisPtr, arg1, outStruct, &result) == 0;
return result;
}
}

View file

@ -0,0 +1,114 @@
using System;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.Compatibility;
internal static class SelectedTargetHooks
{
private const int SetSelectedObjectVa = 0x0058D110;
private const int SelectedIdVa = 0x00871E54;
// Phase B: resolve s_selected_id's address by code-xref (ret; mov eax,[s_selected_id] =
// C3 A1 <addr>), operand at offset 2; the VA stays as fallback. Resolved in Initialize.
private static readonly byte?[] PatXrefSelectedId = [ 0xC3, 0xA1, null, null, null, null, 0x89, 0x87 ];
private static int _selectedIdAddr = SelectedIdVa;
/// <summary>
/// Reads the AC client's currently-selected target id directly from the
/// global. Used by PluginManager.DispatchLoginCompleteToLoadedPlugins to
/// re-seed plugins with the live target after a deferred init (events
/// fired before <c>_initialized=true</c> are dropped by the queue gate).
/// </summary>
public static uint ReadCurrentSelectedId() => ReadUInt32(_selectedIdAddr);
// Verified unique + lands at 0x0058D110 offline (tools/pe_pattern.py).
private static readonly byte?[] SetSelectedObjectPattern =
[
0x8B, 0x4C, 0x24, 0x08, 0x85, 0xC9, 0xA1, 0x54
];
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void SetSelectedObjectDelegate(uint selectedId, int reselect);
private static SetSelectedObjectDelegate? _originalSetSelectedObject;
private static SetSelectedObjectDelegate? _setSelectedObjectDetour;
private static IntPtr _targetAddress;
private static string _statusMessage = "Not probed yet.";
public static bool IsInstalled { get; private set; }
public static string StatusMessage => _statusMessage;
public static void Initialize()
{
if (IsInstalled)
return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
{
_statusMessage = "acclient.exe not available.";
return;
}
HookResolver.ResolveResult resolved = HookResolver.Resolve(textSection, "SelectedTarget.SetSelectedObject", SetSelectedObjectPattern, SetSelectedObjectVa);
if (!resolved.Success)
{
_statusMessage = $"ACCWeenieObject::SetSelectedObject unresolved (VA 0x{SetSelectedObjectVa:X8}).";
RynthLog.Compat($"Compat: selected-target hook failed - {_statusMessage}");
return;
}
_selectedIdAddr = HookResolver.ResolveData(textSection, "SelectedTarget.s_selected_id", PatXrefSelectedId, 2, SelectedIdVa).Address.ToInt32();
try
{
_targetAddress = resolved.Address;
_setSelectedObjectDetour = SetSelectedObjectDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_setSelectedObjectDetour);
_originalSetSelectedObject = Marshal.GetDelegateForFunctionPointer<SetSelectedObjectDelegate>(MinHook.HookCreate(_targetAddress, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(_targetAddress);
IsInstalled = true;
_statusMessage = $"Hooked ACCWeenieObject::SetSelectedObject @ 0x{_targetAddress.ToInt32():X8}.";
RynthLog.Info(
$"Compat: selected-target hook ready - SetSelectedObject=0x{_targetAddress.ToInt32():X8}, selectedId=0x{SelectedIdVa:X8}");
}
catch (Exception ex)
{
_statusMessage = ex.Message;
RynthLog.Compat($"Compat: selected-target hook failed - {ex.Message}");
}
}
private static void SetSelectedObjectDetour(uint selectedId, int reselect)
{
uint previousTargetId = ReadUInt32(_selectedIdAddr);
try
{
_originalSetSelectedObject!(selectedId, reselect);
}
catch (Exception ex)
{
try { RynthLog.Compat($"Compat: selected-target detour error - {ex.GetType().Name}: {ex.Message}"); } catch { }
throw;
}
uint currentTargetId = ReadUInt32(_selectedIdAddr);
if (currentTargetId == previousTargetId)
return;
if (Interlocked.Increment(ref _detourLogCount) <= 5)
RynthLog.Compat($"Compat: selected-target detour fired (#{_detourLogCount}) - prev=0x{previousTargetId:X8} curr=0x{currentTargetId:X8} reselect={reselect}");
PluginManager.QueueSelectedTargetChange(currentTargetId, previousTargetId);
}
private static int _detourLogCount;
private static uint ReadUInt32(int address)
{
return unchecked((uint)Marshal.ReadInt32(new IntPtr(address)));
}
}

View file

@ -0,0 +1,208 @@
using System;
using System.Diagnostics;
using System.IO;
using System.Text.Json;
using RynthCore.App;
namespace RynthCore.Engine.Compatibility;
internal static class SessionStateRegistry
{
private static bool _initialized;
private static bool _loginRecorded;
// Last-recorded session identity, exposed in-memory so the GetEngineStatusJson accessor
// can label this client without re-parsing any file (re-reading
// the session record here can recurse through DatFileShareHooks — see the
// long comment in TryWriteLoginState). Empty until LoginComplete records.
internal static string LastAccountName { get; private set; } = string.Empty;
internal static string LastCharacterName { get; private set; } = string.Empty;
internal static string LastServerName { get; private set; } = string.Empty;
public static void Initialize()
{
if (_initialized)
return;
_initialized = true;
LoginLifecycleHooks.LoginComplete += OnLoginComplete;
// No longer subscribe to LogoutLifecycleHooks. RecvNotice_Logoff has
// been observed firing during normal play (transient state changes,
// not actual logoff), and flipping IsLoggedIn=false on a per-process
// record would let the launcher's stuck-client reaper kill a healthy
// in-game client. The launcher's _everLoggedInPids latch handles the
// post-login case from its side without needing this signal.
}
public static void Poll()
{
if (_loginRecorded || !LoginLifecycleHooks.HasObservedLoginComplete)
return;
TryWriteLoginState();
}
private static void OnLoginComplete()
{
TryWriteLoginState();
}
/// <summary>
/// Flip the persisted record to <c>IsLoggedIn=false</c> + record
/// <c>LogoutAtUtc</c>. Fires for both clean logout (CPlayerSystem::ExecuteLogOff)
/// and server-driven disconnect (gmGamePlayUI::RecvNotice_Logoff). The
/// launcher's stuck-client reaper uses LogoutAtUtc to detect a session
/// that's been sitting on the disconnect/char-select screen too long.
/// Resets <see cref="_loginRecorded"/> so a relogin within the same
/// process re-records correctly.
/// </summary>
private static void OnLogoutObserved()
{
try
{
SessionStateRecord? record = SessionStateStore.TryReadForProcess(Environment.ProcessId);
if (record == null)
return;
record.IsLoggedIn = false;
record.LogoutAtUtc = DateTime.UtcNow;
SessionStateStore.WriteForProcess(Environment.ProcessId, record);
_loginRecorded = false;
RynthLog.Verbose($"SessionState: recorded logout for PID {Environment.ProcessId}.");
}
catch (Exception ex)
{
RynthLog.Compat($"SessionState: failed to record logout - {ex.Message}");
}
}
private static void TryWriteLoginState()
{
if (_loginRecorded)
return;
try
{
// Do not call TryReadForProcess here — JsonDocument.Parse inside
// it interacts with DatFileShareHooks.CreateFile in a way that
// causes a stack overflow (~17s after LoginComplete). All fields
// it would have contributed are either read from the launch-context
// file below or reseeded from Process.StartTime, so the result was
// always null anyway once the workaround was in place.
SessionStateRecord? existingRecord = null;
(string accountName, string serverName, string targetCharacter) = ReadLaunchContext();
accountName = Coalesce(accountName, existingRecord?.AccountName);
serverName = Coalesce(serverName, existingRecord?.ServerName);
targetCharacter = Coalesce(targetCharacter, existingRecord?.TargetCharacter);
string characterName = ResolveCharacterName(targetCharacter);
if (string.IsNullOrWhiteSpace(characterName))
characterName = Coalesce(existingRecord?.CharacterName, targetCharacter);
var record = new SessionStateRecord
{
ProcessId = Environment.ProcessId,
AccountName = accountName,
ServerName = serverName,
TargetCharacter = targetCharacter,
CharacterName = characterName,
LaunchStartedAtUtc = existingRecord?.LaunchStartedAtUtc ?? GetProcessStartTimeUtc(),
LoginCompletedAtUtc = DateTime.UtcNow,
IsLoggedIn = true
};
SessionStateStore.WriteForProcess(Environment.ProcessId, record);
if (!string.IsNullOrWhiteSpace(accountName) && !string.IsNullOrWhiteSpace(characterName))
CharacterCacheStore.UpsertCharacter(accountName, serverName, characterName);
// Cache identity in-memory for the GetEngineStatusJson accessor.
LastAccountName = accountName;
LastCharacterName = characterName;
LastServerName = serverName;
_loginRecorded = true;
RynthLog.Info($"SessionState: recorded login session for PID {Environment.ProcessId} account='{accountName}' character='{characterName}' (IsLoggedIn=true).");
}
catch (Exception ex)
{
RynthLog.Compat($"SessionState: failed to record login session - {ex.Message}");
}
}
private static string ResolveCharacterName(string fallbackCharacter)
{
// DIAGNOSTIC: live-memory lookup disabled — ClientObjectHooks.TryGetObjectName
// chain (GetWeenieObject + GetObjectName variants) was bisected as the
// recursive AV trigger at LoginComplete. Returning the launch-context
// character name only until the lookup is fixed.
return fallbackCharacter ?? string.Empty;
#pragma warning disable CS0162
uint playerId = ClientHelperHooks.GetPlayerId();
if (playerId != 0 && ClientObjectHooks.TryGetObjectName(playerId, out string actualName) && !string.IsNullOrWhiteSpace(actualName))
return actualName;
return fallbackCharacter ?? string.Empty;
#pragma warning restore CS0162
}
private static DateTime GetProcessStartTimeUtc()
{
try
{
using Process process = Process.GetCurrentProcess();
return process.StartTime.ToUniversalTime();
}
catch
{
return DateTime.UtcNow;
}
}
private static (string accountName, string serverName, string targetCharacter) ReadLaunchContext()
{
try
{
string rootDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"RynthCore");
string processPath = Path.Combine(rootDir, "launch_contexts", $"launch_context_{Environment.ProcessId}.json");
(string accountName, string serverName, string targetCharacter) processContext = ReadLaunchContextFile(processPath);
if (!string.IsNullOrWhiteSpace(processContext.accountName) ||
!string.IsNullOrWhiteSpace(processContext.serverName) ||
!string.IsNullOrWhiteSpace(processContext.targetCharacter))
{
return processContext;
}
return ReadLaunchContextFile(Path.Combine(rootDir, "launch_context.json"));
}
catch
{
return (string.Empty, string.Empty, string.Empty);
}
}
private static (string accountName, string serverName, string targetCharacter) ReadLaunchContextFile(string filePath)
{
if (!File.Exists(filePath))
return (string.Empty, string.Empty, string.Empty);
using JsonDocument doc = JsonDocument.Parse(File.ReadAllBytes(filePath));
JsonElement root = doc.RootElement;
string accountName = root.TryGetProperty("AccountName", out JsonElement an) ? an.GetString() ?? string.Empty : string.Empty;
string serverName = root.TryGetProperty("ServerName", out JsonElement sn) ? sn.GetString() ?? string.Empty : string.Empty;
string target = root.TryGetProperty("TargetCharacter", out JsonElement tc) ? tc.GetString() ?? string.Empty : string.Empty;
return (accountName, serverName, target);
}
private static string Coalesce(string? primary, string? fallback)
{
if (!string.IsNullOrWhiteSpace(primary))
return primary.Trim();
return fallback?.Trim() ?? string.Empty;
}
}

View file

@ -0,0 +1,558 @@
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.Engine.Hooking;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.Compatibility;
internal static class SmartBoxHooks
{
private const int NetBlobBufPtrOffset = 0x2C;
private const int NetBlobBufSizeOffset = 0x30;
private const uint PositionUpdateOpcode = 0x0000F74C;
private const uint PlayerPositionUpdateOpcode = 0x0000F74B;
private const uint VectorUpdateOpcode = 0x0000F74E;
private const uint UpdateObjectOpcode = 0x0000F7DB;
// ACSmartBox::DispatchSmartBoxEvent
// 83 EC 08 53 8B 5C 24 10 8B 53 30 83 FA 04 8B 43 2C 56 8B F1 89 44 24 14 89 54 24 08 72 ?? 8B 08
private static readonly byte?[] DispatchSmartBoxEventPattern =
[
0x83, 0xEC, 0x08, 0x53, 0x8B, 0x5C, 0x24, 0x10,
0x8B, 0x53, 0x30, 0x83, 0xFA, 0x04, 0x8B, 0x43,
0x2C, 0x56, 0x8B, 0xF1, 0x89, 0x44, 0x24, 0x14,
0x89, 0x54, 0x24, 0x08, 0x72, null, 0x8B, 0x08
];
// UIQueueManager::ProcessNetBlobData @ 0x0055BCD0 — the real inbound GameEvent
// dispatcher (switches on inner event type: 0x1B1/0x1B2 attack, 0x1AC/0x1AD
// victim/killer, 0x1C0 health, …). thiscall(this, uint* data, int end);
// the inner event type is *data and the payload follows at data+4.
// ⚠ This MUST differ from DispatchSmartBoxEventPattern — they were once an
// identical copy-paste, which deduped this hook away (it never installed, so
// combat events were never seen). Verified unique vs acclient.exe.
private static readonly byte?[] DispatchGameEventPattern =
[
0x81, 0xEC, 0xC0, 0x01, 0x00, 0x00, 0x53, 0x55,
0x8B, 0xAC, 0x24, 0xD0, 0x01, 0x00, 0x00, 0x56,
0x57, 0x8B, 0xF9, 0x8B, 0x8C, 0x24, 0xD4, 0x01,
0x00, 0x00, 0x8B, 0x11, 0x8B, 0xC1, 0x8D, 0x34,
0x29, 0x83, 0xC1, 0x04
];
private static IntPtr _originalDispatchSmartBoxEventPtr;
private static IntPtr _originalDispatchGameEventPtr;
private static string _statusMessage = "Not probed yet.";
public static bool IsInstalled { get; private set; }
public static string StatusMessage => _statusMessage;
private static readonly object _initLock = new();
public static void Initialize()
{
lock (_initLock)
{
if (IsInstalled)
return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
{
_statusMessage = "acclient.exe not available.";
return;
}
try
{
unsafe
{
var hookedAddresses = new HashSet<IntPtr>();
// Hook SmartBox Event
int sbOff = PatternScanner.FindPattern(textSection.Bytes, DispatchSmartBoxEventPattern);
if (sbOff >= 0)
{
IntPtr sbAddr = new IntPtr(textSection.TextBaseVa + sbOff);
if (hookedAddresses.Add(sbAddr))
{
delegate* unmanaged[Thiscall]<IntPtr, IntPtr, uint> pSbDetour = &DispatchSmartBoxEventDetour;
MinHook.Hook(sbAddr, (IntPtr)pSbDetour, out _originalDispatchSmartBoxEventPtr);
RynthLog.Verbose($"Compat: smartbox hook ready @ 0x{sbAddr.ToInt32():X8}");
}
}
else RynthLog.Compat("Compat: smartbox pattern not found.");
// Hook Game Event
int geOff = PatternScanner.FindPattern(textSection.Bytes, DispatchGameEventPattern);
if (geOff >= 0)
{
IntPtr geAddr = new IntPtr(textSection.TextBaseVa + geOff);
if (hookedAddresses.Add(geAddr))
{
delegate* unmanaged[Thiscall]<IntPtr, IntPtr, int, uint> pGeDetour = &DispatchGameEventDetour;
MinHook.Hook(geAddr, (IntPtr)pGeDetour, out _originalDispatchGameEventPtr);
RynthLog.Verbose($"Compat: game-event hook ready @ 0x{geAddr.ToInt32():X8}");
}
else RynthLog.Compat("Compat: game-event pattern matched already-hooked address.");
}
else RynthLog.Compat("Compat: game-event pattern not found.");
}
IsInstalled = true;
_statusMessage = "Hooks installed.";
}
catch (Exception ex)
{
_statusMessage = ex.Message;
RynthLog.Compat($"Compat: hooks failed - {ex.Message}");
}
}
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
private static unsafe uint DispatchSmartBoxEventDetour(IntPtr thisPtr, IntPtr blob)
{
MainThreadGuard.RecordIfFirst();
RecursionGuard.Tick("SmartBoxHooks.DispatchSmartBoxEvent");
var pOriginal = (delegate* unmanaged[Thiscall]<IntPtr, IntPtr, uint>)_originalDispatchSmartBoxEventPtr;
if (!LoginLifecycleHooks.HasObservedLoginComplete)
{
try { CharacterCaptureHooks.ProcessPotentialCharacterMessage(blob, isGameEvent: false); } catch { }
return pOriginal(thisPtr, blob);
}
SmartBoxEventInfo info = ReadSmartBoxEventInfo(blob);
DiagEvent("SB", false, blob, info);
uint status = pOriginal(thisPtr, blob);
try
{
TryQueueHealthUpdate(blob, info);
TryQueueDamageEvent(blob, info);
if (info.RawObjectId != 0 &&
(info.Opcode == PositionUpdateOpcode ||
info.Opcode == PlayerPositionUpdateOpcode ||
info.Opcode == VectorUpdateOpcode ||
info.Opcode == UpdateObjectOpcode))
{
PluginManager.QueueUpdateObject(info.RawObjectId);
}
}
catch { }
return status;
}
// UIQueueManager::ProcessNetBlobData(this, uint* data, int size). thiscall:
// `this` in ECX (thisPtr), then the two stack args (data, size). The inner
// GameEvent type is *data; the event payload follows at data+4. `size` is the
// payload byte LENGTH — verified against the live binary: the hooked fn's
// prologue computes its own bound as `lea esi,[data+size]`. NOTE: this is a
// DIFFERENT function/shape than DispatchSmartBoxEvent — must keep the 2nd
// stack arg or the thiscall callee-cleanup imbalances the stack and crashes AC.
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
private static unsafe uint DispatchGameEventDetour(IntPtr thisPtr, IntPtr data, int size)
{
MainThreadGuard.RecordIfFirst();
// Engine-side BusyCount watchdog: fires on every inbound game event
// while in-world (AC's main thread). Self-heals busy-count desync.
try { BusyCountHooks.CheckWatchdog(); } catch { }
RecursionGuard.Tick("SmartBoxHooks.DispatchGameEvent");
var pOriginal = (delegate* unmanaged[Thiscall]<IntPtr, IntPtr, int, uint>)_originalDispatchGameEventPtr;
try
{
// Reject undersized payloads instead of clamping up: an inflated
// bound would let parsers read past the real payload (uncatchable
// NativeAOT AV on a page boundary).
if (data != IntPtr.Zero && size >= 4)
{
uint eventType = unchecked((uint)Marshal.ReadInt32(data));
int len = size > 0x4000 ? 0x4000 : size;
ParseGameEvent(eventType, data, (uint)len);
}
}
catch { }
return pOriginal(thisPtr, data, size);
}
private static int _geEventLogCount;
private static int _hpReadLogCount;
// Parse an inbound GameEvent for the events combat cares about. `data` points
// at the event blob: inner type @ +0, payload @ +4. `size` bounds reads.
private static void ParseGameEvent(uint eventType, IntPtr data, uint size)
{
// Diagnostic: surface the first handful of combat-range events so the hook
// can be verified live and any offset corrected from real bytes. Capped.
if (eventType >= 0x0180 && eventType <= 0x01E0 && _geEventLogCount < 40)
{
_geEventLogCount++;
uint d1 = size >= 8 ? unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 4))) : 0;
uint d2 = size >= 12 ? unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 8))) : 0;
uint d3 = size >= 16 ? unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 12))) : 0;
RynthLog.Compat($"GE evt=0x{eventType:X4} len={size} p=[{d1:X8} {d2:X8} {d3:X8}]");
}
switch (eventType)
{
case 0x01C0: // UpdateHealth: [targetId u32][ratio f32]
if (size >= 12)
{
uint targetId = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 4)));
float ratio = Marshal.PtrToStructure<float>(IntPtr.Add(data, 8));
uint maxHealth = 0, currentHealth = 0;
// We're on AC's main thread here, so read the creature's REAL
// MaxHealth straight from its qualities (SEH-guarded, appraisal-
// free) — fixes the bogus 50 stub for mobs the char can't assess.
// The plugin QueryHealth()s its combat target on lock, which is
// what makes this fire for the mobs it's actually fighting.
// Falls back to the wire-parsed appraisal cache if the read fails.
bool gotReal = ClientObjectHooks.TryReadCreatureMaxHealth(targetId, out uint realMax) && realMax > 0;
if (gotReal)
maxHealth = realMax;
else if (ObjectQualityCache.TryGetCreatureVitals(targetId, out CreatureVitals exact) && exact.MaxHealth > 0)
maxHealth = exact.MaxHealth;
if (maxHealth > 0)
currentHealth = (uint)Math.Round(maxHealth * Math.Clamp(ratio, 0f, 1f));
if (_hpReadLogCount < 25)
{
_hpReadLogCount++;
RynthLog.Compat($"Creature HP id=0x{targetId:X8}: sehRead={(gotReal ? realMax.ToString() : "none")} used={maxHealth} ratio={ratio:0.00}");
}
PluginManager.QueueUpdateHealth(targetId, ratio, currentHealth, maxHealth);
}
break;
case 0x01B1: // AttackerNotification (we hit)
case 0x01B2: // DefenderNotification (we're hit)
ParseGameEventDamage(eventType, data, size);
break;
case 0x01AD: // KillerNotification — death message string (we got a kill)
{
string? msg = ReadString16Latin1(data, 4, size);
if (!string.IsNullOrEmpty(msg))
{
if (_killNotifyLogCount < 12)
{
_killNotifyLogCount++;
RynthLog.Compat($"Combat: kill notify '{msg}'");
}
PluginManager.QueueKillNotification(msg);
}
break;
}
case 0x01C7: // UseDone: [errorType u32] — server finished an action
// (cast/use) with WeenieError.None(0) = completed, or an
// error (0x1D = YoureTooBusy). Read-only observation: bump
// a monotonic counter so the plugin can pace combat casts
// on real server completion instead of a blind interval.
// This is the authoritative ACE Player.IsBusy lifecycle
// signal — it never touches client m_cBusy.
{
uint err = size >= 8 ? unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 4))) : 0;
int seq = System.Threading.Interlocked.Increment(ref _useDoneSeq);
if (_useDoneLogCount < 25)
{
_useDoneLogCount++;
RynthLog.Compat($"UseDone seq={seq} err=0x{err:X}");
}
break;
}
}
}
// Monotonic count of inbound UseDone (0x1C7) events. The plugin records this
// at cast time and re-reads it to detect the server finishing the cast.
private static int _useDoneSeq;
private static int _useDoneLogCount;
public static int GetUseDoneSeq() => System.Threading.Volatile.Read(ref _useDoneSeq);
// AttackerNotification (0x01B1) / DefenderNotification (0x01B2). Payload at
// data+4: string16 name, u32 damageType, f64 percent, u32 damage,
// [u32 damageLocation (defender only),] u32 crit, …. Read-only byte math.
private static void ParseGameEventDamage(uint eventType, IntPtr data, uint size)
{
if (size < 24) return;
bool attacker = eventType == 0x01B1;
int nameLen = (ushort)Marshal.ReadInt16(IntPtr.Add(data, 4));
int strBlock = ((2 + nameLen + 3) / 4) * 4; // u16 len + chars, padded to a multiple of 4
int off = 4 + strBlock; // → damageType
int critOff = off + (attacker ? 16 : 20); // type(4)+percent(8)+damage(4)[+dmgLoc(4)]
if (critOff + 4 > size) return;
uint damageType = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, off)));
uint damage = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, off + 12)));
uint crit = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, critOff)));
if (damage == 0 || damage > 1_000_000) return;
if (_damageEventLogCount < 12)
{
_damageEventLogCount++;
RynthLog.Compat($"Combat: damage evt 0x{eventType:X3} dmg={damage} crit={crit} atk={attacker} len={size}");
}
PluginManager.QueueCombatDamage(damage, damageType, crit != 0, attacker);
}
private static SmartBoxEventInfo ReadSmartBoxEventInfo(IntPtr blob)
{
if (blob == IntPtr.Zero)
return default;
try
{
uint blobSize = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(blob, NetBlobBufSizeOffset)));
if (blobSize < sizeof(uint))
return new SmartBoxEventInfo(0, 0, blobSize);
IntPtr payloadPtr = Marshal.ReadIntPtr(IntPtr.Add(blob, NetBlobBufPtrOffset));
if (payloadPtr == IntPtr.Zero)
return new SmartBoxEventInfo(0, 0, blobSize);
uint opcode = unchecked((uint)Marshal.ReadInt32(payloadPtr));
uint rawObjectId = blobSize >= 8
? unchecked((uint)Marshal.ReadInt32(IntPtr.Add(payloadPtr, sizeof(uint))))
: 0;
return new SmartBoxEventInfo(opcode, rawObjectId, blobSize);
}
catch
{
return default;
}
}
private static void TryQueueHealthUpdate(IntPtr blob, SmartBoxEventInfo info)
{
if (info.Opcode != 0x01C0 || info.BlobSize < 12 || blob == IntPtr.Zero)
return;
try
{
IntPtr payloadPtr = Marshal.ReadIntPtr(IntPtr.Add(blob, NetBlobBufPtrOffset));
if (payloadPtr == IntPtr.Zero)
return;
uint targetId = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(payloadPtr, 4)));
float ratio = Marshal.PtrToStructure<float>(IntPtr.Add(payloadPtr, 8));
uint maxHealth = 0;
uint currentHealth = 0;
// Appraisal-only: emit an absolute health pair ONLY from a real
// appraisal's wire-parsed CreatureProfile (id-keyed). With no
// appraisal, leave max=0 so the UI falls back to a % — the
// pointer-cache and creature Inq maxes are unreliable on ACE and
// fabricated wildly wrong values (e.g. 50/50 for a 190-hp mob).
if (ObjectQualityCache.TryGetCreatureVitals(targetId, out CreatureVitals exact) && exact.MaxHealth > 0)
{
maxHealth = exact.MaxHealth;
currentHealth = (uint)Math.Round(maxHealth * Math.Clamp(ratio, 0f, 1f));
}
PluginManager.QueueUpdateHealth(targetId, ratio, currentHealth, maxHealth);
}
catch
{
}
}
private static int _damageEventLogCount;
// AttackerNotification (0x01B1, you hit) / DefenderNotification (0x01B2, you're
// hit) carry the EXACT per-hit damage + crit — the only client-side source of
// real damage numbers (chat is flavor text; health deltas miss one-shots).
// These arrive as GameEvents whose blob envelope is
// [recipientId][sequence][eventType][payload] (eventType at +8), while
// SmartBox-dispatched events put eventType at +0. Detect the eventType at
// either offset, then parse the payload that follows:
// string16 name (u16 charCount + cp1252 1-byte chars, padded so (2+len)%4==0)
// u32 damageType, f64 percent, u32 damage, [u32 damageLocation (defender),]
// u32 crit, u64 attackConditions
// Pure read-only byte math (no allocation) to stay detour-safe.
private static void TryQueueDamageEvent(IntPtr blob, SmartBoxEventInfo info)
{
if (blob == IntPtr.Zero || info.BlobSize < 24)
return;
try
{
IntPtr payloadPtr = Marshal.ReadIntPtr(IntPtr.Add(blob, NetBlobBufPtrOffset));
if (payloadPtr == IntPtr.Zero)
return;
uint et0 = unchecked((uint)Marshal.ReadInt32(payloadPtr));
uint et8 = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(payloadPtr, 8)));
int nameOff;
uint eventType;
if (et0 == 0x01B1 || et0 == 0x01B2) { eventType = et0; nameOff = 4; } // SmartBox-style
else if (et8 == 0x01B1 || et8 == 0x01B2) { eventType = et8; nameOff = 12; } // GameEvent envelope
else return;
bool attacker = eventType == 0x01B1;
int nameLen = (ushort)Marshal.ReadInt16(IntPtr.Add(payloadPtr, nameOff));
int strBlock = ((2 + nameLen + 3) / 4) * 4; // u16 len + chars, padded to a multiple of 4
int off = nameOff + strBlock; // → damageType
int critOff = off + (attacker ? 16 : 20); // type(4)+percent(8)+damage(4)[+dmgLoc(4)]
if (critOff + 4 > info.BlobSize)
return;
uint damageType = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(payloadPtr, off)));
uint damage = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(payloadPtr, off + 12)));
uint crit = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(payloadPtr, critOff)));
if (damage == 0 || damage > 1_000_000)
return;
if (_damageEventLogCount < 12)
{
_damageEventLogCount++;
RynthLog.Compat($"Combat: damage evt 0x{eventType:X3} nameOff={nameOff} dmg={damage} crit={crit} atk={attacker} blob={info.BlobSize}");
}
PluginManager.QueueCombatDamage(damage, damageType, crit != 0, attacker);
}
catch
{
}
}
private static int _killNotifyLogCount;
// KillerNotification (0x01AD) is sent to the player ONLY when they kill
// something, at the lethal hit — before the death animation plays out and
// the creature reclassifies to a corpse. That makes it the EARLIEST
// reliable "target dead" signal: the health=0 update and the Monster->Corpse
// flip both land at/after the corpse swap (ACE delays CreateCorpse by the
// full death-animation length), so combat that paces on those would burn a
// second full cast at an already-dead mob. Payload is a single string16 —
// the formatted death message with the victim name embedded; there is NO
// object id (GameEventKillerNotification just WriteString16L's the text).
// We forward the string so the plugin can match it against its one active
// target by name. Same envelope ambiguity as the damage events: eventType
// at +0 (SmartBox-style) or +8 (GameEvent envelope); the string16 follows
// immediately after the eventType u32.
private static void TryQueueKillNotification(IntPtr blob, SmartBoxEventInfo info)
{
if (blob == IntPtr.Zero || info.BlobSize < 6)
return;
try
{
IntPtr payloadPtr = Marshal.ReadIntPtr(IntPtr.Add(blob, NetBlobBufPtrOffset));
if (payloadPtr == IntPtr.Zero)
return;
uint et0 = unchecked((uint)Marshal.ReadInt32(payloadPtr));
uint et8 = info.BlobSize >= 12 ? unchecked((uint)Marshal.ReadInt32(IntPtr.Add(payloadPtr, 8))) : 0;
int strOff;
if (et0 == 0x01AD) strOff = 4; // SmartBox-style: eventType at +0
else if (et8 == 0x01AD) strOff = 12; // GameEvent envelope: eventType at +8
else return;
string? deathMessage = ReadString16Latin1(payloadPtr, strOff, info.BlobSize);
if (string.IsNullOrEmpty(deathMessage))
return;
if (_killNotifyLogCount < 12)
{
_killNotifyLogCount++;
RynthLog.Compat($"Combat: kill notify strOff={strOff} blob={info.BlobSize} msg='{deathMessage}'");
}
PluginManager.QueueKillNotification(deathMessage);
}
catch
{
}
}
// Reads an AC string16 (u16 char count + that many 1-byte cp1252 chars) at
// the given payload offset, bounded by the blob size. Returns null on a
// missing/oversize length so a corrupt field can't allocate wildly inside
// this main-thread detour. High bytes are taken as Latin-1 (monster names
// are ASCII in practice). One small string alloc per kill — the same
// pattern ChatCallbackHooks already uses for inbound chat capture.
private static string? ReadString16Latin1(IntPtr payloadPtr, int off, uint blobSize)
{
if (off < 0 || off + 2 > blobSize) return null;
int len = (ushort)Marshal.ReadInt16(IntPtr.Add(payloadPtr, off));
if (len <= 0 || len > 256) return null;
if (off + 2 + len > blobSize) return null;
Span<char> chars = stackalloc char[len];
for (int i = 0; i < len; i++)
chars[i] = (char)Marshal.ReadByte(IntPtr.Add(payloadPtr, off + 2 + i));
return new string(chars);
}
// ── RE instrumentation (TEMPORARY) ───────────────────────────────────
// Diagnose why combat GameEvents (damage 0x1B1/2, kill 0x1AC/AD, health
// 0x1C0) don't reach the parsers on the user's Decal-coexistence client.
// Logs three things, all capped: (1) detour ALIVE + busyness — proves the
// hook fires and isn't on the wrong function; (2) any combat-range event's
// first dwords (COMBAT) so we see the opcode + envelope offset; (3) for the
// game-event detour, the first 30 events unfiltered (GE-ANY) so structure is
// visible even if the opcode sits at an unexpected offset. Remove once fixed.
private static int _geFire, _sbFire, _geCombat, _sbCombat, _geAny;
private static unsafe void DiagEvent(string tag, bool isGe, IntPtr blob, SmartBoxEventInfo info)
{
int fired = isGe ? ++_geFire : ++_sbFire;
if (fired == 1 || fired == 50 || fired % 500 == 0)
RynthLog.Compat($"{tag}-ALIVE fired={fired} lastOp=0x{info.Opcode:X4} blob={info.BlobSize}");
if (blob == IntPtr.Zero || info.BlobSize < 4)
return;
try
{
IntPtr p = Marshal.ReadIntPtr(IntPtr.Add(blob, NetBlobBufPtrOffset));
if (p == IntPtr.Zero)
return;
uint sz = info.BlobSize;
uint et0 = unchecked((uint)Marshal.ReadInt32(p));
uint w1 = sz >= 8 ? unchecked((uint)Marshal.ReadInt32(IntPtr.Add(p, 4))) : 0;
uint et8 = sz >= 12 ? unchecked((uint)Marshal.ReadInt32(IntPtr.Add(p, 8))) : 0;
uint w3 = sz >= 16 ? unchecked((uint)Marshal.ReadInt32(IntPtr.Add(p, 12))) : 0;
uint w4 = sz >= 20 ? unchecked((uint)Marshal.ReadInt32(IntPtr.Add(p, 16))) : 0;
bool combat = (et0 >= 0x0180 && et0 <= 0x01E0) || (et8 >= 0x0180 && et8 <= 0x01E0);
if (combat)
{
ref int c = ref (isGe ? ref _geCombat : ref _sbCombat);
if (c < 50)
{
c++;
RynthLog.Compat($"{tag}-COMBAT sz={sz} w=[{et0:X8} {w1:X8} {et8:X8} {w3:X8} {w4:X8}]");
}
}
else if (isGe && _geAny < 30)
{
_geAny++;
RynthLog.Compat($"GE-ANY sz={sz} w=[{et0:X8} {w1:X8} {et8:X8} {w3:X8} {w4:X8}]");
}
}
catch { }
}
// WireParseIdentifyFromBlob / TryCacheVitalsFromIdentify removed 2026-05-18:
// calling CombatActionHooks.TryParseIdentifyResponse from an [UnmanagedCallersOnly]
// detour on AC's main thread triggers ObjectQualityCache dictionary growth
// (allocation) for each newly-identified mob → GC during the reverse-P/Invoke
// transition → RhpReversePInvokeAttachOrTrapThread2 STATUS_FAIL_FAST (silent
// process death, no dialog). Mob health display falls back to ratio (%) mode;
// absolute values can be restored via a pre-allocated pump-thread ring buffer.
private readonly record struct SmartBoxEventInfo(uint Opcode, uint RawObjectId, uint BlobSize);
}

View file

@ -0,0 +1,355 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace RynthCore.Engine.Compatibility;
internal static class SmartBoxLocator
{
public const int SmartBoxCmdInterpOffset = 0xB8;
public const int SmartBoxPlayerIdOffset = 0xF4;
public const int SmartBoxPlayerOffset = 0xF8;
private static IntPtr _smartboxStaticAddr;
private static IntPtr _moduleBase;
private static int _imageSize;
private static readonly List<IntPtr> _smartboxStaticCandidates = [];
private static string _statusMessage = "Not probed yet.";
// ─── VirtualQuery-based memory validation ────────────────────────────
[DllImport("kernel32.dll", SetLastError = false)]
private static extern int VirtualQuery(IntPtr lpAddress, out MEMORY_BASIC_INFORMATION lpBuffer, int dwLength);
[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 = 0x1000;
private const uint PAGE_NOACCESS = 0x01;
private const uint PAGE_GUARD = 0x100;
private const uint READABLE_MASK = 0x02 | 0x04 | 0x08 | 0x20 | 0x40 | 0x80;
/// <summary>
/// Checks whether the given memory range is committed and readable without triggering an AV.
/// Uses VirtualQuery — safe to call on any address including unmapped pages.
/// Critical for NativeAOT where AccessViolationException cannot be caught.
/// </summary>
public static bool IsMemoryReadable(IntPtr address, int size)
{
if (address == IntPtr.Zero || size <= 0)
return false;
if (VirtualQuery(address, out MEMORY_BASIC_INFORMATION mbi,
Marshal.SizeOf<MEMORY_BASIC_INFORMATION>()) == 0)
return false;
if (mbi.State != MEM_COMMIT)
return false;
if ((mbi.Protect & PAGE_NOACCESS) != 0)
return false;
if ((mbi.Protect & PAGE_GUARD) != 0)
return false;
if ((mbi.Protect & READABLE_MASK) == 0)
return false;
// Ensure the committed region covers the full requested range.
// Deep-audit finding #32 (2026-06-18): this used signed 32-bit
// arithmetic (ToInt32()) — acclient.exe is LARGE_ADDRESS_AWARE so
// addresses above 0x7FFFFFFF are reachable, and ToInt32() on those
// can wrap. Do the comparison in 64-bit (every caller passes a small
// compile-time size, so no overflow risk on that side).
long regionEnd = mbi.BaseAddress.ToInt64() + mbi.RegionSize.ToInt64();
long requestEnd = address.ToInt64() + size;
return requestEnd <= regionEnd;
}
public static bool IsInitialized { get; private set; }
public static int CandidateCount => _smartboxStaticCandidates.Count;
public static string StatusMessage => _statusMessage;
public static bool Probe()
{
Reset();
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
{
_statusMessage = "acclient.exe not available.";
return false;
}
try
{
_moduleBase = textSection.ModuleBase;
_imageSize = textSection.ImageSize;
CollectSmartBoxCandidates(textSection.Bytes, textSection.TextBaseVa, textSection.ModuleBase.ToInt32());
if (_smartboxStaticCandidates.Count == 0)
{
_statusMessage = "SmartBox::smartbox static not found.";
RynthLog.Compat("Compat: smartbox locator probe failed - SmartBox::smartbox static not found.");
return false;
}
_smartboxStaticAddr = _smartboxStaticCandidates[0];
IsInitialized = true;
_statusMessage = "Ready.";
return true;
}
catch (Exception ex)
{
Reset();
_statusMessage = ex.Message;
RynthLog.Compat($"Compat: smartbox locator probe failed - {ex.Message}");
return false;
}
}
public static bool TryGetSmartBox(out IntPtr smartBox, out IntPtr smartboxStaticAddr, out string failure)
{
smartBox = IntPtr.Zero;
smartboxStaticAddr = IntPtr.Zero;
failure = string.Empty;
if ((!IsInitialized || _smartboxStaticCandidates.Count == 0) && !Probe())
{
failure = _statusMessage;
return false;
}
foreach (IntPtr candidate in EnumerateCandidates())
{
try
{
IntPtr resolved = Marshal.ReadIntPtr(candidate);
if (resolved == IntPtr.Zero)
{
failure = "SmartBox instance not ready.";
continue;
}
IntPtr vtable = Marshal.ReadIntPtr(resolved);
if (!IsPointerInModule(vtable))
{
failure = $"SmartBox vtable looks invalid (0x{vtable.ToInt32():X8}).";
continue;
}
smartBox = resolved;
smartboxStaticAddr = candidate;
_smartboxStaticAddr = candidate;
return true;
}
catch (Exception ex)
{
failure = ex.Message;
}
}
if (string.IsNullOrEmpty(failure))
failure = "SmartBox instance not ready.";
return false;
}
public static bool TryGetPlayer(out IntPtr player, out uint playerId, out string failure)
{
player = IntPtr.Zero;
playerId = 0;
if (!TryGetSmartBox(out IntPtr smartBox, out _, out failure))
return false;
try
{
player = Marshal.ReadIntPtr(smartBox + SmartBoxPlayerOffset);
playerId = unchecked((uint)Marshal.ReadInt32(smartBox + SmartBoxPlayerIdOffset));
if (player == IntPtr.Zero)
{
failure = playerId != 0
? $"Player pointer not ready (playerId=0x{playerId:X8})."
: "Player pointer not ready.";
return false;
}
IntPtr vtable = Marshal.ReadIntPtr(player);
if (!IsPointerInModule(vtable))
{
failure = $"Player vtable looks invalid (0x{vtable.ToInt32():X8}).";
return false;
}
return true;
}
catch (Exception ex)
{
failure = ex.Message;
return false;
}
}
public static bool IsPointerInModule(IntPtr ptr)
{
if (ptr == IntPtr.Zero || _moduleBase == IntPtr.Zero || _imageSize <= 0)
return false;
int value = ptr.ToInt32();
int start = _moduleBase.ToInt32();
int end = start + _imageSize;
return value >= start && value < end;
}
private static IEnumerable<IntPtr> EnumerateCandidates()
{
if (_smartboxStaticAddr != IntPtr.Zero)
yield return _smartboxStaticAddr;
foreach (IntPtr candidate in _smartboxStaticCandidates)
{
if (candidate == _smartboxStaticAddr)
continue;
yield return candidate;
}
}
private static void CollectSmartBoxCandidates(byte[] text, int textBaseVa, int imageBase)
{
_smartboxStaticCandidates.Clear();
HashSet<int> seen = [];
AddCandidates(FindCmdInterpReferenceCandidates(text, imageBase), seen);
AddCandidates(FindCleanupPatternCandidates(text, textBaseVa, imageBase), seen);
}
private static void AddCandidates(IEnumerable<IntPtr> candidates, HashSet<int> seen)
{
foreach (IntPtr candidate in candidates)
{
int value = candidate.ToInt32();
if (value == 0 || !seen.Add(value))
continue;
_smartboxStaticCandidates.Add(candidate);
}
}
private static IEnumerable<IntPtr> FindCleanupPatternCandidates(byte[] text, int textBaseVa, int imageBase)
{
int dataLo = imageBase + 0x400000;
int dataHi = imageBase + 0x510000;
for (int i = 0; i < text.Length - 12; i++)
{
if (text[i] != 0xC7 || text[i + 1] != 0x05)
continue;
int addr = BitConverter.ToInt32(text, i + 2);
if (addr < dataLo || addr > dataHi)
continue;
if (BitConverter.ToInt32(text, i + 6) != 0 || text[i + 10] != 0xC3)
continue;
byte[] loadPat = new byte[5];
loadPat[0] = 0xA1;
BitConverter.GetBytes(addr).CopyTo(loadPat, 1);
for (int back = 5; back < 40; back++)
{
int j = i - back;
if (j < 0)
break;
if (!PatternScanner.VerifyBytes(text, j, loadPat))
continue;
for (int k = j + 5; k < j + 10 && k < text.Length - 1; k++)
{
if (text[k] != 0x85 || text[k + 1] != 0xC0)
continue;
bool hasDtorCall = false;
for (int m = k; m < i - 2 && m < text.Length - 3; m++)
{
if (text[m] == 0x6A && text[m + 1] == 0x01 &&
text[m + 2] == 0xFF && text[m + 3] == 0x10)
{
hasDtorCall = true;
break;
}
}
if (hasDtorCall)
{
yield return new IntPtr(addr);
break;
}
}
}
}
}
private static IEnumerable<IntPtr> FindCmdInterpReferenceCandidates(byte[] text, int imageBase)
{
int dataLo = imageBase + 0x400000;
int dataHi = imageBase + 0x510000;
for (int i = 0; i < text.Length - 24; i++)
{
if (text[i] != 0xA1)
continue;
int addr = BitConverter.ToInt32(text, i + 1);
if (addr < dataLo || addr > dataHi)
continue;
bool hasNullCheck = false;
for (int k = i + 5; k < i + 10 && k < text.Length - 1; k++)
{
if (text[k] == 0x85 && text[k + 1] == 0xC0)
{
hasNullCheck = true;
break;
}
}
if (!hasNullCheck)
continue;
for (int k = i + 5; k < i + 24 && k < text.Length - 6; k++)
{
if (text[k] != 0x8B)
continue;
byte modrm = text[k + 1];
if ((modrm & 0xC7) != 0x80)
continue;
if (BitConverter.ToInt32(text, k + 2) != SmartBoxCmdInterpOffset)
continue;
yield return new IntPtr(addr);
break;
}
}
}
private static void Reset()
{
_smartboxStaticAddr = IntPtr.Zero;
_moduleBase = IntPtr.Zero;
_imageSize = 0;
_smartboxStaticCandidates.Clear();
IsInitialized = false;
_statusMessage = "Not probed yet.";
}
}

View file

@ -0,0 +1,83 @@
// ============================================================================
// RynthCore.Engine - Compatibility/SmartBoxSetStateHooks.cs
//
// Hooks SmartBox::HandleSetState to track per-object physics state changes.
// When the server sends a SetState blob for a world object, this function is
// called with the object ID and new PhysicsState bitfield — giving us both
// without any reverse-pointer lookup.
//
// VA derivation (from Chorizite SmartBox.cs .text address):
// .text:004533E0 SmartBox::HandleSetState → 0x004533E0
// enum_Entrypoint: 0x00453420 (jmp stub — do NOT hook this one)
//
// Signature (Chorizite):
// NetBlobProcessedStatus __thiscall SmartBox::HandleSetState(
// SmartBox *this, NetBlob *blob, unsigned int object_id,
// unsigned int new_state, PhysicsTimestampPack *timestamps)
// ============================================================================
using System;
using System.Collections.Concurrent;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
namespace RynthCore.Engine.Compatibility;
internal static class SmartBoxSetStateHooks
{
// .text address of SmartBox::HandleSetState
private const int HandleSetStateVa = 0x004533E0;
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate uint HandleSetStateDelegate(
IntPtr thisPtr, IntPtr blobPtr, uint objectId, uint newState, IntPtr timestampsPtr);
private static HandleSetStateDelegate? _originalHandleSetState;
private static HandleSetStateDelegate? _handleSetStateDetour;
private static bool _hookInstalled;
private static string _statusMessage = "Not initialized.";
// Per-object last-known physics state.
private static readonly ConcurrentDictionary<uint, uint> _objectState = new();
// Debug: log first N calls
private static int _debugLogCount;
public static bool IsInstalled => _hookInstalled;
public static string StatusMessage => _statusMessage;
public static void Initialize()
{
// VA 0x004533E0 was found to land mid-function in this binary (firstByte=0xCF).
// Physics state is now read directly from CPhysicsObj+0xA8 via TryGetObjectPhysicsState.
// Hook not installed; TryGetObjectState remains available for future use.
_statusMessage = "Disabled — using direct CPhysicsObj state read instead.";
RynthLog.Verbose("Compat: smartbox-setstate hook skipped — direct read via CPhysicsObj+0xA8 in use.");
}
/// <summary>
/// Returns the last physics state received from the server for this object.
/// Returns false if no SetState has been seen for this object since injection.
/// </summary>
public static bool TryGetObjectState(uint objectId, out uint state)
{
return _objectState.TryGetValue(objectId, out state);
}
private static uint HandleSetStateDetour(
IntPtr thisPtr, IntPtr blobPtr, uint objectId, uint newState, IntPtr timestampsPtr)
{
try
{
_objectState[objectId] = newState;
int n = Interlocked.Increment(ref _debugLogCount);
if (n <= 60)
RynthLog.Verbose($"SetState#{n} obj=0x{objectId:X8} state=0x{newState:X8}");
}
catch { }
return _originalHandleSetState!(thisPtr, blobPtr, objectId, newState, timestampsPtr);
}
}

View file

@ -0,0 +1,108 @@
using System;
using System.Collections.Generic;
using System.IO;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// On startup, reads a user-editable file at
/// <c>%APPDATA%\RynthCore\string_anchors.txt</c> and, for each non-blank /
/// non-comment line, runs <see cref="StringRefScanner.DumpStringAnchors"/>.
///
/// Workflow for figuring out which function a string anchors:
/// 1. Pick a candidate string you think might live in AC's body for a
/// function you want to hook (e.g. "ClientMagicSystem::CastSpell",
/// "Combat::CastSpell"). One per line in the file.
/// 2. Launch any RynthCore-injected acclient.exe.
/// 3. Read the resulting Compat lines in <c>RynthCore.log</c>:
/// StringRef: '...' @ 0xVA — pushed by N site(s); function entries: 0x...
/// A single function entry means that string uniquely identifies that
/// function — wire it into the relevant hook as the anchor.
/// 4. Iterate the file until each function you care about has a unique
/// string anchor.
///
/// File format: one literal per line, blank lines and lines starting with
/// '#' are ignored. No quoting; everything between BOM-stripped start of
/// line and the trailing newline is the literal.
/// </summary>
internal static class StringAnchorDiagnostic
{
private static readonly byte[] CombatPrologue =
[0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8];
private static readonly byte[] GenericPrologue =
[0x55, 0x8B, 0xEC]; // push ebp; mov ebp, esp — wider net than CombatPrologue
public static string FilePath => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"RynthCore",
"string_anchors.txt");
public static void RunIfConfigured()
{
try
{
string path = FilePath;
if (!File.Exists(path))
return; // No file → no diagnostic; quiet.
string[] rawLines = File.ReadAllLines(path);
var literals = new List<string>(rawLines.Length);
foreach (string raw in rawLines)
{
string line = raw.Trim();
if (line.Length == 0) continue;
if (line.StartsWith('#')) continue;
literals.Add(line);
}
if (literals.Count == 0)
{
RynthLog.Compat($"StringAnchorDiagnostic: '{path}' has no candidate strings (all blank/comment).");
return;
}
if (!AcClientModule.TryReadTextSection(out AcClientTextSection module))
{
RynthLog.Compat("StringAnchorDiagnostic: acclient.exe not readable, skipping.");
return;
}
// One-time per-process dump of every ASCII string ≥ 8 chars in
// the image. Lives next to engine.json so the user (or this
// engine on next launch) can grep it for real anchor candidates
// when guessing fails. Cheap (~1s) and read-only.
string dumpPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"RynthCore",
"acclient_strings.txt");
try
{
StringRefScanner.DumpAllStrings(module, dumpPath, minLength: 8);
}
catch (Exception ex)
{
RynthLog.Compat($"StringAnchorDiagnostic: string dump failed — {ex.GetType().Name}: {ex.Message}");
}
RynthLog.Compat($"StringAnchorDiagnostic: scanning {literals.Count} candidate string(s) against acclient.exe ({module.Bytes.Length:X} bytes).");
// Try the tight CombatPrologue first (matches the same prologue
// pattern the existing pattern scans use, so anchor results are
// directly comparable to what _castSpell etc. would bind to).
RynthLog.Compat("StringAnchorDiagnostic: --- pass 1: CombatPrologue (83 EC 0C 53 56 57 E8) ---");
StringRefScanner.DumpStringAnchors(module, literals, CombatPrologue);
// Then a generic push-ebp prologue. Many AC functions don't use
// the combat prologue — this widens the net.
RynthLog.Compat("StringAnchorDiagnostic: --- pass 2: generic prologue (55 8B EC push ebp; mov ebp, esp) ---");
StringRefScanner.DumpStringAnchors(module, literals, GenericPrologue);
RynthLog.Compat("StringAnchorDiagnostic: scan complete.");
}
catch (Exception ex)
{
RynthLog.Compat($"StringAnchorDiagnostic: failed — {ex.GetType().Name}: {ex.Message}");
}
}
}

View file

@ -0,0 +1,274 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Finds AC client functions by anchoring on string literals that those
/// functions push onto the stack (for printf/debug-trace/error messages).
///
/// Why this exists: the existing PatternScanner.FindPattern + FindPrologueBefore
/// approach matches on a generic 6-byte prologue (e.g. `83 EC 0C 53 56 57 E8`)
/// that dozens of functions share. On retail AC the body opcodes we anchor on
/// (`mov [edx], imm32`) happen to make the first match correct, but on ACE
/// rebuilds the same prologue matches a *different* function — leading to
/// `_castSpell` and `InstallInnerDispatcherHook` calling/hooking the wrong
/// function and AVing AC.
///
/// String references are far more discriminating: a string like
/// "Combat::CastSpell" is referenced by exactly one function (the one that
/// logs it on error), so finding the `push &string` site and walking back to
/// the function prologue gives a verifiable anchor.
///
/// Workflow:
/// 1. Identify a string that AC's target function pushes (run strings.exe
/// on acclient.exe, look for self-naming debug/error messages).
/// 2. Call FindFunctionsByStringRef("Combat::CastSpell", prologue).
/// 3. If exactly one match, that's the function. If multiple, narrow with
/// a second string or fall back to a body-pattern check.
/// 4. If zero matches, the string isn't present in this binary — the
/// caller should fall back to a pattern scan or refuse to bind.
/// </summary>
internal static class StringRefScanner
{
/// <summary>
/// Find the absolute VA of a NUL-terminated ASCII string literal inside
/// the loaded acclient.exe image window. Returns 0 if not present.
///
/// Note: <see cref="AcClientModule.TryReadTextSection"/> reads from
/// moduleBase+0x1000 to end-of-image, so the byte window covers .text
/// AND .rdata AND .data. String literals live in .rdata, which is
/// included.
/// </summary>
public static int FindStringVa(AcClientTextSection module, string literal)
{
if (string.IsNullOrEmpty(literal))
return 0;
byte[] needle = Encoding.ASCII.GetBytes(literal);
byte[] haystack = module.Bytes;
int max = haystack.Length - needle.Length - 1;
for (int i = 0; i <= max; i++)
{
// Match the literal exactly...
bool match = true;
for (int j = 0; j < needle.Length; j++)
{
if (haystack[i + j] != needle[j])
{
match = false;
break;
}
}
if (!match) continue;
// ...and require a NUL byte after it so we don't match a prefix
// of a longer string ("CastSpell" inside "CastSpellOnTarget").
if (haystack[i + needle.Length] != 0)
continue;
return module.TextBaseVa + i;
}
return 0;
}
/// <summary>
/// Find every `push imm32` instruction whose immediate equals
/// <paramref name="targetVa"/>. Opcode 0x68 + 4 little-endian bytes.
/// This is how MSVC-emitted C++ pushes a string literal address before
/// a printf-family call. Returns file offsets relative to
/// <c>module.TextBaseVa</c>.
/// </summary>
public static List<int> FindPushImm32Sites(AcClientTextSection module, int targetVa)
{
var sites = new List<int>();
byte b0 = (byte)(targetVa & 0xFF);
byte b1 = (byte)((targetVa >> 8) & 0xFF);
byte b2 = (byte)((targetVa >> 16) & 0xFF);
byte b3 = (byte)((targetVa >> 24) & 0xFF);
byte[] bytes = module.Bytes;
int max = bytes.Length - 5;
for (int i = 0; i < max; i++)
{
if (bytes[i] != 0x68) continue;
if (bytes[i + 1] != b0) continue;
if (bytes[i + 2] != b1) continue;
if (bytes[i + 3] != b2) continue;
if (bytes[i + 4] != b3) continue;
sites.Add(i);
}
return sites;
}
/// <summary>
/// Walk backward from <paramref name="siteOff"/> looking for the nearest
/// occurrence of <paramref name="prologue"/>. Returns the offset of the
/// matched prologue, or -1 if none found within <paramref name="maxBackward"/>.
///
/// Unlike PatternScanner.FindPrologueBefore which has its own search loop,
/// this version is intentionally local to a string-ref site so the
/// match window stays small and a global pattern can't accidentally
/// match a function far away.
/// </summary>
public static int FindFunctionEntryBefore(AcClientTextSection module, int siteOff, byte[] prologue, int maxBackward = 0x2000)
{
if (prologue.Length == 0)
return -1;
byte[] bytes = module.Bytes;
int floor = Math.Max(0, siteOff - maxBackward);
for (int i = siteOff; i >= floor; i--)
{
if (i + prologue.Length > bytes.Length)
continue;
bool match = true;
for (int j = 0; j < prologue.Length; j++)
{
if (bytes[i + j] != prologue[j])
{
match = false;
break;
}
}
if (match)
return i;
}
return -1;
}
/// <summary>
/// One-call helper: locate every function whose body pushes
/// <paramref name="literal"/>, by finding the string in the image,
/// finding every <c>push string_va</c> site, and walking back to the
/// nearest matching prologue.
///
/// Returns the set of absolute VAs of candidate function entries.
/// Caller should treat a single-result list as a hard match, and a
/// multi-result list as "needs more disambiguation."
/// </summary>
public static List<int> FindFunctionsByStringRef(
AcClientTextSection module,
string literal,
byte[] prologue,
int maxBackward = 0x2000)
{
var hits = new HashSet<int>();
int stringVa = FindStringVa(module, literal);
if (stringVa == 0)
return new List<int>();
foreach (int site in FindPushImm32Sites(module, stringVa))
{
int funcOff = FindFunctionEntryBefore(module, site, prologue, maxBackward);
if (funcOff >= 0)
hits.Add(module.TextBaseVa + funcOff);
}
return new List<int>(hits);
}
/// <summary>
/// Walks the loaded image and writes every printable ASCII run of at
/// least <paramref name="minLength"/> bytes (terminated by NUL or any
/// non-printable byte) to <paramref name="outputPath"/>, one per line,
/// in the form: <c>0xVA\ttext</c>.
///
/// This is the catalog the user (or a future automated anchor picker)
/// greps for real anchors. AC client release builds tend to strip
/// __FUNCTION__-style debug names but keep user-facing strings, format
/// strings, RTTI type descriptors (".?AVClassName@@"), and file paths
/// (when assertions or trace macros remained) — those are the real
/// hooks for string anchoring.
/// </summary>
public static void DumpAllStrings(AcClientTextSection module, string outputPath, int minLength = 8)
{
byte[] bytes = module.Bytes;
int baseVa = module.TextBaseVa;
using var sw = new System.IO.StreamWriter(outputPath, append: false, encoding: System.Text.Encoding.UTF8);
sw.WriteLine($"# acclient.exe ASCII string dump — base VA 0x{baseVa:X8}, size 0x{bytes.Length:X}, minLength={minLength}");
sw.WriteLine("# Each line: <hex VA><TAB><string>");
int i = 0;
int written = 0;
while (i < bytes.Length)
{
byte b = bytes[i];
if (b < 0x20 || b > 0x7E)
{
i++;
continue;
}
int start = i;
while (i < bytes.Length)
{
byte c = bytes[i];
if (c < 0x20 || c > 0x7E)
break;
i++;
}
int len = i - start;
if (len >= minLength)
{
int va = baseVa + start;
// ASCII-only payload, safe to convert via Encoding.ASCII.
string text = System.Text.Encoding.ASCII.GetString(bytes, start, len);
sw.Write("0x");
sw.Write(va.ToString("X8"));
sw.Write('\t');
sw.WriteLine(text);
written++;
}
}
RynthLog.Compat($"StringRef: dumped {written} string(s) of length>={minLength} to '{outputPath}'.");
}
/// <summary>
/// Diagnostic: log every string in <paramref name="literals"/> with the
/// VA we found it at, plus every push site for that string, plus the
/// nearest enclosing function entry. Useful for hand-calibration: run
/// this once with a list of candidate strings and read the log to see
/// which strings uniquely identify which functions.
/// </summary>
public static void DumpStringAnchors(AcClientTextSection module, IEnumerable<string> literals, byte[] prologue)
{
foreach (string literal in literals)
{
int va = FindStringVa(module, literal);
if (va == 0)
{
RynthLog.Compat($"StringRef: '{literal}' — NOT FOUND in image.");
continue;
}
List<int> sites = FindPushImm32Sites(module, va);
if (sites.Count == 0)
{
RynthLog.Compat($"StringRef: '{literal}' @ 0x{va:X8} — string exists but no `push imm32` site references it (may be loaded by `mov reg, imm32` or stored in vtable).");
continue;
}
var funcs = new HashSet<int>();
foreach (int site in sites)
{
int funcOff = FindFunctionEntryBefore(module, site, prologue);
if (funcOff >= 0)
funcs.Add(module.TextBaseVa + funcOff);
}
string fnList;
if (funcs.Count == 0)
{
fnList = "(no enclosing prologue match)";
}
else
{
var parts = new List<string>(funcs.Count);
foreach (int v in funcs) parts.Add($"0x{v:X8}");
fnList = string.Join(", ", parts);
}
RynthLog.Compat($"StringRef: '{literal}' @ 0x{va:X8} — pushed by {sites.Count} site(s); function entries: {fnList}");
}
}
}

View file

@ -0,0 +1,79 @@
using System;
using System.Runtime.InteropServices;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Reads portal/teleport state directly from CPlayerSystem::teleport_in_progress.
///
/// Ghidra analysis of CPlayerSystem::SetTeleportInProgress (0x0055E2A0):
/// MOV AL, [ESP+4] ; bool arg
/// MOV [ESI + 0x238], AL ; stored at this+0x238
///
/// So: isPortaling = *(CPlayerSystem + 0x238)
/// PlayerSystem singleton pointer: 0x0087119C (PlayerSystemVa, already known)
/// </summary>
internal static class TeleportStateHooks
{
private const int PlayerSystemPtrVa = 0x0087119C;
private const int TeleportInProgressOffset = 0x238;
// Phase B: resolve CPlayerSystem's address by code-xref (mov dword [CPlayerSystem],0 =
// C7 05 <addr> 00 00 00 00), operand at offset 2; the VA stays as fallback.
private static readonly byte?[] PatXrefPlayerSystem = [ 0xC7, 0x05, null, null, null, null, 0x00, 0x00, 0x00, 0x00, 0x83, 0xC6 ];
private static int _playerSystemPtrAddr = PlayerSystemPtrVa;
public static bool IsInstalled => true; // no hook needed — direct memory read
// Deep-audit finding #14 (2026-06-18): this raw-dereferenced CPlayerSystem
// unconditionally, including off AC's main thread — exposed to plugins via
// RynthCoreHost.IsPortaling() and polled constantly (NavigationEngine /
// RadarWallRenderer / NavMarkerRenderer / ExpressionEngine), some of which
// run on the Decal-coexistence pump thread. During relog/teleport teardown
// the singleton can be non-null but freed/mid-reassignment — an off-thread
// read of that is an uncatchable AV under NativeAOT (a null check alone
// doesn't protect against it). Gate to the main thread; off-thread callers
// get the last main-thread-observed value instead of touching AC memory.
private static volatile bool _cachedIsPortaling;
/// <summary>Returns true while the player is in the teleport/portal transit state.</summary>
public static unsafe bool IsPortaling
{
get
{
if (!MainThreadGuard.IsOnMainThread())
return _cachedIsPortaling;
try
{
IntPtr playerSystemAddr = (IntPtr)_playerSystemPtrAddr;
if (!ClientObjectHooks.IsReadablePointer(playerSystemAddr))
return _cachedIsPortaling;
IntPtr playerSystem = *(IntPtr*)_playerSystemPtrAddr;
if (playerSystem == IntPtr.Zero)
{
_cachedIsPortaling = false;
return false;
}
IntPtr flagAddr = playerSystem + TeleportInProgressOffset;
if (!ClientObjectHooks.IsReadablePointer(flagAddr))
return _cachedIsPortaling;
bool result = *(byte*)flagAddr != 0;
_cachedIsPortaling = result;
return result;
}
catch
{
return _cachedIsPortaling;
}
}
}
// Called from EntryPoint.Initialize chain — nothing to install for a direct read.
public static void Initialize()
{
if (AcClientModule.TryReadTextSection(out AcClientTextSection text))
_playerSystemPtrAddr = HookResolver.ResolveData(text, "Teleport.CPlayerSystem", PatXrefPlayerSystem, 2, PlayerSystemPtrVa).Address.ToInt32();
RynthLog.Verbose($"Compat: teleport-state ready — direct read CPlayerSystem+0x238 @ PlayerSystemPtr=0x{_playerSystemPtrAddr:X8}");
}
}

View file

@ -0,0 +1,124 @@
using System;
using System.Threading;
using RynthCore.Engine.Hooking;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Installs a NATIVE null-guard on AC's tagged-text parser consumer
/// <c>FUN_0067D3C0</c> (live VA 0x0067D3C0) to kill the text-parser singleton
/// race AV.
///
/// Crash this fixes (captured 2026-06-03, native-crash.log):
/// <code>
/// code=0xC0000005 exAddr=acclient.exe+0x0027D3DA (live 0x0067D3DA) eax=0
/// 0067d3da MOV EDI,[EAX+0xC] ; EAX = parser context = 0 -> AV READ [null+0xC]
/// </code>
/// The parser context comes from the unsynchronized singleton DAT_008F881C.
/// When our off-thread plugin pump triggers a text-generation path while AC's
/// main thread is mid-parse on incoming chat (heavy Olthoi-hive combat chat),
/// the singleton races to null and this consumer dereferences it.
///
/// ⚠ This guard MUST be native. A MANAGED MinHook detour here was deployed
/// 2026-05-25 and crashed pid 20852 within ~7s: the consumer is called by AC's
/// main thread for EVERY parsed tag, so a managed detour incurs a NativeAOT
/// reverse-P/Invoke transition per tag and fail-fasts. The detour body now lives
/// entirely in RynthCore.SehTrampoline.dll (RC_TagParserGuard — pure native, no
/// managed transition). This class just installs the MinHook redirect to that
/// native detour and hands it the trampoline (original) BEFORE enabling. If the
/// parser context is null the native guard drops one parse run (returns 0); the
/// caller (FUN_0067E150) discards the return value, so that is safe.
/// </summary>
internal static class TextParserGuardHooks
{
// FUN_0067D3C0 in retail/ACE acclient.exe (byte-identical; verified at install).
private const int TargetVa = 0x0067D3C0;
// Prologue from the function start, including the literal data pointer 0x007FF308
// (bytes 5-9) — stable across retail/ACE — which makes this a strong validation
// signature. Verified unique + lands at 0x0067D3C0 offline (tools/pe_pattern.py).
private static readonly byte?[] FuncPattern =
[
0x83, 0xEC, 0x50, // SUB ESP, 0x50
0x53, // PUSH EBX
0x55, // PUSH EBP
0xB8, 0x08, 0xF3 // MOV EAX, 0x7FF308 (low bytes)
];
private static IntPtr _targetAddress;
private static int _installed;
private static string _statusMessage = "Not probed yet.";
public static bool IsInstalled => Volatile.Read(ref _installed) != 0;
public static string StatusMessage => _statusMessage;
/// <summary>Null-context parse runs the native guard has dropped (served from the
/// trampoline DLL; 0 if unavailable).</summary>
public static uint NullParamSkipCount => SehTrampoline.TagParserSkipCount;
public static void Initialize()
{
if (Interlocked.CompareExchange(ref _installed, 1, 0) != 0)
return;
// The detour body lives in the trampoline DLL; without it we cannot install a
// native guard, and we must NOT fall back to a managed detour (the 7s-crash).
if (!SehTrampoline.IsAvailable)
{
Volatile.Write(ref _installed, 0);
_statusMessage = "SEH trampoline unavailable.";
RynthLog.Compat("Compat: text-parser guard NOT installed — SEH trampoline unavailable (no managed fallback by design).");
return;
}
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
{
Volatile.Write(ref _installed, 0);
_statusMessage = "acclient.exe not available.";
return;
}
HookResolver.ResolveResult resolved = HookResolver.Resolve(textSection, "TextParserGuard.FUN_0067D3C0", FuncPattern, TargetVa);
if (!resolved.Success)
{
Volatile.Write(ref _installed, 0);
_statusMessage = $"unresolved (VA 0x{TargetVa:X8}).";
RynthLog.Compat($"Compat: text-parser guard NOT installed — {_statusMessage}");
return;
}
try
{
_targetAddress = resolved.Address;
IntPtr detour = SehTrampoline.GetTagParserGuardAddress();
if (detour == IntPtr.Zero)
{
Volatile.Write(ref _installed, 0);
_statusMessage = "native detour address was null.";
RynthLog.Compat($"Compat: text-parser guard NOT installed — {_statusMessage}");
return;
}
// Redirect FUN_0067D3C0 -> RC_TagParserGuard (native). HookCreate returns
// the trampoline (original); hand it to the native guard BEFORE enabling so
// the very first detoured call already has a valid original to call through.
IntPtr trampoline = MinHook.HookCreate(_targetAddress, detour);
SehTrampoline.SetTagParserOriginal(trampoline);
Thread.MemoryBarrier();
MinHook.Enable(_targetAddress);
Volatile.Write(ref _installed, 1);
_statusMessage = $"Native parser guard @ 0x{_targetAddress.ToInt32():X8}.";
RynthLog.Compat(
$"Compat: text-parser guard ready (NATIVE) — target=0x{_targetAddress.ToInt32():X8}, " +
$"detour=0x{detour.ToInt32():X8}, trampoline=0x{trampoline.ToInt32():X8}.");
}
catch (Exception ex)
{
Volatile.Write(ref _installed, 0);
_statusMessage = ex.Message;
RynthLog.Compat($"Compat: text-parser guard install threw {ex.GetType().Name}: {ex.Message}");
}
}
}

View file

@ -0,0 +1,244 @@
// ============================================================================
// RynthCore.Engine - Compatibility/ThreadStackSampler.cs
//
// Cross-thread stack sampler. Once per heartbeat tick, walks every other
// thread in the process via Win32 SuspendThread + GetThreadContext +
// EBP-chain unwinding. For each thread, records how deep its stack currently
// is (number of return addresses landing inside our engine module). If any
// thread crosses the runaway-depth threshold, dumps the full chain of
// engine-RVA return addresses to the log.
//
// This catches recursion that the per-detour RecursionGuard misses — namely,
// recursion contained entirely between two engine-internal methods that
// never re-enter any of our hook detours.
//
// We don't symbolicate inline; the dumped RVAs can be cross-referenced to
// the PDB after the fact.
// ============================================================================
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
namespace RynthCore.Engine.Compatibility;
internal static class ThreadStackSampler
{
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr OpenThread(uint dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwThreadId);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern uint SuspendThread(IntPtr hThread);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern int ResumeThread(IntPtr hThread);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetThreadContext(IntPtr hThread, IntPtr lpContext);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr hObject);
[DllImport("kernel32.dll")]
private static extern uint GetCurrentThreadId();
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr GetModuleHandleW(string? lpModuleName);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetModuleHandleExW(uint dwFlags, IntPtr lpModuleName, out IntPtr phModule);
[DllImport("psapi.dll", SetLastError = true)]
private static extern bool GetModuleInformation(IntPtr hProcess, IntPtr hModule, out MODULEINFO lpmodinfo, uint cb);
[DllImport("kernel32.dll")]
private static extern IntPtr GetCurrentProcess();
[StructLayout(LayoutKind.Sequential)]
private struct MODULEINFO
{
public IntPtr lpBaseOfDll;
public uint SizeOfImage;
public IntPtr EntryPoint;
}
private const uint THREAD_SUSPEND_RESUME = 0x0002;
private const uint THREAD_GET_CONTEXT = 0x0008;
private const uint THREAD_QUERY_INFORMATION = 0x0040;
private const uint THREAD_QUERY_LIMITED_INFO = 0x0800;
private const uint CONTEXT_CONTROL = 0x00010001;
private const uint CONTEXT_INTEGER = 0x00010002;
// x86 CONTEXT layout: 716 bytes. Field offsets verified against winnt.h.
private const int CTX_SIZE = 716;
private const int CTX_OFF_EBP = 180;
private const int CTX_OFF_EIP = 184;
private const int CTX_OFF_ESP = 196;
private const int CTX_OFF_FLAGS = 0;
/// <summary>Engine module base + end, set once at first sample.</summary>
private static IntPtr _engineBase;
private static IntPtr _engineEnd;
/// <summary>Threshold for "this thread is deep in recursion": number of
/// distinct return addresses that land in our engine module.</summary>
private const int DepthAlarm = 50;
private static int _samplesEmittedTotal;
private const int MaxSamplesEmitted = 5;
public static void SampleAll()
{
if (_samplesEmittedTotal >= MaxSamplesEmitted) return;
if (_engineBase == IntPtr.Zero)
ResolveEngineRange();
if (_engineBase == IntPtr.Zero) return;
uint myTid = GetCurrentThreadId();
IntPtr ctxBuf = Marshal.AllocHGlobal(CTX_SIZE);
try
{
ProcessThread[] threads;
try { threads = new ProcessThread[Process.GetCurrentProcess().Threads.Count]; Process.GetCurrentProcess().Threads.CopyTo(threads, 0); }
catch { return; }
foreach (ProcessThread t in threads)
{
uint tid = (uint)t.Id;
if (tid == myTid) continue;
IntPtr h = OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_LIMITED_INFO, false, tid);
if (h == IntPtr.Zero) continue;
try
{
if (SuspendThread(h) == 0xFFFFFFFF) continue;
Marshal.WriteInt32(ctxBuf, CTX_OFF_FLAGS, (int)(CONTEXT_CONTROL | CONTEXT_INTEGER));
if (!GetThreadContext(h, ctxBuf)) continue;
uint eip = (uint)Marshal.ReadInt32(ctxBuf, CTX_OFF_EIP);
uint ebp = (uint)Marshal.ReadInt32(ctxBuf, CTX_OFF_EBP);
uint esp = (uint)Marshal.ReadInt32(ctxBuf, CTX_OFF_ESP);
int engineHits = WalkAndCount(ebp, esp, out string captured);
if (engineHits >= DepthAlarm)
{
if (Interlocked.Increment(ref _samplesEmittedTotal) > MaxSamplesEmitted) return;
RynthLog.Info("================================================================");
RynthLog.Info($"==== DEEP STACK in tid 0x{tid:X} ({tid}) name='{t.Id}' eip=0x{eip:X8} ebp=0x{ebp:X8} esp=0x{esp:X8} engineHits={engineHits} ====");
RynthLog.Info(captured);
RynthLog.Info("================================================================");
}
}
finally
{
ResumeThread(h);
CloseHandle(h);
}
}
}
finally
{
Marshal.FreeHGlobal(ctxBuf);
}
}
/// <summary>Walk EBP frame chain and count return addresses inside engine.
/// Builds a trace string (only filled if depth crosses alarm).</summary>
private static int WalkAndCount(uint ebp, uint esp, out string trace)
{
var sb = new System.Text.StringBuilder();
int hits = 0;
uint baseAddr = (uint)_engineBase.ToInt32();
uint endAddr = (uint)_engineEnd.ToInt32();
// 1) Walk EBP chain
uint cur = ebp;
for (int i = 0; i < 1024; i++)
{
if (cur == 0 || (cur & 3) != 0) break;
uint nextEbp, ret;
try
{
nextEbp = (uint)Marshal.ReadInt32((IntPtr)cur);
ret = (uint)Marshal.ReadInt32((IntPtr)cur, 4);
}
catch { break; }
if (ret >= baseAddr && ret < endAddr)
{
hits++;
if (hits <= 60)
sb.AppendLine($" ebp[{i:D3}] ret=0x{ret:X8} engine+0x{(ret - baseAddr):X}");
}
if (nextEbp <= cur || nextEbp - cur > 0x100000) break;
cur = nextEbp;
}
// 2) ESP scan as fallback (catches FPO frames)
if (hits < 5)
{
uint scanFrom = esp;
for (int i = 0; i < 4096; i++)
{
uint addr = scanFrom + (uint)(i * 4);
uint val;
try { val = (uint)Marshal.ReadInt32((IntPtr)addr); }
catch { break; }
if (val >= baseAddr && val < endAddr)
{
hits++;
if (hits <= 60)
sb.AppendLine($" esp+0x{i * 4:X4} ret=0x{val:X8} engine+0x{(val - baseAddr):X}");
}
}
}
trace = sb.ToString();
return hits;
}
private static void ResolveEngineRange()
{
try
{
// Resolve our own DLL by passing the address of one of our methods.
const uint GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS = 0x4;
const uint GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT = 0x2;
unsafe
{
delegate*<void> anchor = &Anchor;
if (!GetModuleHandleExW(
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
(IntPtr)anchor,
out IntPtr hModule) || hModule == IntPtr.Zero)
{
return;
}
if (!GetModuleInformation(GetCurrentProcess(), hModule, out MODULEINFO mi, (uint)Marshal.SizeOf<MODULEINFO>()))
return;
_engineBase = mi.lpBaseOfDll;
_engineEnd = (IntPtr)((long)mi.lpBaseOfDll + mi.SizeOfImage);
RynthLog.Info($"ThreadStackSampler: engine module range 0x{_engineBase.ToInt32():X8}..0x{_engineEnd.ToInt32():X8}");
}
}
catch (Exception ex)
{
RynthLog.Info($"ThreadStackSampler: ResolveEngineRange threw {ex.GetType().Name}: {ex.Message}");
}
}
private static void Anchor() { }
}

View file

@ -0,0 +1,130 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Hooks ClientNet::HandleTimeSynch to track the server time/wall-clock relationship.
/// Used to convert Enchantment._start_time (server seconds) into remaining wall-clock seconds.
///
/// ClientNet::HandleTimeSynch signature (thiscall):
/// void __thiscall ClientNet::HandleTimeSynch(ClientNet *this, CTimeSyncHeader *pHdr, CNetLayerPacket *pkt)
///
/// COptionalHeader layout (4-byte packing, 24 bytes):
/// +0 Turbine_RefCount _ref (vfptr=4, m_cRef=4)
/// +8 UInt32 m_dwMask
/// +12 UInt32 m_Flags
/// +16 Char* m_pData
/// +20 UInt32 m_cbData
/// CTimeSyncHeader layout:
/// +0 COptionalHeader (24 bytes)
/// +24 Double m_time ← server time in seconds
/// </summary>
internal static class TimeSyncHooks
{
private const int HandleTimeSynchVa = 0x005448F0;
// Verified unique + lands exactly at HandleTimeSynchVa offline (tools/pe_pattern.py).
private static readonly byte?[] HandleTimeSynchPattern = [ 0x55, 0x8B, 0xEC, 0x83, 0xE4, 0xF8, 0x83, 0xEC, 0x10, 0x8B ];
private const int TimeSyncHeaderMTimeOffset = 24;
private static IntPtr _originalHandleTimeSynch;
private static bool _initialized;
// Deep-audit finding #19 (2026-06-18): these used to be two plain fields
// (double + long) written on the net thread and read on the pump thread
// with no atomicity — on x86 a 64-bit load/store isn't atomic, so a
// reader could observe a torn _lastWallClockTicks (worst case a
// mis-timed rebuff from a wildly wrong elapsed time). Publishing both as
// one immutable snapshot object, swapped via Volatile.Write/Read, fixes
// that AND the subtler cross-field issue a per-field Interlocked fix
// wouldn't: a reader can no longer see a NEW _lastServerTime paired with
// the OLD _lastWallClockTicks (or vice versa) — the reference swap is
// all-or-nothing.
private sealed class TimeSyncSnapshot
{
public readonly double ServerTime;
public readonly long WallClockTicks;
public TimeSyncSnapshot(double serverTime, long wallClockTicks)
{
ServerTime = serverTime;
WallClockTicks = wallClockTicks;
}
}
private static TimeSyncSnapshot? _snapshot;
public static bool IsInitialized => _initialized;
/// <summary>
/// Returns the estimated current server time in seconds.
/// Returns 0 if no time sync has been received yet.
/// </summary>
public static double GetCurrentServerTime()
{
TimeSyncSnapshot? snap = Volatile.Read(ref _snapshot);
if (snap == null || snap.WallClockTicks == 0)
return 0;
double elapsed = (DateTime.UtcNow.Ticks - snap.WallClockTicks) / (double)TimeSpan.TicksPerSecond;
return snap.ServerTime + elapsed;
}
public static void Initialize()
{
if (_initialized)
return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection text))
{
RynthLog.Compat("Compat: time-sync hook - acclient .text not readable.");
return;
}
HookResolver.ResolveResult resolved = HookResolver.Resolve(text, "TimeSync.HandleTimeSynch", HandleTimeSynchPattern, HandleTimeSynchVa);
if (!resolved.Success)
{
RynthLog.Compat($"Compat: time-sync hook unresolved (0x{HandleTimeSynchVa:X8})");
return;
}
try
{
unsafe
{
delegate* unmanaged[Thiscall]<IntPtr, IntPtr, IntPtr, void> detour = &HandleTimeSynchDetour;
MinHook.Hook(resolved.Address, (IntPtr)detour, out _originalHandleTimeSynch);
}
_initialized = true;
RynthLog.Verbose($"Compat: time-sync hook ready - HandleTimeSynch=0x{resolved.Address.ToInt32():X8} ({resolved.Detail})");
}
catch (Exception ex)
{
RynthLog.Compat($"Compat: time-sync hook failed: {ex.Message}");
}
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })]
private static unsafe void HandleTimeSynchDetour(IntPtr thisPtr, IntPtr pHdr, IntPtr pkt)
{
try
{
if (pHdr != IntPtr.Zero)
{
long bits = Marshal.ReadInt64(pHdr + TimeSyncHeaderMTimeOffset);
double serverTime = BitConverter.Int64BitsToDouble(bits);
if (serverTime > 0)
{
Volatile.Write(ref _snapshot, new TimeSyncSnapshot(serverTime, DateTime.UtcNow.Ticks));
}
}
}
catch { }
var original = (delegate* unmanaged[Thiscall]<IntPtr, IntPtr, IntPtr, void>)_originalHandleTimeSynch;
original(thisPtr, pHdr, pkt);
}
}

View file

@ -0,0 +1,122 @@
using System;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
namespace RynthCore.Engine.Compatibility;
internal static class UiLifecycleHooks
{
private static readonly byte?[] SetUiReadyPattern =
[
0x56, 0x8B, 0x74, 0x24, 0x08, 0x85, 0xF6, 0x75,
0x16, 0x8B, 0x0D, null, null, null, null, 0x85,
0xC9, 0x74, 0x0C, 0x8B, 0x41, 0x04, 0x85, 0xC0,
0x74, 0x05, 0xE8, null, null, null, null, 0x89,
0x35, null, null, null, null, 0x5E, 0xC3
];
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void SetUiReadyDelegate(int isReady);
private static SetUiReadyDelegate? _originalSetUiReady;
private static SetUiReadyDelegate? _setUiReadyDetour;
private static IntPtr _targetAddress;
private static IntPtr _uiReadyFlagAddress;
private static string _statusMessage = "Not probed yet.";
private static long _nextStatusLogTick;
private static bool _waitingLogged;
public static bool IsInstalled { get; private set; }
public static bool HasObservedUiInitialized { get; private set; }
public static string StatusMessage => _statusMessage;
internal static IntPtr UiReadyFlagAddress => _uiReadyFlagAddress;
public static event Action? UiInitialized;
public static void Initialize()
{
if (IsInstalled)
return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
{
_statusMessage = "acclient.exe not available.";
return;
}
try
{
int funcOff = PatternScanner.FindPattern(textSection.Bytes, SetUiReadyPattern);
if (funcOff < 0)
{
_statusMessage = "APIManager::SetUIReady pattern not found.";
RynthLog.Compat($"Compat: UI lifecycle hook failed - {_statusMessage}");
return;
}
_targetAddress = new IntPtr(textSection.TextBaseVa + funcOff);
_uiReadyFlagAddress = new IntPtr(BitConverter.ToInt32(textSection.Bytes, funcOff + 33));
_setUiReadyDetour = SetUiReadyDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_setUiReadyDetour);
_originalSetUiReady = Marshal.GetDelegateForFunctionPointer<SetUiReadyDelegate>(MinHook.HookCreate(_targetAddress, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(_targetAddress);
IsInstalled = true;
_statusMessage = $"Hooked SetUIReady @ 0x{_targetAddress.ToInt32():X8}.";
_nextStatusLogTick = Environment.TickCount64 + 3000;
RynthLog.Verbose(
$"Compat: UI lifecycle hook ready - SetUIReady=0x{_targetAddress.ToInt32():X8}, uiReadyFlag=0x{_uiReadyFlagAddress.ToInt32():X8}");
if (_uiReadyFlagAddress != IntPtr.Zero && Marshal.ReadInt32(_uiReadyFlagAddress) != 0)
{
HasObservedUiInitialized = true;
_statusMessage = "UI ready already active (late attach).";
RynthLog.Verbose("Compat: UI lifecycle already active at inject time.");
}
}
catch (Exception ex)
{
_statusMessage = ex.Message;
RynthLog.Compat($"Compat: UI lifecycle hook failed - {ex.Message}");
}
}
public static void Poll()
{
if (HasObservedUiInitialized || !IsInstalled)
return;
long now = Environment.TickCount64;
if (now < _nextStatusLogTick)
return;
_nextStatusLogTick = now + 3000;
if (!_waitingLogged)
{
_waitingLogged = true;
RynthLog.Verbose("Compat: UI lifecycle awaiting SetUIReady(1).");
}
}
private static void SetUiReadyDetour(int isReady)
{
_originalSetUiReady!(isReady);
if (isReady != 0)
SignalUiInitialized("APIManager::SetUIReady(1)");
}
private static void SignalUiInitialized(string source)
{
if (HasObservedUiInitialized)
return;
HasObservedUiInitialized = true;
_statusMessage = $"UI initialized observed via {source}.";
RynthLog.Verbose($"Compat: UI initialized observed via {source}.");
UiInitialized?.Invoke();
}
}

View file

@ -0,0 +1,259 @@
using System;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.Compatibility;
internal static class UpdateObjectInventoryHooks
{
private const int UpdateObjectInventoryExpectedVa = 0x0055A190;
// Verified unique + lands at 0x0055A190 offline (tools/pe_pattern.py).
private static readonly byte?[] UpdateObjectInventoryPattern =
[
0x8B, 0x44, 0x24, 0x04, 0x50, 0xE8, null, null, null, null, 0x8B, 0x4C
];
// Derived from UpdateObjectInventory disasm: lea ecx, [eax+0x3C]
// The instruction at sig offset 15 (8D 48 3C) encodes the inventory offset.
private const int WeenieObjectInventoryOffset = 0x3C;
// CObjectInventory layout from Chorizite:
// LongHashData (12) + IDList _itemsList + IDList _containersList + ...
private const int ObjectInventoryItemsListOffset = 0x0C;
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void UpdateObjectInventoryDelegate(IntPtr thisPtr, uint objectId, IntPtr newInventory);
private static UpdateObjectInventoryDelegate? _originalUpdateObjectInventory;
private static UpdateObjectInventoryDelegate? _updateObjectInventoryDetour;
private static IntPtr _targetAddress;
private static string _statusMessage = "Not probed yet.";
public static bool IsInstalled { get; private set; }
public static string StatusMessage => _statusMessage;
public static void Initialize()
{
if (IsInstalled)
return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
{
_statusMessage = "acclient.exe not available.";
return;
}
try
{
int updateFuncOff = ResolveUpdateObjectInventoryOffset(textSection, out bool updateUsedScan);
if (updateFuncOff < 0)
{
_statusMessage = "ACCObjectMaint::UpdateObjectInventory unresolved.";
RynthLog.Compat($"Compat: update-object-inventory hook failed - {_statusMessage}");
return;
}
_targetAddress = new IntPtr(textSection.TextBaseVa + updateFuncOff);
_updateObjectInventoryDetour = UpdateObjectInventoryDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_updateObjectInventoryDetour);
_originalUpdateObjectInventory = Marshal.GetDelegateForFunctionPointer<UpdateObjectInventoryDelegate>(
MinHook.HookCreate(_targetAddress, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(_targetAddress);
IsInstalled = true;
_statusMessage =
$"Hooked ACCObjectMaint::UpdateObjectInventory @ 0x{_targetAddress.ToInt32():X8}" +
$"{(updateUsedScan ? " (pattern)" : string.Empty)}.";
RynthLog.Verbose($"Compat: update-object-inventory hook ready - {_statusMessage}");
}
catch (Exception ex)
{
_statusMessage = ex.Message;
RynthLog.Compat($"Compat: update-object-inventory hook failed - {ex.Message}");
}
}
private static int ResolveUpdateObjectInventoryOffset(AcClientTextSection textSection, out bool usedPatternScan)
{
usedPatternScan = false;
HookResolver.ResolveResult resolved = HookResolver.Resolve(
textSection, "UpdateInventory.UpdateObjectInventory", UpdateObjectInventoryPattern, UpdateObjectInventoryExpectedVa);
if (!resolved.Success)
return -1;
usedPatternScan = resolved.Source == HookResolver.ResolveSource.PatternScan;
return resolved.Address.ToInt32() - textSection.TextBaseVa;
}
private static void UpdateObjectInventoryDetour(IntPtr thisPtr, uint objectId, IntPtr newInventory)
{
_originalUpdateObjectInventory!(thisPtr, objectId, newInventory);
// Deep-audit finding #12 (2026-06-18): every sibling server-dispatch
// detour (UpdateObjectServerDispatchHooks, VectorUpdateServerDispatchHooks,
// SmartBoxHooks) wraps its queue call; this one didn't — an escaping
// throw here (e.g. OOM during the queue's lock+Enqueue) fail-fasts the
// client. Call-through stays outside the try, matching the fix note.
try
{
if (objectId != 0)
PluginManager.QueueUpdateObjectInventory(objectId);
}
catch { }
}
public static unsafe int GetContainerContents(uint containerId, uint* itemIds, int maxCount)
{
if (itemIds == null || maxCount <= 0)
return 0;
return GetContainerContents(containerId, new Span<uint>(itemIds, maxCount));
}
private static bool _hasLoggedVtableScan;
/// <summary>
/// Scan weenie object memory in 4-byte steps, logging every in-module pointer (vtable).
/// This reveals the sub-object layout — each vtable pointer marks a base class or embedded object.
/// </summary>
private static void LogWeenieVtableScan(uint containerId, IntPtr weeniePtr)
{
if (_hasLoggedVtableScan) return;
_hasLoggedVtableScan = true;
RynthLog.Verbose($"Compat: === Vtable scan of weenie 0x{containerId:X8} at 0x{weeniePtr.ToInt32():X8} ===");
for (int off = 0; off < 0x80; off += 4)
{
try
{
IntPtr addr = weeniePtr + off;
if (!IsReadablePointer(addr))
{
RynthLog.Verbose($"Compat: +0x{off:X2} UNREADABLE");
continue;
}
IntPtr val = Marshal.ReadIntPtr(addr);
bool inModule = SmartBoxLocator.IsPointerInModule(val);
bool readable = val != IntPtr.Zero && IsReadablePointer(val);
if (inModule)
RynthLog.Verbose($"Compat: +0x{off:X2} = 0x{val.ToInt32():X8} [VTABLE - in module]");
else if (readable && val.ToInt32() > 0x10000)
RynthLog.Verbose($"Compat: +0x{off:X2} = 0x{val.ToInt32():X8} [heap ptr]");
else
RynthLog.Verbose($"Compat: +0x{off:X2} = 0x{val.ToInt32():X8}");
}
catch
{
RynthLog.Verbose($"Compat: +0x{off:X2} ACCESS VIOLATION");
break;
}
}
// Also log what's at the current offset we're using
try
{
IntPtr invPtr = Marshal.ReadIntPtr(weeniePtr + WeenieObjectInventoryOffset);
RynthLog.Verbose($"Compat: Current WeenieObjectInventoryOffset=0x{WeenieObjectInventoryOffset:X2} -> 0x{invPtr.ToInt32():X8} readable={IsReadablePointer(invPtr)}");
}
catch (Exception ex)
{
RynthLog.Compat($"Compat: Failed to read at inventory offset: {ex.Message}");
}
}
private static int GetContainerContents(uint containerId, Span<uint> itemIds)
{
if (containerId == 0 || itemIds.Length == 0)
return 0;
// Brute-force scan: iterate known object IDs and check containerID ownership.
// The embedded CObjectInventory at weenie+0x3C is often empty (especially for
// the player object), so we scan all objects and match by ownership instead.
return ScanByContainerId(containerId, itemIds);
}
/// <summary>
/// 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)
{
int written = 0;
// Scan dynamic object range (0x80000001 – 0x8000FFFF)
for (uint id = 0x80000001; id <= 0x8000FFFF && written < itemIds.Length; id++)
{
if (id == containerId) continue;
if (!ClientObjectHooks.TryGetObjectOwnershipInfo(id, out uint cid, out uint wid, out _))
continue;
if (cid == containerId || wid == containerId)
itemIds[written++] = id;
}
return written;
}
private static int WalkIdList(uint containerId, IntPtr idList, Span<uint> dest, int expectedCount, string label)
{
IntPtr node = Marshal.ReadIntPtr(idList + 0x08); // first node
int written = 0;
int walked = 0;
while (node != IntPtr.Zero && written < expectedCount && written < dest.Length && walked < 2048)
{
walked++;
uint itemId = unchecked((uint)Marshal.ReadInt32(node));
if (itemId != 0)
{
dest[written++] = itemId;
}
node = Marshal.ReadIntPtr(node + 0x08); // next node
}
return written;
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern int VirtualQuery(IntPtr lpAddress, out MEMORY_BASIC_INFORMATION lpBuffer, int dwLength);
[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 MemCommit = 0x1000;
private const uint PageNoAccess = 0x01;
private const uint PageGuard = 0x100;
private static bool IsReadablePointer(IntPtr ptr)
{
if (ptr == IntPtr.Zero)
return false;
if (VirtualQuery(ptr, out MEMORY_BASIC_INFORMATION mbi, Marshal.SizeOf<MEMORY_BASIC_INFORMATION>()) == 0)
return false;
if (mbi.State != MemCommit)
return false;
return (mbi.Protect & (PageNoAccess | PageGuard)) == 0;
}
}

View file

@ -0,0 +1,118 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.Compatibility;
internal static class UpdateObjectServerDispatchHooks
{
private const int DispatchSbUpdateObjectVa = 0x006AD710;
private const int NetBlobBufPtrOffset = 0x2C;
private const int NetBlobBufSizeOffset = 0x30;
private const uint UpdateObjectOpcode = 0x0000F7DB;
// Verified unique + lands at 0x006AD710 offline (tools/pe_pattern.py).
private static readonly byte?[] DispatchSbUpdateObjectPattern =
[
0x81, 0xEC, 0xB8, 0x01, 0x00, 0x00, 0x53, 0x8B, 0x9C, 0x24, 0xC4, 0x01, 0x00, 0x00, 0x85, 0xDB, 0x74, 0x0B, 0x8B, 0x84, 0x24, 0xC0, 0x01, 0x00, 0x00, 0x85, 0xC0, 0x75, 0x0D, 0xB8, 0x03, 0x00, 0x00, 0x00, 0x5B, 0x81, 0xC4, 0xB8, 0x01, 0x00, 0x00, 0xC3, 0x8B, 0x43, 0x2C, 0x56, 0x8B, 0x73, 0x30, 0x89, 0x44, 0x24, 0x08, 0x8B, 0x08, 0x57, 0x8B, 0xF8, 0x83, 0xC0, 0x04, 0x81, 0xF9, 0xDB
];
private static IntPtr _originalDispatchSbUpdateObjectPtr;
private static IntPtr _targetAddress;
private static string _statusMessage = "Not probed yet.";
private static int _dispatchCount;
public static bool IsInstalled { get; private set; }
public static string StatusMessage => _statusMessage;
public static void Initialize()
{
if (IsInstalled)
return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
{
_statusMessage = "acclient.exe not available.";
return;
}
HookResolver.ResolveResult resolved = HookResolver.Resolve(textSection, "UpdateObject.DispatchSbUpdateObject", DispatchSbUpdateObjectPattern, DispatchSbUpdateObjectVa);
if (!resolved.Success)
{
_statusMessage = $"CM_Physics::DispatchSB_UpdateObject unresolved (VA 0x{DispatchSbUpdateObjectVa:X8}).";
RynthLog.Compat($"Compat: update-object hook failed - {_statusMessage}");
return;
}
try
{
unsafe
{
_targetAddress = resolved.Address;
delegate* unmanaged[Cdecl]<IntPtr, IntPtr, uint> pDetour = &DispatchSbUpdateObjectDetour;
MinHook.Hook(_targetAddress, (IntPtr)pDetour, out _originalDispatchSbUpdateObjectPtr);
}
IsInstalled = true;
_statusMessage = $"Hooked CM_Physics::DispatchSB_UpdateObject @ 0x{_targetAddress.ToInt32():X8}.";
RynthLog.Verbose($"Compat: update-object hook ready - DispatchSB_UpdateObject=0x{_targetAddress.ToInt32():X8}");
}
catch (Exception ex)
{
_statusMessage = ex.Message;
RynthLog.Compat($"Compat: update-object hook failed - {ex.Message}");
}
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static unsafe uint DispatchSbUpdateObjectDetour(IntPtr smartBoxPtr, IntPtr blob)
{
RecursionGuard.Tick("UpdateObjectServerDispatchHooks.DispatchSbUpdateObject");
var pOriginal = (delegate* unmanaged[Cdecl]<IntPtr, IntPtr, uint>)_originalDispatchSbUpdateObjectPtr;
uint objectId = TryReadUpdatedObjectId(blob);
uint status = pOriginal(smartBoxPtr, blob);
if (!LoginLifecycleHooks.HasObservedLoginComplete || objectId == 0)
return status;
try
{
int count = Interlocked.Increment(ref _dispatchCount);
if (count <= 8)
RynthLog.Verbose($"Compat: update object #{count} id=0x{objectId:X8} status={status}");
PluginManager.QueueUpdateObject(objectId);
}
catch { }
return status;
}
private static uint TryReadUpdatedObjectId(IntPtr blob)
{
if (blob == IntPtr.Zero)
return 0;
try
{
uint blobSize = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(blob, NetBlobBufSizeOffset)));
if (blobSize < 8)
return 0;
IntPtr payloadPtr = Marshal.ReadIntPtr(IntPtr.Add(blob, NetBlobBufPtrOffset));
if (payloadPtr == IntPtr.Zero)
return 0;
uint opcode = unchecked((uint)Marshal.ReadInt32(payloadPtr));
if (opcode != UpdateObjectOpcode)
return 0;
return unchecked((uint)Marshal.ReadInt32(IntPtr.Add(payloadPtr, sizeof(uint))));
}
catch
{
return 0;
}
}
}

View file

@ -0,0 +1,111 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.Engine.Hooking;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.Compatibility;
internal static class VectorUpdateServerDispatchHooks
{
private const int DispatchSbVectorUpdateVa = 0x006ADC80;
private const int NetBlobBufPtrOffset = 0x2C;
private const int NetBlobBufSizeOffset = 0x30;
private const uint VectorUpdateOpcode = 0x0000F74E;
// Verified unique + lands at 0x006ADC80 offline (tools/pe_pattern.py).
private static readonly byte?[] DispatchSbVectorUpdatePattern =
[
0x83, 0xEC, 0x20, 0x53, 0x8B, 0x5C, 0x24, 0x2C
];
private static IntPtr _originalDispatchSbVectorUpdatePtr;
private static IntPtr _targetAddress;
private static string _statusMessage = "Not probed yet.";
public static bool IsInstalled { get; private set; }
public static string StatusMessage => _statusMessage;
public static void Initialize()
{
if (IsInstalled)
return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
{
_statusMessage = "acclient.exe not available.";
return;
}
HookResolver.ResolveResult resolved = HookResolver.Resolve(textSection, "VectorUpdate.DispatchSbVectorUpdate", DispatchSbVectorUpdatePattern, DispatchSbVectorUpdateVa);
if (!resolved.Success)
{
_statusMessage = $"CM_Physics::DispatchSB_VectorUpdate unresolved (VA 0x{DispatchSbVectorUpdateVa:X8}).";
RynthLog.Compat($"Compat: vector-update hook failed - {_statusMessage}");
return;
}
try
{
unsafe
{
_targetAddress = resolved.Address;
delegate* unmanaged[Cdecl]<IntPtr, IntPtr, uint> pDetour = &DispatchSbVectorUpdateDetour;
MinHook.Hook(_targetAddress, (IntPtr)pDetour, out _originalDispatchSbVectorUpdatePtr);
}
IsInstalled = true;
_statusMessage = $"Hooked CM_Physics::DispatchSB_VectorUpdate @ 0x{_targetAddress.ToInt32():X8}.";
RynthLog.Verbose($"Compat: vector-update hook ready - DispatchSB_VectorUpdate=0x{_targetAddress.ToInt32():X8}");
}
catch (Exception ex)
{
_statusMessage = ex.Message;
RynthLog.Compat($"Compat: vector-update hook failed - {ex.Message}");
}
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static unsafe uint DispatchSbVectorUpdateDetour(IntPtr smartBoxPtr, IntPtr blob)
{
RecursionGuard.Tick("VectorUpdateServerDispatchHooks.DispatchSbVectorUpdate");
var pOriginal = (delegate* unmanaged[Cdecl]<IntPtr, IntPtr, uint>)_originalDispatchSbVectorUpdatePtr;
VectorUpdateInfo info = ReadVectorUpdateInfo(blob);
uint status = pOriginal(smartBoxPtr, blob);
if (!LoginLifecycleHooks.HasObservedLoginComplete)
return status;
if (info.Opcode != VectorUpdateOpcode || info.RawObjectId == 0)
return status;
try { PluginManager.QueueUpdateObject(info.RawObjectId); } catch { }
return status;
}
private static VectorUpdateInfo ReadVectorUpdateInfo(IntPtr blob)
{
if (blob == IntPtr.Zero)
return default;
try
{
uint blobSize = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(blob, NetBlobBufSizeOffset)));
if (blobSize < 8)
return new VectorUpdateInfo(0, 0, blobSize);
IntPtr payloadPtr = Marshal.ReadIntPtr(IntPtr.Add(blob, NetBlobBufPtrOffset));
if (payloadPtr == IntPtr.Zero)
return new VectorUpdateInfo(0, 0, blobSize);
uint opcode = unchecked((uint)Marshal.ReadInt32(payloadPtr));
uint rawObjectId = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(payloadPtr, sizeof(uint))));
return new VectorUpdateInfo(opcode, rawObjectId, blobSize);
}
catch
{
return default;
}
}
private readonly record struct VectorUpdateInfo(uint Opcode, uint RawObjectId, uint BlobSize);
}

View file

@ -0,0 +1,126 @@
using System;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.Compatibility;
/// <summary>
/// Hooks gmVendorUI::RecvNotice_OpenVendor and RecvNotice_CloseVendor to detect vendor open/close.
///
/// VAs from acclient.map (Chorizite) + 0x00401000 base:
/// RecvNotice_OpenVendor real impl = 0x000C52E0 + 0x00401000 = 0x004C52E0 (thunk at 0x004C62E0 → jumps here)
/// RecvNotice_CloseVendor = 0x000BFF40 + 0x00401000 = 0x004C0F40
///
/// We hook the real impl (0x004C5790, called by the thunk) and the close entry directly.
/// </summary>
internal static class VendorHooks
{
// gmVendorUI::RecvNotice_OpenVendor — actual implementation (thunk at 0x004C62E0 jumps here)
private const int RecvNoticeOpenVendorVa = 0x004C5790;
// gmVendorUI::RecvNotice_CloseVendor
private const int RecvNoticeCloseVendorVa = 0x004C0F40;
// Verified unique + lands at 0x004C5790 offline (tools/pe_pattern.py).
private static readonly byte?[] OpenVendorPattern =
[
0x83, 0xEC, 0x2C, 0x53, 0x55, 0x56, 0x57, 0x8B, 0xF1 // SUB ESP,2C; PUSH EBX; PUSH EBP; PUSH ESI; PUSH EDI; MOV ESI,ECX
];
// Verified unique + lands at 0x004C0F40 offline (tools/pe_pattern.py).
private static readonly byte?[] CloseVendorPattern =
[
0x8A, 0x44, 0x24, 0x04, 0x84, 0xC0, 0x75, 0x17 // MOV AL,[ESP+4]; TEST AL,AL; JNZ ...
];
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void RecvNoticeOpenVendorDelegate(IntPtr thisPtr, uint vendorId, IntPtr vpRef, IntPtr itemsRef, int shopMode);
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void RecvNoticeCloseVendorDelegate(IntPtr thisPtr, int updating);
private static RecvNoticeOpenVendorDelegate? _originalOpen;
private static RecvNoticeOpenVendorDelegate? _openDetour;
private static RecvNoticeCloseVendorDelegate? _originalClose;
private static RecvNoticeCloseVendorDelegate? _closeDetour;
private static IntPtr _openAddress;
private static IntPtr _closeAddress;
private static string _statusMessage = "Not probed yet.";
private static uint _currentVendorId;
public static bool IsInstalled { get; private set; }
public static string StatusMessage => _statusMessage;
public static void Initialize()
{
if (IsInstalled) return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
{
_statusMessage = "acclient.exe not available.";
return;
}
HookResolver.ResolveResult resolvedOpen = HookResolver.Resolve(textSection, "Vendor.OpenVendor", OpenVendorPattern, RecvNoticeOpenVendorVa);
if (!resolvedOpen.Success)
{
_statusMessage = $"RecvNotice_OpenVendor unresolved (VA 0x{RecvNoticeOpenVendorVa:X8}).";
RynthLog.Compat($"Compat: vendor hooks failed - {_statusMessage}");
return;
}
HookResolver.ResolveResult resolvedClose = HookResolver.Resolve(textSection, "Vendor.CloseVendor", CloseVendorPattern, RecvNoticeCloseVendorVa);
if (!resolvedClose.Success)
{
_statusMessage = $"RecvNotice_CloseVendor unresolved (VA 0x{RecvNoticeCloseVendorVa:X8}).";
RynthLog.Compat($"Compat: vendor hooks failed - {_statusMessage}");
return;
}
try
{
_openAddress = resolvedOpen.Address;
_openDetour = OpenVendorDetour;
IntPtr openPtr = Marshal.GetFunctionPointerForDelegate(_openDetour);
_originalOpen = Marshal.GetDelegateForFunctionPointer<RecvNoticeOpenVendorDelegate>(
MinHook.HookCreate(_openAddress, openPtr));
_closeAddress = resolvedClose.Address;
_closeDetour = CloseVendorDetour;
IntPtr closePtr = Marshal.GetFunctionPointerForDelegate(_closeDetour);
_originalClose = Marshal.GetDelegateForFunctionPointer<RecvNoticeCloseVendorDelegate>(
MinHook.HookCreate(_closeAddress, closePtr));
Thread.MemoryBarrier();
MinHook.Enable(_openAddress);
MinHook.Enable(_closeAddress);
IsInstalled = true;
_statusMessage = $"Hooked vendor @ open=0x{_openAddress.ToInt32():X8} close=0x{_closeAddress.ToInt32():X8}.";
RynthLog.Verbose($"Compat: vendor hooks ready - {_statusMessage}");
}
catch (Exception ex)
{
_statusMessage = ex.Message;
RynthLog.Compat($"Compat: vendor hooks failed - {ex.Message}");
}
}
private static void OpenVendorDetour(IntPtr thisPtr, uint vendorId, IntPtr vpRef, IntPtr itemsRef, int shopMode)
{
_originalOpen!(thisPtr, vendorId, vpRef, itemsRef, shopMode);
if (vendorId == 0) return;
_currentVendorId = vendorId;
PluginManager.QueueVendorOpen(vendorId);
}
private static void CloseVendorDetour(IntPtr thisPtr, int updating)
{
_originalClose!(thisPtr, updating);
uint vid = _currentVendorId;
_currentVendorId = 0;
if (vid != 0)
PluginManager.QueueVendorClose(vid);
}
}

View file

@ -0,0 +1,129 @@
using System;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.Compatibility;
internal static class ViewObjectContentsHooks
{
private const int ViewObjectContentsVa = 0x005596B0;
private const int StopViewingObjectContentsVa = 0x00559770;
// Verified unique + lands at 0x005596B0 offline (tools/pe_pattern.py).
private static readonly byte?[] ViewObjectContentsPattern =
[
0x53, 0x8B, 0x5C, 0x24, 0x08, 0x56, 0x57, 0x53,
0x8B, 0xF9, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x85
];
// Verified unique + lands at 0x00559770 offline (tools/pe_pattern.py).
private static readonly byte?[] StopViewingObjectContentsPattern =
[
0x56, 0x57, 0x8B, 0x7C, 0x24, 0x0C, 0x57, 0x8B,
0xF1, 0xE8, null, null, null, null, 0x85, 0xC0, 0x74, 0x07
];
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void ViewObjectContentsDelegate(IntPtr thisPtr, uint objectId, IntPtr newContents);
[UnmanagedFunctionPointer(CallingConvention.ThisCall)]
private delegate void StopViewingObjectContentsDelegate(IntPtr thisPtr, uint objectId);
private static ViewObjectContentsDelegate? _originalViewObjectContents;
private static ViewObjectContentsDelegate? _viewObjectContentsDetour;
private static StopViewingObjectContentsDelegate? _originalStopViewingObjectContents;
private static StopViewingObjectContentsDelegate? _stopViewingObjectContentsDetour;
private static IntPtr _viewTargetAddress;
private static IntPtr _stopTargetAddress;
private static string _statusMessage = "Not probed yet.";
private static int _viewDispatchCount;
private static int _stopDispatchCount;
public static bool IsInstalled { get; private set; }
public static string StatusMessage => _statusMessage;
public static void Initialize()
{
if (IsInstalled)
return;
if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection))
{
_statusMessage = "acclient.exe not available.";
return;
}
HookResolver.ResolveResult resolvedView = HookResolver.Resolve(textSection, "ViewContents.ViewObjectContents", ViewObjectContentsPattern, ViewObjectContentsVa);
if (!resolvedView.Success)
{
_statusMessage = $"ACCObjectMaint::ViewObjectContents unresolved (VA 0x{ViewObjectContentsVa:X8}).";
RynthLog.Compat($"Compat: view-object-contents hook failed - {_statusMessage}");
return;
}
HookResolver.ResolveResult resolvedStop = HookResolver.Resolve(textSection, "ViewContents.StopViewingObjectContents", StopViewingObjectContentsPattern, StopViewingObjectContentsVa);
if (!resolvedStop.Success)
{
_statusMessage = $"ACCObjectMaint::StopViewingObjectContents unresolved (VA 0x{StopViewingObjectContentsVa:X8}).";
RynthLog.Compat($"Compat: view-object-contents hook failed - {_statusMessage}");
return;
}
try
{
_viewTargetAddress = resolvedView.Address;
_viewObjectContentsDetour = ViewObjectContentsDetour;
IntPtr viewDetourPtr = Marshal.GetFunctionPointerForDelegate(_viewObjectContentsDetour);
_originalViewObjectContents = Marshal.GetDelegateForFunctionPointer<ViewObjectContentsDelegate>(MinHook.HookCreate(_viewTargetAddress, viewDetourPtr));
_stopTargetAddress = resolvedStop.Address;
_stopViewingObjectContentsDetour = StopViewingObjectContentsDetour;
IntPtr stopDetourPtr = Marshal.GetFunctionPointerForDelegate(_stopViewingObjectContentsDetour);
_originalStopViewingObjectContents = Marshal.GetDelegateForFunctionPointer<StopViewingObjectContentsDelegate>(MinHook.HookCreate(_stopTargetAddress, stopDetourPtr));
Thread.MemoryBarrier();
MinHook.Enable(_viewTargetAddress);
MinHook.Enable(_stopTargetAddress);
IsInstalled = true;
_statusMessage = $"Hooked contents view seams @ 0x{_viewTargetAddress.ToInt32():X8}/0x{_stopTargetAddress.ToInt32():X8}.";
RynthLog.Verbose(
$"Compat: view-object-contents hooks ready - view=0x{_viewTargetAddress.ToInt32():X8}, stop=0x{_stopTargetAddress.ToInt32():X8}");
}
catch (Exception ex)
{
_statusMessage = ex.Message;
RynthLog.Compat($"Compat: view-object-contents hook failed - {ex.Message}");
}
}
private static void ViewObjectContentsDetour(IntPtr thisPtr, uint objectId, IntPtr newContents)
{
_originalViewObjectContents!(thisPtr, objectId, newContents);
if (objectId == 0)
return;
ClientHelperHooks.NotifyViewObjectContents(objectId);
int count = Interlocked.Increment(ref _viewDispatchCount);
if (count <= 0)
RynthLog.Verbose($"Compat: view contents #{count} id=0x{objectId:X8} contents=0x{newContents.ToInt32():X8}");
PluginManager.QueueViewObjectContents(objectId);
}
private static void StopViewingObjectContentsDetour(IntPtr thisPtr, uint objectId)
{
_originalStopViewingObjectContents!(thisPtr, objectId);
if (objectId == 0)
return;
ClientHelperHooks.NotifyStopViewingObjectContents(objectId);
int count = Interlocked.Increment(ref _stopDispatchCount);
if (count <= 5)
RynthLog.Verbose($"Compat: stop view contents #{count} id=0x{objectId:X8}");
PluginManager.QueueStopViewingObjectContents(objectId);
}
}

View file

@ -0,0 +1,104 @@
// ============================================================================
// RynthCore.Engine - CrashDump.cs
// Writes a minidump of THIS process via dbghelp!MiniDumpWriteDump. Used by
// MainThreadHangWatchdog to capture a real post-mortem the moment AC's main
// thread is confirmed permanently wedged — a targeted replacement for
// always-on procdump (which also dumped on every clean exit and every handled
// first-chance AV, so a .dmp's existence never meant a real crash).
//
// Safe to call from a background thread: MiniDumpWriteDump suspends all other
// threads internally while it snapshots them, which is exactly what we want for
// a hang. The dbghelp.dll P/Invoke is lazy-bound (no cost unless we ever fire).
// ============================================================================
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace RynthCore.Engine;
internal static class CrashDump
{
[DllImport("dbghelp.dll", SetLastError = true)]
private static extern bool MiniDumpWriteDump(
IntPtr hProcess,
uint processId,
SafeHandle hFile,
uint dumpType,
IntPtr exceptionParam,
IntPtr userStreamParam,
IntPtr callbackParam);
[DllImport("kernel32.dll")]
private static extern IntPtr GetCurrentProcess();
[DllImport("kernel32.dll")]
private static extern uint GetCurrentProcessId();
// MINIDUMP_TYPE. ⚠ AC ships an ANCIENT dbghelp.dll 6.1 (2003) in its own
// directory; it's already loaded by base name, so [DllImport("dbghelp.dll")]
// binds to THAT, not the modern OS v10. dbghelp 6.1 predates
// MiniDumpWithThreadInfo (0x1000, added in 6.5) and REJECTS it with
// ERROR_INVALID_PARAMETER (87) — which is why every hang dump failed
// (diagnosed 2026-06-10). Use only flags 6.1 supports: MiniDumpNormal already
// carries ALL thread stacks (enough to read a deadlock's lock holder);
// WithHandleData (0x4, since 5.1) is kept. On any failure we retry bare Normal.
private const uint DumpTypePreferred = 0x00000000 | 0x00000004; // Normal + WithHandleData
private const uint DumpTypeFallback = 0x00000000; // Normal only (universally supported)
/// <summary>
/// Write a minidump of the current process to Logs\dumps\. Best-effort;
/// never throws. Returns true on success and sets <paramref name="dumpPath"/>.
/// </summary>
internal static bool WriteSelfDump(string reason, out string dumpPath)
{
dumpPath = string.Empty;
try
{
string dir = Path.Combine(LogPaths.LogDirectory, "dumps");
Directory.CreateDirectory(dir);
string stamp = DateTime.Now.ToString("yyyyMMdd_HHmmss");
dumpPath = Path.Combine(dir, $"hang_{Environment.ProcessId}_{stamp}.dmp");
using var fs = new FileStream(dumpPath, FileMode.Create, FileAccess.Write, FileShare.None);
bool ok = MiniDumpWriteDump(
GetCurrentProcess(), GetCurrentProcessId(), fs.SafeFileHandle,
DumpTypePreferred, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
int err = ok ? 0 : Marshal.GetLastWin32Error();
// ERROR_INVALID_PARAMETER (87) ⇒ AC's ancient dbghelp 6.1 rejected a flag.
// Retry with bare MiniDumpNormal (universally supported, still has every
// thread stack — what we need to read the deadlock's lock holder).
if (!ok && err == 87)
{
fs.SetLength(0);
ok = MiniDumpWriteDump(
GetCurrentProcess(), GetCurrentProcessId(), fs.SafeFileHandle,
DumpTypeFallback, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
err = ok ? 0 : Marshal.GetLastWin32Error();
if (ok) RynthLog.Error($"CrashDump: rich flags rejected by AC's old dbghelp 6.1 — wrote bare Normal dump, reason={reason}");
}
if (!ok)
{
RynthLog.Error($"CrashDump: MiniDumpWriteDump failed err={err} reason={reason}");
// Don't leave a 0-byte .dmp behind — it reads as a crash marker
// during triage (observed: hang_17692_20260611_114430.dmp, 0
// bytes, main thread suspended mid-exception-dispatch).
try { fs.Close(); File.Delete(dumpPath); } catch { }
return false;
}
long size = 0;
try { size = new FileInfo(dumpPath).Length; } catch { }
RynthLog.Error($"CrashDump: wrote {dumpPath} ({size / 1024}KB) reason={reason}");
return true;
}
catch (Exception ex)
{
RynthLog.Error($"CrashDump: exception {ex.GetType().Name}: {ex.Message}");
return false;
}
}
}

View file

@ -0,0 +1,455 @@
// ============================================================================
// RynthCore.Engine - CrashLogger.cs
// Installs a Win32 Vectored Exception Handler so that an AV (uncatchable in
// NativeAOT) is logged with the faulting address + module BEFORE the process
// dies. Without this, silent AVs leave us guessing which call crashed.
// ============================================================================
using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace RynthCore.Engine;
internal static class CrashLogger
{
[StructLayout(LayoutKind.Sequential)]
private struct EXCEPTION_RECORD
{
public uint ExceptionCode;
public uint ExceptionFlags;
public IntPtr ExceptionRecord;
public IntPtr ExceptionAddress;
public uint NumberParameters;
// ExceptionInformation[15] follows — not needed for our logging
}
[StructLayout(LayoutKind.Sequential)]
private struct EXCEPTION_POINTERS
{
public IntPtr ExceptionRecord; // EXCEPTION_RECORD*
public IntPtr ContextRecord; // CONTEXT*
}
private delegate int VectoredHandler(IntPtr exceptionInfo);
[DllImport("kernel32.dll")]
private static extern IntPtr AddVectoredExceptionHandler(uint first, VectoredHandler handler);
private delegate int UnhandledExceptionFilter(IntPtr exceptionInfo);
[DllImport("kernel32.dll")]
private static extern IntPtr SetUnhandledExceptionFilter(UnhandledExceptionFilter handler);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
private static extern uint GetModuleFileNameW(IntPtr hModule, char[] lpFilename, uint nSize);
[DllImport("psapi.dll", SetLastError = true)]
private static extern bool GetModuleInformation(IntPtr hProcess, IntPtr hModule, out MODULEINFO lpmodinfo, uint cb);
[DllImport("kernel32.dll")]
private static extern IntPtr GetCurrentProcess();
[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
{
public IntPtr lpBaseOfDll;
public uint SizeOfImage;
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;
// Exception codes worth logging — skip the noisy breakpoints / single-steps.
private const uint EXCEPTION_ACCESS_VIOLATION = 0xC0000005;
private const uint EXCEPTION_ILLEGAL_INSTRUCTION = 0xC000001D;
private const uint EXCEPTION_PRIV_INSTRUCTION = 0xC0000096;
private const uint EXCEPTION_INT_DIVIDE_BY_ZERO = 0xC0000094;
private const uint EXCEPTION_STACK_OVERFLOW = 0xC00000FD;
// Return values for VectoredHandler
private const int EXCEPTION_CONTINUE_SEARCH = 0;
// Pin the delegate so it isn't GC'd while Windows holds the function pointer.
private static VectoredHandler? _handler;
private static UnhandledExceptionFilter? _suefHandler;
private static bool _installed;
// Once-per-process latch; first interesting AV wins.
private static int _crashLogged;
// First-chance trace counter: dump exception code + addr for the first
// N exceptions we observe regardless of "interesting" filter, so we can
// confirm VEH is even firing during a real crash.
private static int _firstChanceTraceCount;
private const int FirstChanceTraceLimit = 20;
public static void Install()
{
if (_installed) return;
// ── DO NOT install the managed VEH / SUEF (proven fatal 2026-05-16) ──
// AddVectoredExceptionHandler(CALL_FIRST, managed-delegate) registers a
// NativeAOT *managed reverse-P/Invoke* that the OS invokes for EVERY
// first-chance SEH exception process-wide — including the many that AC,
// d3d9.dll and Avalonia raise-and-handle internally in normal
// operation. On an AC-owned thread (render/EndScene) where the runtime
// can't safely attach/trap (mid-render, mid-GC), that transition
// fail-fasts in RhpReversePInvokeAttachOrTrapThread2 — exactly the
// 2026-05-16 10:13 dump (CrashLogger.VectoredHandler is literally on
// the fail-fast stack, EndScene→OverlayTextureRenderer.UploadFrame).
// It also does GC-capable managed work (Marshal.PtrToStructure,
// RynthLog) inside exception dispatch. Same fatal class as the removed
// RaiseFailFastException hook. Across the entire multi-session crash
// investigation this handler produced ZERO usable crash logs — every
// real crash either overflowed past the stack reservation (bypassing
// VEH) or the VEH's own transition fail-fasted. It is pure liability:
// it converts first-chance exceptions AC would otherwise handle into
// guaranteed fail-fast process death. SUEF has the same managed-
// callback hazard and also never produced a usable log. Both removed.
// External crash capture (procdump -ma -t) replaced this diagnostic.
try
{
_installed = true;
RynthLog.Info("CrashLogger: managed VEH/SUEF intentionally NOT installed (fatal in NativeAOT-injected acclient — see code comment).");
}
catch (Exception ex)
{
RynthLog.Info($"CrashLogger: install failed {ex.GetType().Name}: {ex.Message}");
}
}
/// <summary>
/// SetUnhandledExceptionFilter target — runs only when no other handler
/// catches the exception. Same dump as the VEH path, but explicitly
/// labeled so we know which path produced the log.
/// </summary>
private static int OnUnhandledException(IntPtr pExceptionInfo)
{
try
{
RynthLog.Error("==== SUEF (last-chance unhandled) FIRED ====");
ProcessException(pExceptionInfo, sourceTag: "SUEF");
}
catch
{
}
// EXCEPTION_CONTINUE_SEARCH (0) lets WER take over (which on this
// box doesn't seem to be configured to log either, but we've at
// least written our banner now).
return 0;
}
private static int OnVectoredException(IntPtr pExceptionInfo)
{
ProcessException(pExceptionInfo, sourceTag: "VEH");
return EXCEPTION_CONTINUE_SEARCH;
}
/// <summary>
/// Shared exception handling — called from both the VEH (first-chance)
/// and SUEF (last-chance) paths. Tagged with which path observed it so
/// we can tell whether VEH is even running during a real crash.
/// </summary>
private static void ProcessException(IntPtr pExceptionInfo, string sourceTag)
{
try
{
EXCEPTION_POINTERS ep = Marshal.PtrToStructure<EXCEPTION_POINTERS>(pExceptionInfo);
EXCEPTION_RECORD er = Marshal.PtrToStructure<EXCEPTION_RECORD>(ep.ExceptionRecord);
// First-chance trace (capped). Logs every SEH exception we observe
// for the first N times, regardless of whether it's "interesting".
// This proves VEH is firing and lets us see codes we may want to
// start treating as fatal.
int traceN = Interlocked.Increment(ref _firstChanceTraceCount);
if (traceN <= FirstChanceTraceLimit)
{
RynthLog.Info($"[{sourceTag}] fc#{traceN} code=0x{er.ExceptionCode:X8} addr=0x{er.ExceptionAddress.ToInt64():X8} flags=0x{er.ExceptionFlags:X}");
}
// Only log genuinely fatal categories. Normal operation throws SEH
// exceptions (C++ 0xE06D7363, CLR 0xE0434352, etc.) we should ignore.
bool interesting =
er.ExceptionCode == EXCEPTION_ACCESS_VIOLATION ||
er.ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION ||
er.ExceptionCode == EXCEPTION_PRIV_INSTRUCTION ||
er.ExceptionCode == EXCEPTION_INT_DIVIDE_BY_ZERO ||
er.ExceptionCode == EXCEPTION_STACK_OVERFLOW;
if (!interesting)
return;
string module = ResolveModule(er.ExceptionAddress, out IntPtr moduleBase);
// Historically we returned EXCEPTION_CONTINUE_SEARCH whenever the
// faulting address didn't resolve to a module — to suppress the
// flood of speculative-null-deref AVs that .NET Framework's CLR
// (used by Decal-injected managed plugins) generates as part of
// normal nullable reads. Problem: that filter ALSO suppressed
// genuine fatal AVs whose target address is NULL, in freed heap,
// or in JIT'd code — which is most of what actually kills AC.
// We only enable the filter when Decal is loaded; otherwise we
// log every interesting AV unconditionally and let the once-per-
// process latch (added below) keep the log readable.
if (moduleBase == IntPtr.Zero && Compatibility.DecalDetection.IsDecalLoaded)
return;
// Once-per-process latch: log the first interesting fault, then
// stop logging subsequent AVs to keep the log focused on the
// root cause. The process is going to die anyway, and tail
// SEH unwind frequently re-raises the same fault several times.
if (Interlocked.Exchange(ref _crashLogged, 1) != 0)
return;
long rva = moduleBase != IntPtr.Zero
? er.ExceptionAddress.ToInt64() - moduleBase.ToInt64()
: 0;
string codeName = er.ExceptionCode switch
{
EXCEPTION_ACCESS_VIOLATION => "ACCESS_VIOLATION",
EXCEPTION_ILLEGAL_INSTRUCTION => "ILLEGAL_INSTRUCTION",
EXCEPTION_PRIV_INSTRUCTION => "PRIV_INSTRUCTION",
EXCEPTION_INT_DIVIDE_BY_ZERO => "DIVIDE_BY_ZERO",
EXCEPTION_STACK_OVERFLOW => "STACK_OVERFLOW",
_ => "UNKNOWN",
};
RynthLog.Info("================================================================");
RynthLog.Error($"==== CRASH ({codeName}) [{sourceTag}] build={EntryPoint.BuildStamp} initCount={EntryPoint.InitCount} thread={Environment.CurrentManagedThreadId}");
RynthLog.Info(
$" code=0x{er.ExceptionCode:X8} addr=0x{er.ExceptionAddress.ToInt64():X8} " +
$"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($" AV kind={kind} faultAddr=0x{avAddr.ToInt64():X8}");
}
DumpContext(ep.ContextRecord);
RynthLog.Info("================================================================");
}
catch
{
// Logging must not throw — we're in an exception handler.
}
}
/// <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>
/// <summary>
/// Reused by MainThreadHangWatchdog: format a captured x86 CONTEXT* (from
/// GetThreadContext on a suspended thread) as a register dump + stack walk.
/// </summary>
internal static void DumpExternalContext(IntPtr ctx, string tag) => DumpContext(ctx, tag);
private static void DumpContext(IntPtr ctx) => DumpContext(ctx, "CRASH");
/// <summary>module+RVA for a code address, or &lt;unknown&gt; — used by the
/// hang watchdog for cheap per-sample eip summaries.</summary>
internal static string ResolveCodeAddr(IntPtr addr)
{
try
{
string m = ResolveModule(addr, out IntPtr b);
return b != IntPtr.Zero ? $"{ShortModule(m)}+0x{addr.ToInt64() - b.ToInt64():X}" : "<unknown>";
}
catch { return "<err>"; }
}
private static void DumpContext(IntPtr ctx, string tag)
{
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(
$"{tag} 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($"{tag} 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;
try
{
if (!GetModuleHandleExW(
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
address, out IntPtr hModule) || hModule == IntPtr.Zero)
{
return "<unknown>";
}
moduleBase = hModule;
char[] buf = new char[512];
uint len = GetModuleFileNameW(hModule, buf, (uint)buf.Length);
if (len == 0) return "<noname>";
return new string(buf, 0, (int)len);
}
catch
{
return "<resolve-failed>";
}
}
}

View file

@ -0,0 +1,168 @@
// ═══════════════════════════════════════════════════════════════════════════
// RynthCore.Engine — D3D9/BitmapFont.cs
// Dependency-free 5x7 bitmap font, ported from RynthCore2's bitmap_font.cpp.
//
// Standard 5x7 glyph cells. Each glyph is 7 rows; the low 5 bits of each row
// are the columns, bit 4 = leftmost. A set bit is a lit pixel cell. Lit cells
// are emitted as rectangles through a caller-supplied sink so the renderer
// (VitalHud) can turn each into a colored quad. No allocation, no texture.
// ═══════════════════════════════════════════════════════════════════════════
using System;
namespace RynthCore.Engine.D3D9;
internal static class BitmapFont
{
/// <summary>Receives one lit pixel cell as an inclusive-exclusive rect.</summary>
internal delegate void CellSink(int x0, int y0, int x1, int y1);
public const int GlyphW = 5;
public const int GlyphH = 7;
private const int Advance = GlyphW + 1; // one-cell gap between glyphs
// Glyph table row, in a fixed order; IndexOf maps a character to a row.
// 0 = space
// 1..10 = '0'..'9'
// 11..36 = 'A'..'Z'
// 37..45 = '/' ':' '.' ',' '-' '+' '%' '(' ')'
private const int GSpace = 0;
private const int GDigit0 = 1;
private const int GLetterA = 11;
private const int GSlash = 37;
private const int GColon = 38;
private const int GDot = 39;
private const int GComma = 40;
private const int GDash = 41;
private const int GPlus = 42;
private const int GPercent = 43;
private const int GLParen = 44;
private const int GRParen = 45;
// 5x7 cells, bit 4 leftmost — transcribed verbatim from bitmap_font.cpp.
private static readonly byte[][] Glyphs =
[
/* space */ [0, 0, 0, 0, 0, 0, 0],
/* 0 */ [0b01110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b01110],
/* 1 */ [0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110],
/* 2 */ [0b01110, 0b10001, 0b00001, 0b00010, 0b00100, 0b01000, 0b11111],
/* 3 */ [0b11111, 0b00010, 0b00100, 0b00010, 0b00001, 0b10001, 0b01110],
/* 4 */ [0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010],
/* 5 */ [0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110],
/* 6 */ [0b00110, 0b01000, 0b10000, 0b11110, 0b10001, 0b10001, 0b01110],
/* 7 */ [0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b01000, 0b01000],
/* 8 */ [0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110],
/* 9 */ [0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b00010, 0b01100],
/* A */ [0b01110, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001],
/* B */ [0b11110, 0b10001, 0b10001, 0b11110, 0b10001, 0b10001, 0b11110],
/* C */ [0b01110, 0b10001, 0b10000, 0b10000, 0b10000, 0b10001, 0b01110],
/* D */ [0b11100, 0b10010, 0b10001, 0b10001, 0b10001, 0b10010, 0b11100],
/* E */ [0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b11111],
/* F */ [0b11111, 0b10000, 0b10000, 0b11110, 0b10000, 0b10000, 0b10000],
/* G */ [0b01110, 0b10001, 0b10000, 0b10111, 0b10001, 0b10001, 0b01111],
/* H */ [0b10001, 0b10001, 0b10001, 0b11111, 0b10001, 0b10001, 0b10001],
/* I */ [0b01110, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110],
/* J */ [0b00111, 0b00010, 0b00010, 0b00010, 0b00010, 0b10010, 0b01100],
/* K */ [0b10001, 0b10010, 0b10100, 0b11000, 0b10100, 0b10010, 0b10001],
/* L */ [0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b10000, 0b11111],
/* M */ [0b10001, 0b11011, 0b10101, 0b10101, 0b10001, 0b10001, 0b10001],
/* N */ [0b10001, 0b11001, 0b10101, 0b10011, 0b10001, 0b10001, 0b10001],
/* O */ [0b01110, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110],
/* P */ [0b11110, 0b10001, 0b10001, 0b11110, 0b10000, 0b10000, 0b10000],
/* Q */ [0b01110, 0b10001, 0b10001, 0b10001, 0b10101, 0b10010, 0b01101],
/* R */ [0b11110, 0b10001, 0b10001, 0b11110, 0b10100, 0b10010, 0b10001],
/* S */ [0b01111, 0b10000, 0b10000, 0b01110, 0b00001, 0b00001, 0b11110],
/* T */ [0b11111, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100, 0b00100],
/* U */ [0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01110],
/* V */ [0b10001, 0b10001, 0b10001, 0b10001, 0b10001, 0b01010, 0b00100],
/* W */ [0b10001, 0b10001, 0b10001, 0b10101, 0b10101, 0b10101, 0b01010],
/* X */ [0b10001, 0b10001, 0b01010, 0b00100, 0b01010, 0b10001, 0b10001],
/* Y */ [0b10001, 0b10001, 0b01010, 0b00100, 0b00100, 0b00100, 0b00100],
/* Z */ [0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b10000, 0b11111],
/* / */ [0b00001, 0b00010, 0b00010, 0b00100, 0b01000, 0b01000, 0b10000],
/* : */ [0b00000, 0b00100, 0b00100, 0b00000, 0b00100, 0b00100, 0b00000],
/* . */ [0b00000, 0b00000, 0b00000, 0b00000, 0b00000, 0b01100, 0b01100],
/* , */ [0b00000, 0b00000, 0b00000, 0b00000, 0b01100, 0b00100, 0b01000],
/* - */ [0b00000, 0b00000, 0b00000, 0b11111, 0b00000, 0b00000, 0b00000],
/* + */ [0b00000, 0b00100, 0b00100, 0b11111, 0b00100, 0b00100, 0b00000],
/* % */ [0b11001, 0b11010, 0b00010, 0b00100, 0b01000, 0b01011, 0b10011],
/* ( */ [0b00010, 0b00100, 0b01000, 0b01000, 0b01000, 0b00100, 0b00010],
/* ) */ [0b01000, 0b00100, 0b00010, 0b00010, 0b00010, 0b00100, 0b01000],
];
// Maps an ASCII character to a glyph row, or -1 if unsupported (advance blank).
private static int IndexOf(char c)
{
if (c >= '0' && c <= '9') return GDigit0 + (c - '0');
if (c >= 'A' && c <= 'Z') return GLetterA + (c - 'A');
if (c >= 'a' && c <= 'z') return GLetterA + (c - 'a'); // fold to uppercase
return c switch
{
' ' => GSpace,
'/' => GSlash,
':' => GColon,
'.' => GDot,
',' => GComma,
'-' => GDash,
'+' => GPlus,
'%' => GPercent,
'(' => GLParen,
')' => GRParen,
_ => -1,
};
}
/// <summary>Pixel height of a glyph at the given cell size.</summary>
public static int Height(int cellPx)
{
if (cellPx < 1) cellPx = 1;
return GlyphH * cellPx;
}
/// <summary>Pixel width of a rendered string at the given cell size. Takes a
/// span so callers can measure stack-formatted text without allocating.</summary>
public static int MeasureWidth(ReadOnlySpan<char> s, int cellPx)
{
if (s.IsEmpty) return 0;
if (cellPx < 1) cellPx = 1;
int n = s.Length;
// n glyphs, each GlyphW wide, with (n-1) single-cell gaps between them.
return (n * GlyphW + (n - 1)) * cellPx;
}
/// <summary>
/// Emits the lit cells of <paramref name="s"/> at (x, y) at the given cell
/// size by invoking <paramref name="sink"/> once per lit cell. Takes a span
/// (string literals convert implicitly) so it stays allocation-free; the sink
/// is a cached delegate on the caller side.
/// </summary>
public static void Emit(ReadOnlySpan<char> s, int x, int y, int cellPx, CellSink sink)
{
if (s.IsEmpty || sink == null) return;
if (cellPx < 1) cellPx = 1;
int penX = x;
foreach (char ch in s)
{
int gi = IndexOf(ch);
if (gi >= 0 && gi != GSpace)
{
byte[] rows = Glyphs[gi];
for (int r = 0; r < GlyphH; r++)
{
int bits = rows[r];
for (int c = 0; c < GlyphW; c++)
{
if (((bits >> (GlyphW - 1 - c)) & 1) != 0)
{
int x0 = penX + c * cellPx;
int y0 = y + r * cellPx;
sink(x0, y0, x0 + cellPx, y0 + cellPx);
}
}
}
}
penX += Advance * cellPx;
}
}
}

View file

@ -0,0 +1,270 @@
using System;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
namespace RynthCore.Engine.D3D9;
internal static class D3D9Bootstrapper
{
private const uint D3DSdkVersion = 32;
private const int PollIntervalMs = 50;
private const int BootstrapFallbackMs = 15000;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate IntPtr Direct3DCreate9Delegate(uint sdkVersion);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int CreateDeviceDelegate(
IntPtr pD3D9,
uint adapter,
uint deviceType,
IntPtr hFocusWindow,
uint behaviorFlags,
IntPtr pPresentationParameters,
out IntPtr ppDevice);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
private static extern IntPtr GetModuleHandleA(string? lpModuleName);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
private static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
private static int _started;
private static bool _d3dCreateHookInstalled;
private static bool _createDeviceHookInstalled;
private static bool _realDeviceObserved;
private static Direct3DCreate9Delegate? _originalDirect3DCreate9;
private static Direct3DCreate9Delegate? _direct3DCreate9Detour;
private static CreateDeviceDelegate? _originalCreateDevice;
private static CreateDeviceDelegate? _createDeviceDetour;
private static IntPtr _createDeviceTarget;
private static IntPtr _direct3DCreate9Target;
public static void Start()
{
if (Interlocked.CompareExchange(ref _started, 1, 0) != 0)
return;
var thread = new Thread(BootstrapWorker)
{
Name = "RynthCore.D3D9Bootstrap",
IsBackground = true
};
thread.Start();
}
private static void BootstrapWorker()
{
try
{
// This runs after character login, so d3d9.dll and the game's
// device are fully initialized. Use the NULLREF throwaway device
// for vtable discovery — it's safe post-login because the
// d3d9-on-d3d12 wrapper has finished all its one-time init work.
IntPtr earlyModule = GetModuleHandleA("d3d9.dll");
if (earlyModule != IntPtr.Zero)
{
RynthLog.D3D9("D3D9Bootstrapper: d3d9.dll loaded — discovering EndScene via NULLREF device.");
EndSceneHook.Install("post-login-vtable");
return;
}
RynthLog.D3D9("D3D9Bootstrapper: Waiting for d3d9.dll so RynthCore can hook the real device creation path.");
DateTime fallbackDeadline = DateTime.UtcNow.AddMilliseconds(BootstrapFallbackMs);
while (!EndSceneHook.IsInstalled())
{
IntPtr d3d9Module = GetModuleHandleA("d3d9.dll");
if (d3d9Module != IntPtr.Zero)
{
TryHookDirect3DCreate9(d3d9Module);
if (_realDeviceObserved || EndSceneHook.IsInstalled())
return;
}
if (DateTime.UtcNow >= fallbackDeadline)
{
RynthLog.D3D9("D3D9Bootstrapper: Real CreateDevice path was not observed in time. Falling back to shared vtable discovery.");
RemoveBootstrapHooks();
EndSceneHook.Install();
return;
}
Thread.Sleep(PollIntervalMs);
}
}
catch (Exception ex)
{
RynthLog.D3D9($"D3D9Bootstrapper: FATAL bootstrap error: {ex}");
if (!EndSceneHook.IsInstalled())
{
RynthLog.D3D9("D3D9Bootstrapper: Attempting fallback EndScene install after bootstrap failure.");
RemoveBootstrapHooks();
EndSceneHook.Install();
}
}
}
private static void TryHookDirect3DCreate9(IntPtr d3d9Module)
{
if (_d3dCreateHookInstalled)
return;
IntPtr direct3DCreate9Addr = GetProcAddress(d3d9Module, "Direct3DCreate9");
if (direct3DCreate9Addr == IntPtr.Zero)
{
RynthLog.D3D9($"D3D9Bootstrapper: Direct3DCreate9 export unavailable (error {Marshal.GetLastWin32Error()}).");
return;
}
_direct3DCreate9Target = direct3DCreate9Addr;
_direct3DCreate9Detour = Direct3DCreate9Detour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_direct3DCreate9Detour);
_originalDirect3DCreate9 = Marshal.GetDelegateForFunctionPointer<Direct3DCreate9Delegate>(MinHook.HookCreate(direct3DCreate9Addr, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(direct3DCreate9Addr);
_d3dCreateHookInstalled = true;
RynthLog.D3D9($"D3D9Bootstrapper: Hooked Direct3DCreate9 @ 0x{direct3DCreate9Addr:X8}");
}
private static IntPtr Direct3DCreate9Detour(uint sdkVersion)
{
// The call-through happens unconditionally, outside any try/catch —
// it must always run so the game gets its real IDirect3D9 regardless
// of what our own bootstrapping below does.
IntPtr direct3D9 = _originalDirect3DCreate9!(sdkVersion);
// Deep-audit finding #11 (2026-06-18): everything past the
// call-through is a delegate-marshalled reverse-P/Invoke callback
// with no try/catch. TryHookCreateDevice can throw
// InvalidOperationException out of MinHook.HookCreate/Enable — an
// escaping exception here fail-fasts the whole client. Wrapped for
// parity even though the logging above it can't realistically throw.
try
{
if (sdkVersion != D3DSdkVersion)
RynthLog.D3D9($"D3D9Bootstrapper: Direct3DCreate9 called with SDK {sdkVersion} (expected {D3DSdkVersion}).");
if (direct3D9 == IntPtr.Zero)
{
RynthLog.D3D9("D3D9Bootstrapper: Direct3DCreate9 returned null.");
return direct3D9;
}
TryHookCreateDevice(direct3D9);
}
catch (Exception ex)
{
try { RynthLog.D3D9($"D3D9Bootstrapper: Direct3DCreate9Detour post-processing threw {ex.GetType().Name}: {ex.Message} — degrading to no CreateDevice hook."); }
catch { }
}
return direct3D9;
}
private static void TryHookCreateDevice(IntPtr direct3D9)
{
if (_createDeviceHookInstalled)
return;
// Genuinely unguarded path per the audit: MinHook.HookCreate/Enable can
// throw InvalidOperationException. Log and swallow — the caller already
// has the real direct3D9 pointer from the call-through, so degrading to
// "no CreateDevice hook installed" is a safe no-op, not a crash.
try
{
IntPtr vtable = Marshal.ReadIntPtr(direct3D9);
_createDeviceTarget = Marshal.ReadIntPtr(vtable, D3D9VTableIndex.CreateDevice * IntPtr.Size);
if (_createDeviceTarget == IntPtr.Zero)
{
RynthLog.D3D9("D3D9Bootstrapper: IDirect3D9::CreateDevice pointer was null.");
return;
}
_createDeviceDetour = CreateDeviceDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_createDeviceDetour);
_originalCreateDevice = Marshal.GetDelegateForFunctionPointer<CreateDeviceDelegate>(MinHook.HookCreate(_createDeviceTarget, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(_createDeviceTarget);
_createDeviceHookInstalled = true;
RynthLog.D3D9($"D3D9Bootstrapper: Hooked IDirect3D9::CreateDevice @ 0x{_createDeviceTarget:X8}");
}
catch (Exception ex)
{
try { RynthLog.D3D9($"D3D9Bootstrapper: TryHookCreateDevice threw {ex.GetType().Name}: {ex.Message} — CreateDevice hook not installed."); }
catch { }
}
}
private static void RemoveBootstrapHooks()
{
if (_d3dCreateHookInstalled && _direct3DCreate9Target != IntPtr.Zero)
{
int status = MinHook.MH_DisableHook(_direct3DCreate9Target);
RynthLog.D3D9($"D3D9Bootstrapper: Disable Direct3DCreate9 hook = {MinHook.StatusString(status)}");
status = MinHook.MH_RemoveHook(_direct3DCreate9Target);
RynthLog.D3D9($"D3D9Bootstrapper: Remove Direct3DCreate9 hook = {MinHook.StatusString(status)}");
_d3dCreateHookInstalled = false;
}
if (_createDeviceHookInstalled && _createDeviceTarget != IntPtr.Zero)
{
int status = MinHook.MH_DisableHook(_createDeviceTarget);
RynthLog.D3D9($"D3D9Bootstrapper: Disable CreateDevice hook = {MinHook.StatusString(status)}");
status = MinHook.MH_RemoveHook(_createDeviceTarget);
RynthLog.D3D9($"D3D9Bootstrapper: Remove CreateDevice hook = {MinHook.StatusString(status)}");
_createDeviceHookInstalled = false;
}
}
private static int CreateDeviceDetour(
IntPtr pD3D9,
uint adapter,
uint deviceType,
IntPtr hFocusWindow,
uint behaviorFlags,
IntPtr pPresentationParameters,
out IntPtr ppDevice)
{
// Call-through happens unconditionally, outside any try/catch, same
// rationale as Direct3DCreate9Detour above.
int hr = _originalCreateDevice!(
pD3D9,
adapter,
deviceType,
hFocusWindow,
behaviorFlags,
pPresentationParameters,
out ppDevice);
// Deep-audit finding #11: wrapped for parity with Direct3DCreate9Detour.
// This path is already pre-contained by InstallFromDevice ->
// InstallFromEndSceneAddress's own try/catch, but a throw from
// RemoveBootstrapHooks (MinHook calls) before that point was not.
try
{
if (hr >= 0 && ppDevice != IntPtr.Zero)
{
_realDeviceObserved = true;
RynthLog.D3D9($"D3D9Bootstrapper: Observed real device creation (device=0x{ppDevice:X8}, hwnd=0x{hFocusWindow:X8}, hr=0x{hr:X8}).");
RemoveBootstrapHooks();
EndSceneHook.InstallFromDevice(ppDevice);
}
else
{
RynthLog.D3D9($"D3D9Bootstrapper: CreateDevice returned hr=0x{hr:X8}, device=0x{ppDevice:X8}");
}
}
catch (Exception ex)
{
try { RynthLog.D3D9($"D3D9Bootstrapper: CreateDeviceDetour post-processing threw {ex.GetType().Name}: {ex.Message}."); }
catch { }
}
return hr;
}
}

View file

@ -0,0 +1,613 @@
// ═══════════════════════════════════════════════════════════════════════════
// RynthCore.Engine — D3D9/D3D9VTable.cs
// Creates a throwaway D3D9 device to harvest vtable function pointers.
// The vtable is shared across all IDirect3DDevice9 instances in the process,
// so the addresses we read here apply to the game's real device.
// ═══════════════════════════════════════════════════════════════════════════
using System;
using System.Runtime.InteropServices;
using RynthCore.Engine.Compatibility;
namespace RynthCore.Engine.D3D9;
/// <summary>
/// IDirect3DDevice9 vtable indices (x86, standard d3d9.h order).
/// </summary>
internal static class DeviceVTableIndex
{
public const int Release = 2;
public const int GetCreationParameters = 9;
public const int CreateAdditionalSwapChain = 13;
public const int Reset = 16;
public const int GetBackBuffer = 18;
public const int CreateTexture = 23;
public const int BeginScene = 41;
public const int EndScene = 42;
public const int Clear = 43;
public const int SetTransform = 44;
public const int GetTransform = 45;
public const int GetRenderTarget = 38;
public const int SetRenderTarget = 37;
public const int SetViewport = 47;
public const int GetViewport = 48;
public const int GetTexture = 64;
public const int SetRenderState = 57;
public const int GetRenderState = 58;
public const int SetTexture = 65;
public const int GetTextureStageState = 66;
public const int SetTextureStageState = 67;
public const int GetSamplerState = 68;
public const int SetSamplerState = 69;
public const int SetScissorRect = 75;
public const int GetScissorRect = 76;
public const int DrawPrimitive = 81;
public const int DrawIndexedPrimitive = 82;
public const int DrawPrimitiveUP = 83;
public const int DrawIndexedPrimitiveUP = 84;
public const int SetFVF = 89;
public const int GetFVF = 90;
public const int SetVertexShader = 92;
public const int GetVertexShader = 93;
public const int SetStreamSource = 100;
public const int GetStreamSource = 101;
public const int SetIndices = 104;
public const int GetIndices = 105;
public const int SetPixelShader = 107;
public const int GetPixelShader = 108;
public const int CreateStateBlock = 60;
}
/// <summary>
/// IDirect3DStateBlock9 vtable indices.
/// </summary>
internal static class StateBlockVTableIndex
{
public const int Release = 2;
public const int Capture = 4;
public const int Apply = 5;
}
/// <summary>
/// IDirect3DTexture9 vtable indices.
/// </summary>
internal static class TextureVTableIndex
{
public const int Release = 2;
public const int LockRect = 19;
public const int UnlockRect = 20;
}
/// <summary>
/// IDirect3DSwapChain9 vtable indices.
/// </summary>
internal static class SwapChain9VTableIndex
{
public const int Release = 2;
public const int Present = 3;
// IDirect3DSwapChain9 vtable: 3=Present, 4=GetFrontBufferData, 5=GetBackBuffer.
public const int GetBackBuffer = 5;
}
/// <summary>
/// IDirect3DSurface9 vtable indices.
/// </summary>
internal static class Surface9VTableIndex
{
public const int Release = 2;
}
/// <summary>
/// IDirect3D9 vtable indices.
/// </summary>
internal static class D3D9VTableIndex
{
public const int Release = 2;
public const int CreateDevice = 16;
}
/// <summary>
/// Reads the IDirect3DDevice9 vtable by creating (and immediately releasing)
/// a temporary device + hidden window.
/// Also provides <see cref="ScanModuleForDeviceVTable"/> which finds the vtable
/// by scanning d3d9.dll's module image — no device creation required.
/// </summary>
internal static unsafe class D3D9VTable
{
// ─── D3D9 constants ───────────────────────────────────────────────
private const uint D3D_SDK_VERSION = 32;
private const uint D3DDEVTYPE_HAL = 1;
private const uint D3DDEVTYPE_NULLREF = 4;
private const uint D3DCREATE_SOFTWARE_VERTEXPROCESSING = 0x00000020;
private const uint D3DCREATE_MULTITHREADED = 0x00000004;
private const uint D3DFMT_UNKNOWN = 0;
private const uint D3DSWAPEFFECT_DISCARD = 1;
// ─── Win32 ────────────────────────────────────────────────────────
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr CreateWindowExA(
uint dwExStyle, string lpClassName, string lpWindowName,
uint dwStyle, int x, int y, int nWidth, int nHeight,
IntPtr hWndParent, IntPtr hMenu, IntPtr hInstance, IntPtr lpParam);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool DestroyWindow(IntPtr hWnd);
[DllImport("kernel32.dll")]
private static extern IntPtr GetModuleHandleA(string? lpModuleName);
// ─── D3D9 ─────────────────────────────────────────────────────────
[DllImport("d3d9.dll")]
private static extern IntPtr Direct3DCreate9(uint SDKVersion);
// ─── COM Release delegate ─────────────────────────────────────────
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate uint ReleaseDelegate(IntPtr pThis);
// ─── IDirect3D9::CreateDevice delegate ────────────────────────────
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int CreateDeviceDelegate(
IntPtr pD3D9,
uint Adapter,
uint DeviceType,
IntPtr hFocusWindow,
uint BehaviorFlags,
IntPtr pPresentationParameters,
out IntPtr ppDevice);
// ─── D3DPRESENT_PARAMETERS (x86 layout) ───────────────────────────
[StructLayout(LayoutKind.Sequential)]
private struct D3DPRESENT_PARAMETERS
{
public uint BackBufferWidth;
public uint BackBufferHeight;
public uint BackBufferFormat; // D3DFORMAT
public uint BackBufferCount;
public uint MultiSampleType; // D3DMULTISAMPLE_TYPE
public uint MultiSampleQuality;
public uint SwapEffect; // D3DSWAPEFFECT
public IntPtr hDeviceWindow;
public int Windowed; // BOOL
public int EnableAutoDepthStencil; // BOOL
public uint AutoDepthStencilFormat; // D3DFORMAT
public uint Flags;
public uint FullScreen_RefreshRateInHz;
public uint PresentationInterval;
}
/// <summary>
/// Creates a temp D3D9 device and returns a copy of the device vtable
/// (array of function pointers). Returns null on failure.
/// </summary>
public static IntPtr[]? GetDeviceVTable(int numEntries = 119)
{
IntPtr hWnd = IntPtr.Zero;
IntPtr pD3D9 = IntPtr.Zero;
IntPtr pDevice = IntPtr.Zero;
try
{
// Create a hidden window
hWnd = CreateWindowExA(
0, "STATIC", "RynthCore_D3D9_Temp", 0,
0, 0, 1, 1,
IntPtr.Zero, IntPtr.Zero,
GetModuleHandleA(null), IntPtr.Zero);
if (hWnd == IntPtr.Zero)
{
RynthLog.D3D9("D3D9VTable: Failed to create temp window.");
return null;
}
// Create IDirect3D9
pD3D9 = Direct3DCreate9(D3D_SDK_VERSION);
if (pD3D9 == IntPtr.Zero)
{
RynthLog.D3D9("D3D9VTable: Direct3DCreate9 failed.");
return null;
}
// Set up present parameters
var pp = new D3DPRESENT_PARAMETERS
{
BackBufferWidth = 1,
BackBufferHeight = 1,
BackBufferFormat = D3DFMT_UNKNOWN,
BackBufferCount = 1,
SwapEffect = D3DSWAPEFFECT_DISCARD,
hDeviceWindow = hWnd,
Windowed = 1, // TRUE
};
// Call IDirect3D9::CreateDevice via vtable
IntPtr d3d9VTable = Marshal.ReadIntPtr(pD3D9); // pD3D9->lpVtbl
IntPtr createDeviceAddr = Marshal.ReadIntPtr(d3d9VTable, D3D9VTableIndex.CreateDevice * IntPtr.Size);
var createDevice = Marshal.GetDelegateForFunctionPointer<CreateDeviceDelegate>(createDeviceAddr);
IntPtr ppAlloc = Marshal.AllocHGlobal(Marshal.SizeOf<D3DPRESENT_PARAMETERS>());
Marshal.StructureToPtr(pp, ppAlloc, false);
// Try NULLREF device first — it doesn't touch the GPU, avoiding
// race conditions with the game's render thread on the real HAL device.
int hr = createDevice(
pD3D9,
0, // D3DADAPTER_DEFAULT
D3DDEVTYPE_NULLREF,
hWnd,
D3DCREATE_SOFTWARE_VERTEXPROCESSING | D3DCREATE_MULTITHREADED,
ppAlloc,
out pDevice);
if (hr < 0 || pDevice == IntPtr.Zero)
{
RynthLog.D3D9($"D3D9VTable: NULLREF device failed (hr=0x{hr:X8}), trying HAL fallback.");
Marshal.StructureToPtr(pp, ppAlloc, false);
hr = createDevice(
pD3D9,
0,
D3DDEVTYPE_HAL,
hWnd,
D3DCREATE_SOFTWARE_VERTEXPROCESSING | D3DCREATE_MULTITHREADED,
ppAlloc,
out pDevice);
}
Marshal.FreeHGlobal(ppAlloc);
if (hr < 0 || pDevice == IntPtr.Zero)
{
RynthLog.D3D9($"D3D9VTable: CreateDevice failed, HRESULT=0x{hr:X8}");
return null;
}
// Read the device vtable
IntPtr deviceVTable = Marshal.ReadIntPtr(pDevice); // pDevice->lpVtbl
var vtable = new IntPtr[numEntries];
for (int i = 0; i < numEntries; i++)
vtable[i] = Marshal.ReadIntPtr(deviceVTable, i * IntPtr.Size);
RynthLog.D3D9($"D3D9VTable: Captured {numEntries} entries. " +
$"EndScene=0x{vtable[DeviceVTableIndex.EndScene]:X8}");
return vtable;
}
catch (Exception ex)
{
RynthLog.D3D9($"D3D9VTable: Exception: {ex.Message}");
return null;
}
finally
{
// Release the temp device and D3D9 object
if (pDevice != IntPtr.Zero)
{
IntPtr vtbl = Marshal.ReadIntPtr(pDevice);
IntPtr releaseAddr = Marshal.ReadIntPtr(vtbl, DeviceVTableIndex.Release * IntPtr.Size);
var release = Marshal.GetDelegateForFunctionPointer<ReleaseDelegate>(releaseAddr);
release(pDevice);
}
if (pD3D9 != IntPtr.Zero)
{
IntPtr vtbl = Marshal.ReadIntPtr(pD3D9);
IntPtr releaseAddr = Marshal.ReadIntPtr(vtbl, D3D9VTableIndex.Release * IntPtr.Size);
var release = Marshal.GetDelegateForFunctionPointer<ReleaseDelegate>(releaseAddr);
release(pD3D9);
}
if (hWnd != IntPtr.Zero)
DestroyWindow(hWnd);
}
}
/// <summary>
/// Scans the loaded d3d9.dll module image for the IDirect3DDevice9 vtable
/// without creating any D3D9 objects. This avoids the thread-safety hazard
/// of creating a throwaway device while the game's real device is rendering.
/// Returns null if the scan cannot find a valid candidate.
/// </summary>
public static IntPtr[]? ScanModuleForDeviceVTable(int numEntries = 119)
{
IntPtr hModule = GetModuleHandleA("d3d9.dll");
if (hModule == IntPtr.Zero)
{
RynthLog.D3D9("D3D9VTable: d3d9.dll not loaded — module scan skipped.");
return null;
}
const int MaxReasonableModuleSize = 50 * 1024 * 1024;
if (!TryReadModuleImageSize(hModule, out int imageSize) || imageSize < 0x2000 || imageSize > MaxReasonableModuleSize)
{
RynthLog.D3D9($"D3D9VTable: d3d9.dll PE headers unusable (imageSize=0x{imageSize:X}) — module scan skipped.");
return null;
}
int baseAddr = hModule.ToInt32();
int vtableByteLen = numEntries * 4; // x86 pointer size
RynthLog.D3D9($"D3D9VTable: Reading d3d9.dll (0x{baseAddr:X8}, 0x{imageSize:X} bytes)...");
// Copy module into managed memory page-by-page, skipping any
// uncommitted pages. SizeOfImage can exceed committed memory
// and NativeAOT cannot catch the resulting AccessViolationException.
byte[] image = new byte[imageSize];
int readableBytes = 0;
const int PageSize = 0x1000;
for (int off = 0; off < imageSize; off += PageSize)
{
int chunk = Math.Min(PageSize, imageSize - off);
IntPtr addr = IntPtr.Add(hModule, off);
if (SmartBoxLocator.IsMemoryReadable(addr, chunk))
{
Marshal.Copy(addr, image, off, chunk);
readableBytes += chunk;
}
}
if (readableBytes < vtableByteLen + 0x1000)
{
RynthLog.D3D9($"D3D9VTable: Only {readableBytes} readable bytes in d3d9.dll — too small for vtable scan.");
return null;
}
RynthLog.D3D9($"D3D9VTable: Scanning d3d9.dll ({readableBytes} readable bytes) for {numEntries}-entry device vtable...");
// Collect ALL candidate vtables. d3d9.dll on Windows 11 can contain
// multiple vtables (inner implementation + outer proxy). The game's
// device typically uses the LAST one (the outer proxy layer).
IntPtr[]? bestCandidate = null;
int bestOffset = 0;
int candidateCount = 0;
for (int off = 0x1000; off <= imageSize - vtableByteLen; off += 4)
{
// Fast reject: first 3 entries (QueryInterface, AddRef, Release) must be in-module
int p0 = BitConverter.ToInt32(image, off);
if ((uint)(p0 - baseAddr) >= (uint)imageSize) continue;
int p1 = BitConverter.ToInt32(image, off + 4);
if ((uint)(p1 - baseAddr) >= (uint)imageSize) continue;
int p2 = BitConverter.ToInt32(image, off + 8);
if ((uint)(p2 - baseAddr) >= (uint)imageSize) continue;
// QI, AddRef, Release must be distinct functions
if (p0 == p1 || p1 == p2) continue;
// Count in-module pointers across all entries
int inModule = 3;
for (int i = 3; i < numEntries; i++)
{
int ptr = BitConverter.ToInt32(image, off + i * 4);
if ((uint)(ptr - baseAddr) < (uint)imageSize)
inModule++;
}
// Require ≥95% in-module (113 of 119)
if (inModule < numEntries * 95 / 100) continue;
// EndScene (42) and BeginScene (41) must differ
int esPtr = BitConverter.ToInt32(image, off + DeviceVTableIndex.EndScene * 4);
int bsPtr = BitConverter.ToInt32(image, off + DeviceVTableIndex.BeginScene * 4);
if (esPtr == bsPtr) continue;
// Verify EndScene starts with a hookable function prologue
int esOff = esPtr - baseAddr;
if ((uint)esOff >= (uint)(imageSize - 3)) continue;
if (!IsRecognizedPrologue(image, esOff)) continue;
candidateCount++;
// Build candidate array
var vtable = new IntPtr[numEntries];
for (int i = 0; i < numEntries; i++)
vtable[i] = new IntPtr(BitConverter.ToInt32(image, off + i * 4));
RynthLog.D3D9($"D3D9VTable: Candidate #{candidateCount} at d3d9+0x{off:X}: " +
$"EndScene=0x{vtable[DeviceVTableIndex.EndScene]:X8} ({inModule}/{numEntries} in-module)");
bestCandidate = vtable;
bestOffset = off;
}
if (bestCandidate != null)
{
RynthLog.D3D9($"D3D9VTable: Using candidate #{candidateCount} (last of {candidateCount}) at d3d9+0x{bestOffset:X}: " +
$"EndScene=0x{bestCandidate[DeviceVTableIndex.EndScene]:X8}");
return bestCandidate;
}
RynthLog.D3D9("D3D9VTable: Module scan found no device vtable candidates.");
return null;
}
private static bool IsRecognizedPrologue(byte[] image, int offset)
{
byte b = image[offset];
if (b == 0x55) return true; // push ebp
if (b == 0x8B && image[offset + 1] == 0xFF) return true; // mov edi,edi (hot-patch)
if (b == 0x83 && image[offset + 1] == 0xEC) return true; // sub esp, imm8
return false;
}
/// <summary>
/// Finds the game's existing IDirect3DDevice9 by scanning process heap memory
/// for a live COM object whose vtable is in d3d9.dll with 119 entries.
/// Completely read-only — no D3D9 API calls, no thread-safety hazards.
/// Returns null if no device is found.
/// </summary>
public static IntPtr[]? FindExistingDeviceVTable(int numEntries = 119)
{
IntPtr d3d9Module = GetModuleHandleA("d3d9.dll");
if (d3d9Module == IntPtr.Zero)
{
RynthLog.D3D9("D3D9VTable: d3d9.dll not loaded — device scan skipped.");
return null;
}
if (!TryReadModuleImageSize(d3d9Module, out int d3d9Size) || d3d9Size < 0x2000)
{
RynthLog.D3D9("D3D9VTable: d3d9.dll PE headers unusable — device scan skipped.");
return null;
}
int d3d9Base = d3d9Module.ToInt32();
int d3d9End = d3d9Base + d3d9Size;
int vtableByteLen = numEntries * 4;
// Pre-read d3d9.dll image so vtable validation reads from safe managed memory
byte[] d3d9Image = new byte[d3d9Size];
int d3d9Readable = 0;
const int PageSize = 0x1000;
for (int off = 0; off < d3d9Size; off += PageSize)
{
int chunk = Math.Min(PageSize, d3d9Size - off);
IntPtr addr = IntPtr.Add(d3d9Module, off);
if (SmartBoxLocator.IsMemoryReadable(addr, chunk))
{
Marshal.Copy(addr, d3d9Image, off, chunk);
d3d9Readable += chunk;
}
}
if (d3d9Readable < vtableByteLen + PageSize)
{
RynthLog.D3D9($"D3D9VTable: Only {d3d9Readable} readable bytes in d3d9.dll — device scan skipped.");
return null;
}
RynthLog.D3D9($"D3D9VTable: Scanning process heap for live D3D9 device (d3d9=0x{d3d9Base:X8}, size=0x{d3d9Size:X})...");
int regionsScanned = 0;
long bytesScanned = 0;
int d3d9Pointers = 0;
IntPtr scanAddr = new IntPtr(0x10000);
while (scanAddr.ToInt32() > 0 && scanAddr.ToInt32() < 0x7FFE0000)
{
if (!VirtualQueryWrapped(scanAddr, out int regionBase, out int regionSize,
out uint state, out uint protect, out uint type))
break;
if (regionSize <= 0) break;
IntPtr nextAddr = new IntPtr(regionBase + regionSize);
// Only scan committed, readable, private (heap) memory
bool committed = (state & 0x1000) != 0; // MEM_COMMIT
bool readable = protect != 0 && (protect & 0x01) == 0 && (protect & 0x100) == 0; // !NOACCESS, !GUARD
bool isPrivate = (type & 0x20000) != 0; // MEM_PRIVATE
if (!committed || !readable || !isPrivate || regionSize < 128)
{
scanAddr = nextAddr;
continue;
}
regionsScanned++;
// Safe page-by-page copy of this region
byte[] regionData = new byte[regionSize];
int regionReadable = 0;
for (int off = 0; off < regionSize; off += PageSize)
{
int chunk = Math.Min(PageSize, regionSize - off);
IntPtr pageAddr = new IntPtr(regionBase + off);
if (SmartBoxLocator.IsMemoryReadable(pageAddr, chunk))
{
Marshal.Copy(pageAddr, regionData, off, chunk);
regionReadable += chunk;
}
}
bytesScanned += regionReadable;
// Scan each dword for a vtable pointer into d3d9.dll
for (int off = 0; off <= regionReadable - 4; off += 4)
{
int value = BitConverter.ToInt32(regionData, off);
if (value < d3d9Base || value >= d3d9End) continue;
d3d9Pointers++;
// Check if this is a 119-entry device vtable
int vtableOffset = value - d3d9Base;
if (vtableOffset + vtableByteLen > d3d9Readable) continue;
int inModule = 0;
for (int i = 0; i < numEntries; i++)
{
int entry = BitConverter.ToInt32(d3d9Image, vtableOffset + i * 4);
if (entry >= d3d9Base && entry < d3d9End)
inModule++;
}
if (inModule < numEntries * 95 / 100) continue;
// BeginScene and EndScene must differ
int bs = BitConverter.ToInt32(d3d9Image, vtableOffset + DeviceVTableIndex.BeginScene * 4);
int es = BitConverter.ToInt32(d3d9Image, vtableOffset + DeviceVTableIndex.EndScene * 4);
if (bs == es) continue;
// EndScene must have a hookable prologue
int esOff = es - d3d9Base;
if ((uint)esOff >= (uint)(d3d9Readable - 3)) continue;
if (!IsRecognizedPrologue(d3d9Image, esOff)) continue;
var vtable = new IntPtr[numEntries];
for (int i = 0; i < numEntries; i++)
vtable[i] = new IntPtr(BitConverter.ToInt32(d3d9Image, vtableOffset + i * 4));
int objectAddr = regionBase + off;
RynthLog.D3D9($"D3D9VTable: Found live device at 0x{objectAddr:X8}, vtable=0x{value:X8} (d3d9+0x{vtableOffset:X}), " +
$"EndScene=0x{vtable[DeviceVTableIndex.EndScene]:X8} ({inModule}/{numEntries} in-module)");
RynthLog.D3D9($"D3D9VTable: Heap scan stats: {regionsScanned} regions, {bytesScanned / 1024}KB, {d3d9Pointers} d3d9 pointers checked.");
return vtable;
}
scanAddr = nextAddr;
}
RynthLog.D3D9($"D3D9VTable: No live device found — {regionsScanned} regions, {bytesScanned / 1024}KB, {d3d9Pointers} d3d9 pointers.");
return null;
}
// ─── VirtualQuery wrapper ─────────────────────────────────────────
[DllImport("kernel32.dll", SetLastError = false)]
private static extern int VirtualQuery(IntPtr lpAddress, byte[] lpBuffer, int dwLength);
private static bool VirtualQueryWrapped(IntPtr address, out int regionBase, out int regionSize,
out uint state, out uint protect, out uint type)
{
regionBase = 0; regionSize = 0; state = 0; protect = 0; type = 0;
byte[] buf = new byte[28]; // MEMORY_BASIC_INFORMATION on x86
int result = VirtualQuery(address, buf, 28);
if (result == 0) return false;
regionBase = BitConverter.ToInt32(buf, 0); // BaseAddress
regionSize = BitConverter.ToInt32(buf, 12); // RegionSize
state = BitConverter.ToUInt32(buf, 16); // State
protect = BitConverter.ToUInt32(buf, 20); // Protect
type = BitConverter.ToUInt32(buf, 24); // Type
return true;
}
private static bool TryReadModuleImageSize(IntPtr moduleBase, out int imageSize)
{
imageSize = 0;
try
{
if ((ushort)Marshal.ReadInt16(moduleBase) != 0x5A4D) return false; // MZ
int peOffset = Marshal.ReadInt32(moduleBase, 0x3C);
if (peOffset <= 0) return false;
IntPtr ntHeaders = IntPtr.Add(moduleBase, peOffset);
if ((uint)Marshal.ReadInt32(ntHeaders) != 0x00004550) return false; // PE\0\0
imageSize = Marshal.ReadInt32(ntHeaders, 0x18 + 0x38); // SizeOfImage
return imageSize > 0x1000;
}
catch
{
return false;
}
}
}

View file

@ -0,0 +1,408 @@
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Compatibility;
using RynthCore.Engine.Hooking;
using RynthCore.Engine.ImGuiBackend;
namespace RynthCore.Engine.D3D9;
internal static class EndSceneHook
{
private const int MaxOffscreenSkipLogs = 3;
private const int MaxOffscreenSkipsBeforeFallback = 120;
private const int OffscreenFallbackDelayMs = 3000;
private const int UiInitWarmupFrames = 180;
// ── FPS Governor — set by plugins via API ───────────────────────
internal static bool FpsLimitEnabled;
internal static int FpsTargetFocused = 60;
internal static int FpsTargetBackground = 30;
private static readonly Stopwatch _fpsTimer = Stopwatch.StartNew();
private static bool _fpsLimiterLoggedOnce;
private static int _fpsDebugCounter;
private static long _fpsCounterStart;
private static int _fpsCounterFrames;
/// <summary>
/// Last measured EndScene frames-per-second, refreshed once per second.
/// Updated whether or not the FPS governor is enabled — UI panels (the
/// RynthAi footer) read this for a live frame-rate display. Volatile
/// because writes happen on the AC pump thread and reads happen on the
/// Avalonia dispatcher thread (10 Hz panel tick); double-word atomic on
/// x86 and we don't need a tear-free guarantee on this value.
/// </summary>
internal static volatile float MeasuredFps;
private static long _liveFpsCounterStart;
private static int _liveFpsCounterFrames;
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern uint GetWindowThreadProcessId(IntPtr hwnd, out uint lpdwProcessId);
[DllImport("kernel32.dll")]
private static extern uint GetCurrentProcessId();
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int EndSceneDelegate(IntPtr pDevice);
private static EndSceneDelegate? _originalEndScene;
private static EndSceneDelegate? _hookDelegate;
private static IntPtr _endSceneAddr;
private static bool _installed;
private static int _frameCount;
private static int _renderCount;
private static int _skipCount;
private static int _uiFrameCount;
private static bool _offscreenFilterDisabled;
private static bool _uiActivated;
private static bool _warmupLogged;
private static long _installTick;
private static long _firstOffscreenTick;
private static string _installSource = "uninitialized";
public static void Install()
{
Install("fallback-vtable");
}
public static void Install(string installSource)
{
if (_installed)
return;
ResetInstallState(installSource);
// Vtable discovery uses a NULLREF device to avoid GPU contention
// with the game's render thread. Retry once on failure.
const int maxAttempts = 2;
for (int attempt = 1; attempt <= maxAttempts; attempt++)
{
RynthLog.D3D9($"EndSceneHook: Discovering D3D9 vtable (attempt {attempt}/{maxAttempts})...");
if (attempt > 1)
System.Threading.Thread.Sleep(500);
IntPtr[]? vtable = D3D9VTable.GetDeviceVTable();
if (vtable != null)
{
IntPtr endSceneAddress = vtable[DeviceVTableIndex.EndScene];
RynthLog.D3D9($"EndSceneHook: EndScene @ 0x{endSceneAddress:X8}");
InstallFromEndSceneAddress(endSceneAddress);
return;
}
RynthLog.D3D9($"EndSceneHook: Vtable discovery returned null on attempt {attempt}.");
}
RynthLog.D3D9("EndSceneHook: FAILED - could not discover vtable after all attempts.");
}
public static void InstallFromDevice(IntPtr pDevice)
{
if (_installed)
return;
if (pDevice == IntPtr.Zero)
{
RynthLog.D3D9("EndSceneHook: Real-device install skipped because the device pointer was null.");
return;
}
ResetInstallState("real-device");
IntPtr deviceVTable = Marshal.ReadIntPtr(pDevice);
IntPtr endSceneAddress = Marshal.ReadIntPtr(deviceVTable, DeviceVTableIndex.EndScene * IntPtr.Size);
RynthLog.D3D9($"EndSceneHook: Using real D3D9 device 0x{pDevice:X8}; EndScene @ 0x{endSceneAddress:X8}");
InstallFromEndSceneAddress(endSceneAddress);
}
public static void InstallFromAddress(IntPtr endSceneAddress, string installSource)
{
if (_installed)
return;
if (endSceneAddress == IntPtr.Zero)
{
RynthLog.D3D9("EndSceneHook: Address install skipped because EndScene was null.");
return;
}
ResetInstallState(installSource);
RynthLog.D3D9($"EndSceneHook: Using explicit EndScene address 0x{endSceneAddress:X8} from {installSource}.");
InstallFromEndSceneAddress(endSceneAddress);
}
public static bool IsInstalled()
{
return _installed;
}
public static int GetRenderCount()
{
return _renderCount;
}
public static void Uninstall()
{
if (!_installed)
return;
// Order is critical: disable the detour FIRST so AC's render thread
// stops entering our code, then drain in-flight calls, THEN tear down
// ImGui. If we destroyed the context first, an in-flight EndScene call
// would assert on `GImGui != NULL`.
int status = MinHook.MH_DisableHook(_endSceneAddr);
RynthLog.D3D9($"EndSceneHook: Disable = {MinHook.StatusString(status)}");
// Let the render thread return through the trampoline.
Thread.Sleep(80);
EngineFrameController.Shutdown();
status = MinHook.MH_RemoveHook(_endSceneAddr);
RynthLog.D3D9($"EndSceneHook: Remove = {MinHook.StatusString(status)}");
_installed = false;
_originalEndScene = null;
_offscreenFilterDisabled = false;
}
private static void ResetInstallState(string installSource)
{
_installSource = installSource;
_frameCount = 0;
_renderCount = 0;
_skipCount = 0;
_uiFrameCount = 0;
_offscreenFilterDisabled = false;
_uiActivated = false;
_warmupLogged = false;
_installTick = Environment.TickCount64;
_firstOffscreenTick = 0;
}
private static void InstallFromEndSceneAddress(IntPtr endSceneAddress)
{
_endSceneAddr = endSceneAddress;
_hookDelegate = new EndSceneDelegate(EndSceneDetour);
IntPtr hookPtr = Marshal.GetFunctionPointerForDelegate(_hookDelegate);
try
{
_originalEndScene = Marshal.GetDelegateForFunctionPointer<EndSceneDelegate>(MinHook.HookCreate(_endSceneAddr, hookPtr));
Thread.MemoryBarrier();
MinHook.Enable(_endSceneAddr);
_installed = true;
RynthLog.D3D9($"EndSceneHook: INSTALLED successfully via {_installSource}.");
}
catch (Exception ex)
{
RynthLog.D3D9($"EndSceneHook: MinHook failed - {ex.Message}");
}
}
private static int EndSceneDetour(IntPtr pDevice)
{
// Liveness beacon for MainThreadHangWatchdog — this detour runs on AC's
// main/render thread every frame (even with the ImGui backend disabled),
// so a stalled beat means the main thread is wedged. Must never throw.
try { MainThreadHangWatchdog.MainThreadBeat(); } catch { }
try
{
if (!_offscreenFilterDisabled && !DX9Backend.IsRenderingToBackBuffer(pDevice))
{
if (_firstOffscreenTick == 0)
_firstOffscreenTick = Environment.TickCount64;
if (_skipCount < MaxOffscreenSkipLogs)
RynthLog.D3D9("EndSceneHook: Skipping offscreen EndScene pass.");
_skipCount++;
long offscreenElapsedMs = Environment.TickCount64 - _firstOffscreenTick;
if (_skipCount < MaxOffscreenSkipsBeforeFallback && offscreenElapsedMs < OffscreenFallbackDelayMs)
return _originalEndScene!(pDevice);
_offscreenFilterDisabled = true;
RynthLog.D3D9($"EndSceneHook: Falling back to unfiltered EndScene after {_skipCount} skipped offscreen pass(es) over {offscreenElapsedMs}ms.");
}
_renderCount++;
_frameCount++;
// Per-frame chatbox visibility assertion (no-op unless plugin enables suppression).
try { ChatHooks.TickHide(); } catch { /* never let this bring down EndScene */ }
// Per-frame retail-radar visibility assertion (no-op unless plugin enables suppression).
try { RadarHooks.TickHide(); } catch { /* never let this bring down EndScene */ }
// Per-frame retail-powerbar visibility assertion (no-op unless plugin enables suppression).
try { PowerbarHooks.TickHide(); } catch { /* never let this bring down EndScene */ }
if (_renderCount == 1 && _offscreenFilterDisabled && _skipCount > 0)
{
long installElapsedMs = Environment.TickCount64 - _installTick;
RynthLog.D3D9($"EndSceneHook: First render after offscreen fallback ({_skipCount} skip(s), {installElapsedMs}ms since install).");
}
if (_renderCount == 1 && _skipCount > 0)
RynthLog.D3D9($"EndSceneHook: First backbuffer frame after skipping {_skipCount} offscreen pass(es).");
// On first backbuffer frame, verify we hooked the right function by
// reading the device's own vtable. A mismatch means the module scan
// found an internal/proxy vtable, not the one the game's device uses.
if (_renderCount == 1)
{
IntPtr deviceVtable = Marshal.ReadIntPtr(pDevice);
IntPtr actualEndScene = Marshal.ReadIntPtr(deviceVtable, DeviceVTableIndex.EndScene * IntPtr.Size);
bool match = actualEndScene == _endSceneAddr;
RynthLog.D3D9($"EndSceneHook: Device vtable EndScene=0x{actualEndScene:X8}, hooked=0x{_endSceneAddr:X8} — {(match ? "MATCH" : "MISMATCH")}");
if (!match && actualEndScene != IntPtr.Zero)
{
// Deep-audit finding #8 (2026-06-18): the old sequence
// disabled+REMOVED the old hook (freeing the trampoline
// _originalEndScene points at) BEFORE attempting the new
// install. If the new MH_CreateHook then threw,
// _originalEndScene was never reassigned — it still bound
// the now-freed trampoline — yet the code force-set
// _installed=true and this function's bottom called
// through it: a use-after-free. Fixed order: only remove
// the OLD hook after the NEW one is confirmed installed;
// on failure, re-enable the OLD hook and keep using its
// still-valid trampoline instead of a dangling one.
RynthLog.D3D9("EndSceneHook: Rehooking at the device's actual EndScene address.");
IntPtr oldAddr = _endSceneAddr;
EndSceneDelegate? oldOriginal = _originalEndScene;
MinHook.MH_DisableHook(oldAddr);
InstallFromEndSceneAddress(actualEndScene);
if (_installed)
{
// New hook confirmed live — safe to free the old
// trampoline now.
MinHook.MH_RemoveHook(oldAddr);
return _originalEndScene!(pDevice);
}
RynthLog.D3D9("EndSceneHook: Rehook failed — restoring original hook.");
// New install failed (InstallFromEndSceneAddress leaves
// _installed=false on failure). Restore the OLD hook
// rather than trust a dangling delegate.
_endSceneAddr = oldAddr;
_originalEndScene = oldOriginal;
MinHook.Enable(oldAddr);
_installed = true;
}
}
if (!_uiActivated)
{
if (!_warmupLogged)
{
RynthLog.D3D9($"EndSceneHook: Backbuffer detected. Warming up {UiInitWarmupFrames} frame(s) before UI init.");
_warmupLogged = true;
}
if (_renderCount < UiInitWarmupFrames)
return _originalEndScene!(pDevice);
_uiActivated = true;
RynthLog.D3D9("EndSceneHook: Warmup complete - initializing ImGui.");
}
// EngineFrameController.OnEndScene runs the always-on engine work
// (matrix capture, plugin tick, nav rendering, pending action drains)
// every frame. The EnableImGuiBackend gate moved INSIDE the
// controller so it scopes only the ImGui-specific block; this call
// site no longer needs to gate it.
EngineFrameController.OnEndScene(pDevice);
_uiFrameCount++;
if (_uiFrameCount == 60 && RynthCore.Engine.Plugins.EngineSettings.EnableImGuiBackend)
RynthLog.D3D9("EndSceneHook: 60 UI frames - ImGui is stable.");
if (_renderCount == UiInitWarmupFrames && !RynthCore.Engine.Plugins.EngineSettings.EnableImGuiBackend)
RynthLog.D3D9("EndSceneHook: ImGui backend disabled via engine.json (EnableImGuiBackend=false). Always-on engine work still runs; only ImGui draw calls are skipped.");
// Avalonia compositor: independent of ImGui. Reads the latest
// Avalonia surface from OverlaySurfaceBridge and blits it as a
// fullscreen alpha-blended quad onto AC's back buffer. Runs every
// frame regardless of EnableImGuiBackend so the Avalonia overlay
// is visible even when ImGui per-frame work is disabled. Driven
// here exclusively — EngineFrameController.OnEndScene intentionally
// does NOT call it (avoids double-blit / TryConsume races).
try
{
OverlayTextureRenderer.Render(pDevice);
}
catch (Exception ovEx)
{
if (_uiFrameCount < 30)
RynthLog.D3D9($"EndSceneHook: OverlayTextureRenderer.Render error: {ovEx.GetType().Name}: {ovEx.Message}");
}
}
catch (Exception ex)
{
if (_uiFrameCount < 30)
RynthLog.D3D9($"EndSceneHook: Frame {_frameCount} error: {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}");
}
// ── Always-on FPS measurement for UI footer ──────────────────
// Runs whether or not the governor is enabled so the RynthAi
// footer can show a live FPS even when the user hasn't capped.
// Cheap: one increment + a once-per-second division.
_liveFpsCounterFrames++;
long liveNow = Environment.TickCount64;
if (_liveFpsCounterStart == 0) _liveFpsCounterStart = liveNow;
long liveElapsed = liveNow - _liveFpsCounterStart;
if (liveElapsed >= 1000)
{
MeasuredFps = (float)(_liveFpsCounterFrames * 1000.0 / liveElapsed);
_liveFpsCounterFrames = 0;
_liveFpsCounterStart = liveNow;
}
// ── FPS Governor (matches proven NexSuite2 pattern) ─────────
if (FpsLimitEnabled)
{
IntPtr fgWnd = GetForegroundWindow();
// Focused when AC itself is foreground, OR when any window belonging
// to our process is foreground (covers DComp overlay, any Avalonia
// child window, etc.). PID comparison is reliable regardless of how
// the owner chain was established (GWL_HWNDPARENT vs CreateWindow).
GetWindowThreadProcessId(fgWnd, out uint fgPid);
bool isFocused = fgWnd != IntPtr.Zero &&
(fgWnd == Win32Backend.GameHwnd || fgPid == GetCurrentProcessId());
int targetFps = isFocused ? FpsTargetFocused : FpsTargetBackground;
double minFrameMs = 1000.0 / Math.Max(targetFps, 1);
while (_fpsTimer.Elapsed.TotalMilliseconds < minFrameMs)
Thread.Sleep(isFocused ? 0 : 1);
_fpsTimer.Restart();
if (!_fpsLimiterLoggedOnce)
{
_fpsLimiterLoggedOnce = true;
RynthLog.D3D9($"EndSceneHook: FPS governor active — max={FpsTargetFocused} focused, max={FpsTargetBackground} background, gameHwnd=0x{Win32Backend.GameHwnd.ToInt64():X}");
}
// Periodic FPS measurement — log every 60 seconds
_fpsCounterFrames++;
long now = Environment.TickCount64;
if (_fpsCounterStart == 0) _fpsCounterStart = now;
long elapsedMs = now - _fpsCounterStart;
if (elapsedMs >= 60_000)
{
double measuredFps = _fpsCounterFrames * 1000.0 / elapsedMs;
RynthLog.D3D9($"EndSceneHook: FPS={measuredFps:F1} (target={targetFps}, {(isFocused ? "focused" : "background")})");
_fpsCounterFrames = 0;
_fpsCounterStart = now;
}
}
return _originalEndScene!(pDevice);
}
}

View file

@ -0,0 +1,374 @@
// ═══════════════════════════════════════════════════════════════════════════
// RynthCore.Engine — D3D9/GameMatrixCapture.cs
// Captures the game's camera transform and perspective Projection matrix
// for WorldToScreen projection.
//
// AC sets View=identity and World=identity — it transforms all vertices
// on the CPU before sending to D3D9. Only the Projection matrix is real.
//
// Strategy:
// - Hook SetTransform to capture the perspective Projection matrix.
// - Read the camera position + rotation from SmartBox memory.
// - Build the View matrix manually, then ViewProj = View * Proj.
// ═══════════════════════════════════════════════════════════════════════════
using System;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Compatibility;
using RynthCore.Engine.Hooking;
namespace RynthCore.Engine.D3D9;
internal static unsafe class GameMatrixCapture
{
private const uint D3DTS_PROJECTION = 3;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int SetTransformD(IntPtr dev, uint state, float* pMatrix);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int GetViewportD(IntPtr dev, int* pViewport);
// SetTransform hook
private static SetTransformD? _originalSetTransform;
private static SetTransformD? _hookDelegate;
private static bool _hookInstalled;
// Viewport
private static GetViewportD? _getViewport;
private static bool _viewportCached;
private static uint _vpWidth;
private static uint _vpHeight;
private static bool _hasViewport;
// Captured Projection matrix
private static readonly float[] _perspProj = new float[16];
private static bool _hasProj;
// Computed matrices
private static readonly float[] _viewMatrix = new float[16];
private static readonly float[] _viewProj = new float[16];
private static bool _hasValidViewProj;
// Camera frame from SmartBox memory.
// AC's Position struct: PackObj.vfptr (4) + objcell_id (4) + Frame (...).
// Frame is qw,qx,qy,qz (16) + m_fl2gv[9] (36) + m_fOrigin (12) = 64 bytes.
// So at Position start (+0x08 from SmartBox):
// +0x00 PackObj.vfptr (4)
// +0x04 objcell_id (4) ← real viewer cellId
// +0x08 Frame.qw,qx,qy,qz (16)
// +0x18 Frame.m_fl2gv[9] (36) ← cached 3x3 rotation matrix
// +0x3C Frame.m_fOrigin (12) ← camera position (x, y, z)
private const int CameraFrameOffset = 0x08;
private const int CamCellIdOffset = 0x04; // viewer cellId (skips PackObj.vfptr)
private const int CamRotOffset = 0x18;
private const int CamPosOffset = 0x3C;
// Diagnostics
private static int _framesSinceLog;
private static bool _loggedFirstCapture;
public static bool HasCapturedFrame => _hasValidViewProj;
public static uint ViewportWidth => _vpWidth;
public static uint ViewportHeight => _vpHeight;
/// <summary>Copy the 4x4 View matrix (row-major) into the destination.</summary>
public static void GetViewMatrix(ref float dest)
{
fixed (float* s = _viewMatrix)
fixed (float* d = &dest)
{
for (int i = 0; i < 16; i++)
d[i] = s[i];
}
}
/// <summary>Copy the 4x4 Projection matrix (row-major) into the destination.</summary>
public static void GetProjectionMatrix(ref float dest)
{
fixed (float* s = _perspProj)
fixed (float* d = &dest)
{
for (int i = 0; i < 16; i++)
d[i] = s[i];
}
}
private static int SetTransformDetour(IntPtr dev, uint state, float* pMatrix)
{
if (pMatrix != null && state == D3DTS_PROJECTION)
{
bool isPerspective = Math.Abs(pMatrix[11]) > 0.01f;
if (isPerspective)
{
for (int i = 0; i < 16; i++)
_perspProj[i] = pMatrix[i];
_hasProj = true;
}
}
return _originalSetTransform!(dev, state, pMatrix);
}
public static void CaptureFrame(IntPtr pDevice)
{
if (pDevice == IntPtr.Zero)
return;
if (!_hookInstalled)
InstallHook(pDevice);
// Read viewport
if (!_viewportCached)
{
IntPtr vtable = Marshal.ReadIntPtr(pDevice);
_getViewport = Marshal.GetDelegateForFunctionPointer<GetViewportD>(
Marshal.ReadIntPtr(vtable, DeviceVTableIndex.GetViewport * IntPtr.Size));
_viewportCached = true;
}
int* vp = stackalloc int[6];
if (_getViewport!(pDevice, vp) >= 0 && vp[2] > 0 && vp[3] > 0)
{
_vpWidth = (uint)vp[2];
_vpHeight = (uint)vp[3];
_hasViewport = true;
}
if (_hasProj)
BuildViewProjFromCamera();
_framesSinceLog++;
if (_framesSinceLog >= 3000)
{
_framesSinceLog = 0;
RynthLog.D3D9($"GameMatrixCapture: valid={_hasValidViewProj} vp={_vpWidth}x{_vpHeight}");
}
}
private static void BuildViewProjFromCamera()
{
if (!SmartBoxLocator.TryGetSmartBox(out IntPtr smartBox, out _, out _))
return;
IntPtr camFrame = smartBox + CameraFrameOffset;
if (!SmartBoxLocator.IsMemoryReadable(camFrame + CamPosOffset, 12))
return;
// Read 3x3 rotation matrix
float m11 = ReadFloat(camFrame + CamRotOffset + 0);
float m12 = ReadFloat(camFrame + CamRotOffset + 4);
float m13 = ReadFloat(camFrame + CamRotOffset + 8);
float m21 = ReadFloat(camFrame + CamRotOffset + 12);
float m22 = ReadFloat(camFrame + CamRotOffset + 16);
float m23 = ReadFloat(camFrame + CamRotOffset + 20);
float m31 = ReadFloat(camFrame + CamRotOffset + 24);
float m32 = ReadFloat(camFrame + CamRotOffset + 28);
float m33 = ReadFloat(camFrame + CamRotOffset + 32);
// Read position (AC physics: x=EW, y=NS, z=height)
float cx = ReadFloat(camFrame + CamPosOffset + 0);
float cy = ReadFloat(camFrame + CamPosOffset + 4);
float cz = ReadFloat(camFrame + CamPosOffset + 8);
if (cx == 0f && cy == 0f && cz == 0f)
return;
// The camera's pose is stored landblock-local: as the camera orbits
// across a landblock boundary, AC re-anchors the viewer to the new
// landblock and (cx, cy) jumps to that landblock's frame. Plugins
// submitting Nav3D markers around the player are in the PLAYER's
// landblock frame, so we shift the camera back into that frame here.
// Without this, every marker visually leaps 192 m when the camera
// crosses a landblock boundary even though the player hasn't moved.
//
// Guards: the viewer cellId can briefly hold uninitialized / mid-
// teleport junk (e.g. landblock 0x0001 while the world isn't loaded)
// that gives a multi-thousand-meter "delta" and produces a wildly
// wrong view matrix. Only apply the shift when both landblocks look
// like real outdoor world landblocks AND the delta is within ±4
// landblocks (no legitimate camera frustum reaches further).
float rawCx = cx, rawCy = cy;
bool shiftApplied = false;
int dXBlocks = 0, dYBlocks = 0;
uint viewerLbForLog = 0, playerLbForLog = 0;
bool guardBlocked = false;
string guardReason = "";
uint viewerCellId = unchecked((uint)Marshal.ReadInt32(camFrame + CamCellIdOffset));
uint viewerLandblock = viewerCellId >> 16;
viewerLbForLog = viewerLandblock;
// Prefer the landblock the plugin tick LOCKED IN when it submitted
// its Nav3D geometry (see Nav3DRenderer.ClearFrame). If we use the
// CURRENT player landblock instead, render and triangles disagree
// for the frames between the player crossing a boundary and the next
// plugin tick re-submitting — geometry jumps to the adjacent
// landblock for ~1 s and snaps back. Fall back to current player
// landblock when no submission frame is published (zero).
uint submissionLandblock = Nav3DRenderer.ReadyPlayerLandblock;
bool havePose;
uint playerCellId;
if (submissionLandblock != 0)
{
havePose = true;
playerCellId = submissionLandblock << 16;
}
else
{
havePose = PlayerPhysicsHooks.TryGetPlayerPose(out playerCellId, out _, out _, out _,
out _, out _, out _, out _);
}
if (viewerLandblock != 0 && havePose && (playerCellId >> 16) != 0)
{
uint playerLandblock = playerCellId >> 16;
playerLbForLog = playerLandblock;
int viewerLbX = (int)((viewerLandblock >> 8) & 0xFF);
int viewerLbY = (int)(viewerLandblock & 0xFF);
int playerLbX = (int)((playerLandblock >> 8) & 0xFF);
int playerLbY = (int)(playerLandblock & 0xFF);
dXBlocks = viewerLbX - playerLbX;
dYBlocks = viewerLbY - playerLbY;
if (Math.Abs(dXBlocks) <= 4 && Math.Abs(dYBlocks) <= 4 &&
viewerLbX != 0 && viewerLbY != 0)
{
cx += dXBlocks * 192f; // EW shift back into player-landblock frame
cy += dYBlocks * 192f; // NS
shiftApplied = (dXBlocks != 0 || dYBlocks != 0);
}
else
{
guardBlocked = (dXBlocks != 0 || dYBlocks != 0);
guardReason = $"dx={dXBlocks},dy={dYBlocks},vLbX={viewerLbX},vLbY={viewerLbY}";
}
}
// Log when a non-zero shift fires (camera crossed a landblock) or when
// the guard blocked one. Helps catch "paintings move with camera"
// without spamming when player and viewer landblocks agree.
if (shiftApplied || guardBlocked)
{
RynthLog.D3D9($"GameMatrixCapture: viewer lb=0x{viewerLbForLog:X4} player lb=0x{playerLbForLog:X4} " +
$"d=({dXBlocks},{dYBlocks}) raw=({rawCx:F1},{rawCy:F1}) adj=({cx:F1},{cy:F1}) " +
$"{(shiftApplied ? "SHIFTED" : "GUARD-BLOCKED " + guardReason)}");
}
// View matrix rotation block (D3D Y-up, with AC Y/Z swap).
// AC camera rows: row1=Right, row2=Forward, row3=Up
// After Y/Z component swap → D3D basis vectors as columns:
// col0 = Right_d3d = (m11, m13, m12)
// col1 = Up_d3d = (m31, m33, m32)
// col2 = Forward_d3d = (m21, m23, m22)
_viewMatrix[0] = m11; _viewMatrix[1] = m31; _viewMatrix[2] = m21; _viewMatrix[3] = 0;
_viewMatrix[4] = m13; _viewMatrix[5] = m33; _viewMatrix[6] = m23; _viewMatrix[7] = 0;
_viewMatrix[8] = m12; _viewMatrix[9] = m32; _viewMatrix[10] = m22; _viewMatrix[11] = 0;
// Translation = -CamPos_D3D * R_view
// CamPos_D3D = (cx, cz, cy) after Y/Z swap
float px = cx; // EW
float py = cz; // height (D3D Y)
float pz = cy; // NS (D3D Z)
_viewMatrix[12] = -(px * _viewMatrix[0] + py * _viewMatrix[4] + pz * _viewMatrix[8]);
_viewMatrix[13] = -(px * _viewMatrix[1] + py * _viewMatrix[5] + pz * _viewMatrix[9]);
_viewMatrix[14] = -(px * _viewMatrix[2] + py * _viewMatrix[6] + pz * _viewMatrix[10]);
_viewMatrix[15] = 1;
// ViewProj = View * Projection
fixed (float* v = _viewMatrix)
fixed (float* p = _perspProj)
fixed (float* r = _viewProj)
{
for (int row = 0; row < 4; row++)
for (int col = 0; col < 4; col++)
r[row * 4 + col] =
v[row * 4 + 0] * p[0 * 4 + col] +
v[row * 4 + 1] * p[1 * 4 + col] +
v[row * 4 + 2] * p[2 * 4 + col] +
v[row * 4 + 3] * p[3 * 4 + col];
}
if (!_loggedFirstCapture)
{
_loggedFirstCapture = true;
RynthLog.D3D9($"GameMatrixCapture: camera pos=({cx:F2},{cy:F2},{cz:F2}) [EW,NS,Z]");
RynthLog.D3D9($"GameMatrixCapture: View row0=[{_viewMatrix[0]:F4}, {_viewMatrix[1]:F4}, {_viewMatrix[2]:F4}, {_viewMatrix[3]:F4}]");
RynthLog.D3D9($"GameMatrixCapture: View row1=[{_viewMatrix[4]:F4}, {_viewMatrix[5]:F4}, {_viewMatrix[6]:F4}, {_viewMatrix[7]:F4}]");
RynthLog.D3D9($"GameMatrixCapture: View row2=[{_viewMatrix[8]:F4}, {_viewMatrix[9]:F4}, {_viewMatrix[10]:F4}, {_viewMatrix[11]:F4}]");
RynthLog.D3D9($"GameMatrixCapture: View row3=[{_viewMatrix[12]:F4}, {_viewMatrix[13]:F4}, {_viewMatrix[14]:F4}, {_viewMatrix[15]:F4}]");
RynthLog.D3D9($"GameMatrixCapture: viewport={_vpWidth}x{_vpHeight}");
}
_hasValidViewProj = true;
}
private static float ReadFloat(IntPtr address)
{
int bits = Marshal.ReadInt32(address);
return BitConverter.Int32BitsToSingle(bits);
}
public static bool WorldToScreen(float wx, float wy, float wz, out float sx, out float sy)
{
sx = 0f;
sy = 0f;
if (!_hasValidViewProj || _vpWidth == 0 || _vpHeight == 0)
return false;
float clipX = wx * _viewProj[0] + wy * _viewProj[4] + wz * _viewProj[8] + _viewProj[12];
float clipY = wx * _viewProj[1] + wy * _viewProj[5] + wz * _viewProj[9] + _viewProj[13];
float clipW = wx * _viewProj[3] + wy * _viewProj[7] + wz * _viewProj[11] + _viewProj[15];
if (clipW <= 0.001f)
return false;
float ndcX = clipX / clipW;
float ndcY = clipY / clipW;
sx = (ndcX + 1.0f) * 0.5f * _vpWidth;
sy = (1.0f - ndcY) * 0.5f * _vpHeight;
return true;
}
public static int WorldToScreenCallback(float wx, float wy, float wz, float* sx, float* sy)
{
bool result = WorldToScreen(wx, wy, wz, out float screenX, out float screenY);
*sx = screenX;
*sy = screenY;
return result ? 1 : 0;
}
public static int GetViewportSizeCallback(uint* width, uint* height)
{
if (!_hasViewport || _vpWidth == 0 || _vpHeight == 0)
return 0;
*width = _vpWidth;
*height = _vpHeight;
return 1;
}
private static void InstallHook(IntPtr pDevice)
{
try
{
IntPtr vtable = Marshal.ReadIntPtr(pDevice);
IntPtr setTransformAddr = Marshal.ReadIntPtr(vtable, DeviceVTableIndex.SetTransform * IntPtr.Size);
_hookDelegate = new SetTransformD(SetTransformDetour);
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_hookDelegate);
_originalSetTransform = Marshal.GetDelegateForFunctionPointer<SetTransformD>(MinHook.HookCreate(setTransformAddr, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(setTransformAddr);
_hookInstalled = true;
RynthLog.D3D9("GameMatrixCapture: SetTransform hook installed.");
}
catch (Exception ex)
{
RynthLog.D3D9($"GameMatrixCapture: SetTransform hook FAILED — {ex.Message}");
}
}
}

View file

@ -0,0 +1,101 @@
// ═══════════════════════════════════════════════════════════════════════════
// RynthCore.Engine — D3D9/Nav3DRenderInjector.cs
// Hooks DrawIndexedPrimitive to inject nav marker rendering at the
// 3D→UI boundary. When ZENABLE transitions from 1→0, renders markers
// so they appear after the 3D world but before the game's UI pass.
// ═══════════════════════════════════════════════════════════════════════════
using System;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.Hooking;
namespace RynthCore.Engine.D3D9;
internal static class Nav3DRenderInjector
{
private const uint D3DRS_ZENABLE = 7;
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int DrawIndexedPrimitiveD(IntPtr dev, uint primitiveType,
int baseVertexIndex, uint minVertexIndex, uint numVertices,
uint startIndex, uint primCount);
private static DrawIndexedPrimitiveD? _originalDIP;
private static DrawIndexedPrimitiveD? _hookDelegate;
private static bool _hookInstalled;
private static bool _inRender;
// Per-frame transition detection
private static uint _lastZEnable;
private static bool _markersRenderedThisFrame;
private static bool _seen3D;
public static bool RenderedThisFrame => _markersRenderedThisFrame;
public static void ResetFrame()
{
_markersRenderedThisFrame = false;
_seen3D = false;
_lastZEnable = 0;
}
public static void Install(IntPtr pDevice)
{
if (_hookInstalled) return;
try
{
IntPtr vtable = Marshal.ReadIntPtr(pDevice);
IntPtr addr = Marshal.ReadIntPtr(vtable, DeviceVTableIndex.DrawIndexedPrimitive * IntPtr.Size);
_hookDelegate = new DrawIndexedPrimitiveD(Detour);
IntPtr hookPtr = Marshal.GetFunctionPointerForDelegate(_hookDelegate);
_originalDIP = Marshal.GetDelegateForFunctionPointer<DrawIndexedPrimitiveD>(
MinHook.HookCreate(addr, hookPtr));
Thread.MemoryBarrier();
MinHook.Enable(addr);
_hookInstalled = true;
RynthLog.D3D9("Nav3DRenderInjector: DrawIndexedPrimitive hook installed.");
}
catch (Exception ex)
{
RynthLog.D3D9($"Nav3DRenderInjector: Hook install FAILED — {ex.Message}");
}
}
private static int Detour(IntPtr dev, uint primitiveType,
int baseVertexIndex, uint minVertexIndex, uint numVertices,
uint startIndex, uint primCount)
{
if (_inRender)
return _originalDIP!(dev, primitiveType, baseVertexIndex,
minVertexIndex, numVertices, startIndex, primCount);
ImGuiBackend.DX9Backend.DeviceGetRenderState(dev, D3DRS_ZENABLE, out uint zEnable);
if (zEnable != 0)
_seen3D = true;
// Detect 3D→UI transition: ZENABLE goes from 1→0 after 3D draws
if (!_markersRenderedThisFrame && _seen3D && _lastZEnable != 0 && zEnable == 0)
{
_markersRenderedThisFrame = true;
_inRender = true;
try
{
ImGuiBackend.DX9Backend.RenderNav3D(dev);
}
catch
{
}
_inRender = false;
}
_lastZEnable = zEnable;
return _originalDIP!(dev, primitiveType, baseVertexIndex,
minVertexIndex, numVertices, startIndex, primCount);
}
}

View file

@ -0,0 +1,221 @@
// ═══════════════════════════════════════════════════════════════════════════
// RynthCore.Engine — D3D9/Nav3DRenderer.cs
// Data store for 3D navigation markers. Plugins submit geometry every plugin
// tick via AddRing/AddLine/AddTriangle; DX9Backend.RenderNav3D reads it
// during EndScene.
//
// Double-buffered to keep the render thread (60 Hz, AC's EndScene) from
// reading a half-rewritten buffer while the plugin pump thread (~30 Hz) is
// mid Clear → Submit. Without this, every plugin tick produced a 1-frame
// empty/partial render that the user sees as flicker — pronounced when the
// player or camera is in motion (because the submitted contents change each
// tick; when stationary the race window contains identical data so it's
// invisible).
//
// Pattern:
// pump: BeginFrame() → AddX(...) × N → CommitFrame()
// render: reads from the "ready" buffer only; never touches "pending"
// CommitFrame atomically swaps the index reads see.
// ═══════════════════════════════════════════════════════════════════════════
using System.Threading;
using RynthCore.Engine.Compatibility;
namespace RynthCore.Engine.D3D9;
internal static class Nav3DRenderer
{
private const int MaxRings = 256;
private const int MaxLines = 512;
// Triangle: three vertices + color. Sized for a ~3×3-landblock slope
// overlay around the player: 24-cell radius ≈ 49×49 cells × 2 triangles
// = 4802 triangles worst case, with headroom for water and other uses.
private const int MaxTriangles = 8192;
private const float DefaultRingHeight = 0.5f; // back-compat default for AddRing
private sealed class NavBuffer
{
public readonly float[] RingX = new float[MaxRings];
public readonly float[] RingY = new float[MaxRings];
public readonly float[] RingZ = new float[MaxRings];
public readonly float[] RingRadius = new float[MaxRings];
public readonly float[] RingThick = new float[MaxRings];
public readonly float[] RingHeight = new float[MaxRings];
public readonly uint[] RingColor = new uint[MaxRings];
public int RingCount;
public readonly float[] LineX1 = new float[MaxLines];
public readonly float[] LineY1 = new float[MaxLines];
public readonly float[] LineZ1 = new float[MaxLines];
public readonly float[] LineX2 = new float[MaxLines];
public readonly float[] LineY2 = new float[MaxLines];
public readonly float[] LineZ2 = new float[MaxLines];
public readonly float[] LineThick = new float[MaxLines];
public readonly uint[] LineColor = new uint[MaxLines];
public int LineCount;
public readonly float[] TriX1 = new float[MaxTriangles];
public readonly float[] TriY1 = new float[MaxTriangles];
public readonly float[] TriZ1 = new float[MaxTriangles];
public readonly float[] TriX2 = new float[MaxTriangles];
public readonly float[] TriY2 = new float[MaxTriangles];
public readonly float[] TriZ2 = new float[MaxTriangles];
public readonly float[] TriX3 = new float[MaxTriangles];
public readonly float[] TriY3 = new float[MaxTriangles];
public readonly float[] TriZ3 = new float[MaxTriangles];
public readonly uint[] TriColor = new uint[MaxTriangles];
public int TriCount;
// The player's landblock at the moment ClearFrame was called for
// this buffer. All AddX submissions in this tick are in PLAYER-
// landblock-local coordinates (per RynthAi + RynthVision contract),
// so the render side needs THIS landblock — not the current
// player landblock — when it computes the view-matrix shift, or the
// tick's geometry will jump 192m when the player crosses a boundary
// between this tick and the next render frame.
// Zero = "no player pose available; fall back to current".
public uint SubmissionPlayerLandblock;
public void Reset() { RingCount = 0; LineCount = 0; TriCount = 0; SubmissionPlayerLandblock = 0; }
}
// Triple buffer:
// _ready — what the render thread reads (volatile, swap published here)
// _pending — what the pump writes into for the current tick
// _spare — last tick's ready, "cooling off" one tick before the pump
// recycles it. This guarantees the buffer the render thread
// has captured isn't overwritten mid-iteration: when pump
// commits, the buffer the reader was holding becomes _spare
// (untouched for this tick) before becoming _pending the
// tick after that. Cheap insurance against any timing where
// render takes longer than one pump interval.
private static readonly NavBuffer _a = new();
private static readonly NavBuffer _b = new();
private static readonly NavBuffer _c = new();
private static volatile NavBuffer _ready = _a;
private static NavBuffer _pending = _b;
private static NavBuffer _spare = _c;
// ── Render-side reads ────────────────────────────────────────────────────
public static int RingCount => _ready.RingCount;
public static int LineCount => _ready.LineCount;
public static int TriangleCount => _ready.TriCount;
public static void GetRing(int i, out float x, out float y, out float z,
out float radius, out float thickness, out float height, out uint color)
{
var r = _ready;
x = r.RingX[i]; y = r.RingY[i]; z = r.RingZ[i];
radius = r.RingRadius[i]; thickness = r.RingThick[i];
height = r.RingHeight[i]; color = r.RingColor[i];
}
public static void GetLine(int i, out float x1, out float y1, out float z1,
out float x2, out float y2, out float z2, out float thickness, out uint color)
{
var r = _ready;
x1 = r.LineX1[i]; y1 = r.LineY1[i]; z1 = r.LineZ1[i];
x2 = r.LineX2[i]; y2 = r.LineY2[i]; z2 = r.LineZ2[i];
thickness = r.LineThick[i]; color = r.LineColor[i];
}
public static void GetTriangle(int i, out float x1, out float y1, out float z1,
out float x2, out float y2, out float z2,
out float x3, out float y3, out float z3, out uint color)
{
var r = _ready;
x1 = r.TriX1[i]; y1 = r.TriY1[i]; z1 = r.TriZ1[i];
x2 = r.TriX2[i]; y2 = r.TriY2[i]; z2 = r.TriZ2[i];
x3 = r.TriX3[i]; y3 = r.TriY3[i]; z3 = r.TriZ3[i];
color = r.TriColor[i];
}
// The landblock the plugin tick that produced the ready buffer was using.
// Render thread uses this for view-matrix shifting so geometry stays
// anchored to that tick's reference frame even if the player crosses a
// landblock boundary between this tick and the next render frame.
// Returns 0 when no pose was sampled; caller should fall back to
// current player landblock in that case.
public static uint ReadyPlayerLandblock => _ready.SubmissionPlayerLandblock;
// ── Pump-side writes ─────────────────────────────────────────────────────
public static void ClearFrame()
{
_pending.Reset();
// Capture the player's current landblock so the render side knows
// which frame the tick's submissions are anchored in.
if (PlayerPhysicsHooks.TryGetPlayerPose(out uint cellId, out _, out _, out _,
out _, out _, out _, out _))
_pending.SubmissionPlayerLandblock = cellId >> 16;
}
public static void AddRing(float wx, float wy, float wz, float radius, float thickness, uint colorArgb)
=> AddRingEx(wx, wy, wz, radius, thickness, DefaultRingHeight, colorArgb);
public static void AddRingEx(float wx, float wy, float wz, float radius, float thickness, float height, uint colorArgb)
{
var p = _pending;
if (p.RingCount >= MaxRings) return;
int i = p.RingCount++;
p.RingX[i] = wx; p.RingY[i] = wy; p.RingZ[i] = wz;
p.RingRadius[i] = radius;
p.RingThick[i] = thickness;
p.RingHeight[i] = height;
p.RingColor[i] = colorArgb;
}
public static void AddLine(float x1, float y1, float z1, float x2, float y2, float z2, float thickness, uint colorArgb)
{
var p = _pending;
if (p.LineCount >= MaxLines) return;
int i = p.LineCount++;
p.LineX1[i] = x1; p.LineY1[i] = y1; p.LineZ1[i] = z1;
p.LineX2[i] = x2; p.LineY2[i] = y2; p.LineZ2[i] = z2;
p.LineThick[i] = thickness;
p.LineColor[i] = colorArgb;
}
public static void AddTriangle(float x1, float y1, float z1,
float x2, float y2, float z2,
float x3, float y3, float z3, uint colorArgb)
{
var p = _pending;
if (p.TriCount >= MaxTriangles) return;
int i = p.TriCount++;
p.TriX1[i] = x1; p.TriY1[i] = y1; p.TriZ1[i] = z1;
p.TriX2[i] = x2; p.TriY2[i] = y2; p.TriZ2[i] = z2;
p.TriX3[i] = x3; p.TriY3[i] = y3; p.TriZ3[i] = z3;
p.TriColor[i] = colorArgb;
}
/// <summary>
/// Cycle: _pending → _ready → _spare → _pending. The newly-filled buffer
/// becomes ready; the old ready becomes spare (idle this tick); the old
/// spare becomes the next pending. Render reads of the new ready buffer
/// become visible across cores via the volatile field. Called by
/// PluginManager.TickAll AFTER all plugins have submitted.
/// </summary>
public static void CommitFrame()
{
NavBuffer newReady = _pending;
NavBuffer newSpare = _ready;
NavBuffer newPending = _spare;
_spare = newSpare;
_pending = newPending;
Volatile.Write(ref _ready, newReady);
}
// ── C ABI callbacks for plugin contract ──────────────────────────────────
public static void Nav3DClearCallback() => ClearFrame();
public static void Nav3DAddRingCallback(float wx, float wy, float wz, float radius, float thickness, uint color)
=> AddRing(wx, wy, wz, radius, thickness, color);
public static void Nav3DAddRingExCallback(float wx, float wy, float wz, float radius, float thickness, float height, uint color)
=> AddRingEx(wx, wy, wz, radius, thickness, height, color);
public static void Nav3DAddLineCallback(float x1, float y1, float z1, float x2, float y2, float z2, float thickness, uint color)
=> AddLine(x1, y1, z1, x2, y2, z2, thickness, color);
public static void Nav3DAddTriangleCallback(float x1, float y1, float z1, float x2, float y2, float z2, float x3, float y3, float z3, uint color)
=> AddTriangle(x1, y1, z1, x2, y2, z2, x3, y3, z3, color);
}

View file

@ -0,0 +1,600 @@
// ============================================================================
// RynthCore.Engine - D3D9/OverlayTextureRenderer.cs
// Consumes BGRA frames from OverlayFrameBuffer and composites them onto
// the D3D9 back buffer as a fullscreen alpha-blended quad.
//
// Called at the end of OnEndScene, after ImGui has already rendered.
// Uses D3DFVF_XYZRHW | D3DFVF_TEX1 (pre-transformed vertices) so no
// projection matrix setup is needed.
//
// Pixel format: Avalonia Bgra8888 == D3DFMT_A8R8G8B8 in memory — no swizzle.
// ============================================================================
using System;
using System.Runtime.InteropServices;
using RynthCore.Engine.UI;
namespace RynthCore.Engine.D3D9;
internal static unsafe class OverlayTextureRenderer
{
private static readonly Guid IID_IDirect3DDevice9Ex = new("B18B10CE-2649-405A-870F-95F777D4313A");
// ─── D3D9 constants ───────────────────────────────────────────────────
private const uint D3DPT_TRIANGLESTRIP = 5;
private const uint D3DUSAGE_RENDERTARGET = 0x00000001;
private const uint D3DFMT_A8R8G8B8 = 21;
private const uint D3DPOOL_DEFAULT = 0;
private const uint D3DPOOL_MANAGED = 1;
private const uint D3DRS_ALPHABLENDENABLE = 27;
private const uint D3DRS_SRCBLEND = 19;
private const uint D3DRS_DESTBLEND = 20;
private const uint D3DRS_ZENABLE = 7;
private const uint D3DRS_ALPHATESTENABLE = 15;
private const uint D3DRS_CULLMODE = 22;
private const uint D3DRS_LIGHTING = 137;
private const uint D3DRS_FOGENABLE = 28;
private const uint D3DRS_STENCILENABLE = 52;
private const uint D3DRS_COLORWRITEENABLE = 168;
private const uint D3DRS_BLENDOP = 171;
private const uint D3DRS_SCISSORTESTENABLE = 174;
private const uint D3DRS_SRGBWRITEENABLE = 194;
private const uint D3DRS_SEPARATEALPHABLENDENABLE = 206;
private const uint D3DBLENDOP_ADD = 1;
private const uint D3DBLEND_ONE = 2;
private const uint D3DBLEND_SRCALPHA = 5;
private const uint D3DBLEND_INVSRCALPHA = 6;
private const uint D3DCULL_NONE = 1;
private const uint D3DTSS_COLOROP = 1;
private const uint D3DTSS_COLORARG1 = 2;
private const uint D3DTSS_COLORARG2 = 3;
private const uint D3DTSS_ALPHAOP = 4;
private const uint D3DTSS_ALPHAARG1 = 5;
private const uint D3DTSS_ALPHAARG2 = 6;
private const uint D3DTOP_SELECTARG1 = 2;
private const uint D3DTOP_MODULATE = 4;
private const uint D3DTA_TEXTURE = 2;
private const uint D3DTA_DIFFUSE = 0;
private const uint D3DSAMP_MINFILTER = 5;
private const uint D3DSAMP_MAGFILTER = 6;
private const uint D3DTEXF_LINEAR = 2;
private const uint D3DTEXF_POINT = 1;
// D3DFVF_XYZRHW | D3DFVF_TEX1
private const uint FVF = 0x004 | 0x100;
// ─── Vertex (pre-transformed screen-space + UV) ────────────────────────
[StructLayout(LayoutKind.Sequential)]
private struct QuadVertex
{
public float X, Y, Z, RHW;
public float U, V;
}
// ─── D3D9 struct ──────────────────────────────────────────────────────
[StructLayout(LayoutKind.Sequential)]
private struct D3DVIEWPORT9
{
public uint X, Y, Width, Height;
public float MinZ, MaxZ;
}
[StructLayout(LayoutKind.Sequential)]
private struct D3DLOCKED_RECT
{
public int Pitch;
public IntPtr pBits;
}
// ─── Vtable delegates ─────────────────────────────────────────────────
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int CreateTextureD(IntPtr dev, uint w, uint h, uint levels, uint usage, uint fmt, uint pool, out IntPtr ppTex, IntPtr pShared);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int SetTextureD(IntPtr dev, uint stage, IntPtr pTex);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int SetTextureStageStateD(IntPtr dev, uint stage, uint type, uint value);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int GetTextureStageStateD(IntPtr dev, uint stage, uint type, out uint pValue);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int SetSamplerStateD(IntPtr dev, uint sampler, uint type, uint value);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int GetSamplerStateD(IntPtr dev, uint sampler, uint type, out uint pValue);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int GetTextureD(IntPtr dev, uint stage, out IntPtr ppTex);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int SetFVFD(IntPtr dev, uint fvf);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int GetFVFD(IntPtr dev, out uint pFvf);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int SetRenderStateD(IntPtr dev, uint state, uint value);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int GetRenderStateD(IntPtr dev, uint state, out uint pValue);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int SetVertexShaderD(IntPtr dev, IntPtr pShader);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int GetVertexShaderD(IntPtr dev, out IntPtr ppShader);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int SetPixelShaderD(IntPtr dev, IntPtr pShader);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int GetPixelShaderD(IntPtr dev, out IntPtr ppShader);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int GetViewportD(IntPtr dev, D3DVIEWPORT9* vp);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int DrawPrimitiveUPD(IntPtr dev, uint primType, uint primCount, IntPtr pVtxData, uint vtxStride);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate uint ReleaseD(IntPtr pObj);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int QueryInterfaceD(IntPtr pObj, Guid* riid, out IntPtr ppvObject);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int TexLockRectD(IntPtr pTex, uint level, D3DLOCKED_RECT* pLocked, IntPtr pRect, uint flags);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int TexUnlockRectD(IntPtr pTex, uint level);
// ─── Cached delegates ─────────────────────────────────────────────────
private static CreateTextureD? _createTexture;
private static SetTextureD? _setTexture;
private static SetTextureStageStateD? _setTexStageState;
private static GetTextureStageStateD? _getTexStageState;
private static SetSamplerStateD? _setSamplerState;
private static GetSamplerStateD? _getSamplerState;
private static GetTextureD? _getTexture;
private static SetFVFD? _setFVF;
private static GetFVFD? _getFVF;
private static SetRenderStateD? _setRenderState;
private static GetRenderStateD? _getRenderState;
private static SetVertexShaderD? _setVertexShader;
private static GetVertexShaderD? _getVertexShader;
private static SetPixelShaderD? _setPixelShader;
private static GetPixelShaderD? _getPixelShader;
private static GetViewportD? _getViewport;
private static DrawPrimitiveUPD? _drawPrimitiveUP;
private static QueryInterfaceD? _queryInterface;
// ─── State ────────────────────────────────────────────────────────────
private static IntPtr _texture;
private static IntPtr _sharedTextureHandle;
private static int _texW;
private static int _texH;
private static bool _delegatesCached;
private static bool _sharedInteropProbed;
private static bool _sharedInteropSupported;
// ─── Public entry point ───────────────────────────────────────────────
/// <summary>
/// Called from EndScene (D3D9 render thread) after ImGui has rendered.
/// Uploads any pending Avalonia frame to the texture and draws it.
/// </summary>
public static void Render(IntPtr pDevice)
{
if (pDevice == IntPtr.Zero)
return;
if (!_delegatesCached)
{
CacheDelegates(pDevice);
_delegatesCached = true;
}
// Publish viewport size BEFORE consuming a frame so Avalonia has a non-zero
// game-surface size on the very first tick. Without this, the producer waits
// for size > 1 (set previously only inside DrawQuad), but DrawQuad doesn't
// run until a frame is uploaded — chicken-and-egg when ImGui's Win32Backend
// (which also publishes ClientPixelWidth/Height) is disabled.
D3DVIEWPORT9 earlyVp;
if (_getViewport!(pDevice, &earlyVp) >= 0)
{
int vw = (int)earlyVp.Width;
int vh = (int)earlyVp.Height;
if (vw > 1 && vh > 1)
{
bool changed = AvaloniaOverlay.ViewportWidth != vw || AvaloniaOverlay.ViewportHeight != vh;
AvaloniaOverlay.ViewportWidth = vw;
AvaloniaOverlay.ViewportHeight = vh;
if (changed)
AvaloniaOverlay.NotifyGameSurfaceMetricsChanged();
}
}
// Learn as early as possible whether this game device can consume shared
// textures. That lets the producer stay on software submissions only on
// unsupported clients instead of discovering it mid-session.
if (OverlaySurfaceBridge.ActiveSupportsGpuInterop && !_sharedInteropProbed)
EnsureSharedInteropSupport(pDevice);
// Upload new frame if one is available
if (OverlaySurfaceBridge.TryConsume(out OverlaySurfaceFrame? frame) && frame != null)
{
switch (frame.Kind)
{
case OverlaySurfaceKind.SoftwareBgra32 when frame.SoftwarePixels != null:
UploadFrame(pDevice, frame.SoftwarePixels, frame.Width, frame.Height);
break;
case OverlaySurfaceKind.AngleSharedTexture when frame.SharedTexture != null:
if (!TryUseSharedTexture(pDevice, "ANGLE", frame.SharedTexture.Value))
LogSharedTextureStub("ANGLE", frame.SharedTexture);
break;
case OverlaySurfaceKind.DxgiSharedTexture when frame.SharedTexture != null:
if (!TryUseSharedTexture(pDevice, "DXGI", frame.SharedTexture.Value))
LogSharedTextureStub("DXGI", frame.SharedTexture);
break;
case OverlaySurfaceKind.D3D9SharedTexture when frame.SharedTexture != null:
if (!TryUseSharedTexture(pDevice, "D3D9Ex", frame.SharedTexture.Value))
LogSharedTextureStub("D3D9Ex", frame.SharedTexture);
break;
}
}
if (_texture == IntPtr.Zero)
return;
DrawQuad(pDevice);
}
private static void LogSharedTextureStub(string label, OverlaySharedTextureDescriptor? descriptor)
{
if (descriptor == null)
{
RynthLog.D3D9($"OverlayTextureRenderer: {label} shared texture frame arrived without a descriptor.");
return;
}
RynthLog.D3D9(
$"OverlayTextureRenderer: {label} shared texture interop is not implemented yet " +
$"(handle=0x{descriptor.Value.SharedHandle:X8}, size={descriptor.Value.Width}x{descriptor.Value.Height}, adapterLuid=0x{descriptor.Value.AdapterLuid:X}).");
}
public static void Shutdown()
{
ReleaseTexture();
_delegatesCached = false;
_sharedInteropProbed = false;
_sharedInteropSupported = false;
}
// ─── Upload ───────────────────────────────────────────────────────────
private static void UploadFrame(IntPtr pDevice, byte[] pixels, int w, int h)
{
// Recreate texture if dimensions changed
if (_texture == IntPtr.Zero || w != _texW || h != _texH || _sharedTextureHandle != IntPtr.Zero)
{
ReleaseTexture();
int hr = _createTexture!(pDevice, (uint)w, (uint)h, 1, 0,
D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, out _texture, IntPtr.Zero);
if (hr < 0 || _texture == IntPtr.Zero)
{
RynthLog.D3D9($"OverlayTextureRenderer: CreateTexture({w}x{h}) failed HRESULT=0x{hr:X8}");
return;
}
_texW = w;
_texH = h;
RynthLog.D3D9($"OverlayTextureRenderer: Created {w}x{h} overlay texture.");
}
// Lock → copy → unlock
// Use raw function pointers (no GC delegate alloc) — Marshal.GetDelegateForFunctionPointer
// creates a small heap object per call, which at 60+ FPS hammers the LFH and was bisected
// as the cause of a heap-corruption AV in ntdll (write fault at addr ending in FFC).
IntPtr texVtbl = Marshal.ReadIntPtr(_texture);
var lockRectFn = (delegate* unmanaged[Stdcall]<IntPtr, uint, D3DLOCKED_RECT*, IntPtr, uint, int>)
Marshal.ReadIntPtr(texVtbl, TextureVTableIndex.LockRect * IntPtr.Size);
var unlockRectFn = (delegate* unmanaged[Stdcall]<IntPtr, uint, int>)
Marshal.ReadIntPtr(texVtbl, TextureVTableIndex.UnlockRect * IntPtr.Size);
D3DLOCKED_RECT locked;
if (lockRectFn(_texture, 0, &locked, IntPtr.Zero, 0) < 0)
return;
// Avalonia Bgra8888 == D3DFMT_A8R8G8B8 in memory — direct copy, no swizzle
int srcStride = w * 4;
fixed (byte* srcBase = pixels)
{
for (int row = 0; row < h; row++)
{
IntPtr dst = locked.pBits + row * locked.Pitch;
Buffer.MemoryCopy(srcBase + row * srcStride, (void*)dst, srcStride, srcStride);
}
}
unlockRectFn(_texture, 0);
}
private static bool TryUseSharedTexture(IntPtr pDevice, string label, OverlaySharedTextureDescriptor descriptor)
{
if (descriptor.SharedHandle == IntPtr.Zero)
return false;
if (!EnsureSharedInteropSupport(pDevice))
return false;
if (_texture != IntPtr.Zero &&
_sharedTextureHandle == descriptor.SharedHandle &&
_texW == descriptor.Width &&
_texH == descriptor.Height)
{
OverlaySurfaceBridge.NotifySharedTextureOpened(descriptor.SharedHandle);
return true;
}
IntPtr openedTexture = IntPtr.Zero;
IntPtr sharedHandle = descriptor.SharedHandle;
uint usage = descriptor.Usage != 0 ? (uint)descriptor.Usage : D3DUSAGE_RENDERTARGET;
uint format = descriptor.PixelFormat != 0 ? (uint)descriptor.PixelFormat : D3DFMT_A8R8G8B8;
int hr = _createTexture!(
pDevice,
(uint)descriptor.Width,
(uint)descriptor.Height,
1,
usage,
format,
D3DPOOL_DEFAULT,
out openedTexture,
new IntPtr(&sharedHandle));
if (hr < 0 || openedTexture == IntPtr.Zero)
{
RynthLog.D3D9(
$"OverlayTextureRenderer: Failed to open {label} shared texture handle 0x{descriptor.SharedHandle:X8}, HRESULT=0x{hr:X8}.");
return false;
}
ReleaseTexture();
_texture = openedTexture;
_sharedTextureHandle = descriptor.SharedHandle;
_texW = descriptor.Width;
_texH = descriptor.Height;
OverlaySurfaceBridge.NotifySharedTextureOpened(descriptor.SharedHandle);
RynthLog.D3D9(
$"OverlayTextureRenderer: Opened {label} shared texture handle 0x{descriptor.SharedHandle:X8} ({descriptor.Width}x{descriptor.Height}).");
return true;
}
private static bool EnsureSharedInteropSupport(IntPtr pDevice)
{
if (_sharedInteropProbed)
return _sharedInteropSupported;
_sharedInteropProbed = true;
if (_queryInterface == null)
{
RynthLog.D3D9("OverlayTextureRenderer: Shared-texture probe unavailable because QueryInterface is not cached.");
OverlaySurfaceBridge.NotifySharedTextureUnavailable();
return false;
}
IntPtr exDevice = IntPtr.Zero;
Guid iid = IID_IDirect3DDevice9Ex;
int hr = _queryInterface(pDevice, &iid, out exDevice);
if (hr >= 0 && exDevice != IntPtr.Zero)
{
_sharedInteropSupported = true;
RynthLog.D3D9("OverlayTextureRenderer: D3D9Ex shared-texture consumption is available on the active game device.");
ReleaseComObject(exDevice);
return true;
}
RynthLog.D3D9("OverlayTextureRenderer: D3D9Ex shared-texture consumption is unavailable on the active game device; software fallback will remain active.");
OverlaySurfaceBridge.NotifySharedTextureUnavailable();
return false;
}
// ─── Draw ─────────────────────────────────────────────────────────────
private static void DrawQuad(IntPtr pDevice)
{
// Get current viewport to size the quad
D3DVIEWPORT9 vp;
if (_getViewport!(pDevice, &vp) < 0)
return;
float W = vp.Width;
float H = vp.Height;
// Tell the Avalonia thread what the current viewport size is so it can
// keep the canvas sized correctly (prevents stretch/scale artifacts).
int viewportWidth = (int)W;
int viewportHeight = (int)H;
bool viewportChanged =
AvaloniaOverlay.ViewportWidth != viewportWidth ||
AvaloniaOverlay.ViewportHeight != viewportHeight;
AvaloniaOverlay.ViewportWidth = viewportWidth;
AvaloniaOverlay.ViewportHeight = viewportHeight;
if (viewportChanged)
AvaloniaOverlay.NotifyGameSurfaceMetricsChanged();
// Save render states we will change
_getRenderState!(pDevice, D3DRS_ALPHABLENDENABLE, out uint savedAlpha);
_getRenderState!(pDevice, D3DRS_SRCBLEND, out uint savedSrcBlend);
_getRenderState!(pDevice, D3DRS_DESTBLEND, out uint savedDstBlend);
_getRenderState!(pDevice, D3DRS_ZENABLE, out uint savedZ);
_getRenderState!(pDevice, D3DRS_ALPHATESTENABLE, out uint savedAlphaTest);
_getRenderState!(pDevice, D3DRS_CULLMODE, out uint savedCull);
_getRenderState!(pDevice, D3DRS_LIGHTING, out uint savedLighting);
_getRenderState!(pDevice, D3DRS_FOGENABLE, out uint savedFog);
_getRenderState!(pDevice, D3DRS_STENCILENABLE, out uint savedStencil);
_getRenderState!(pDevice, D3DRS_COLORWRITEENABLE, out uint savedColorWrite);
_getRenderState!(pDevice, D3DRS_BLENDOP, out uint savedBlendOp);
_getRenderState!(pDevice, D3DRS_SCISSORTESTENABLE, out uint savedScissor);
_getRenderState!(pDevice, D3DRS_SRGBWRITEENABLE, out uint savedSrgb);
_getRenderState!(pDevice, D3DRS_SEPARATEALPHABLENDENABLE, out uint savedSeparateAlpha);
_getVertexShader!(pDevice, out IntPtr savedVS);
_getPixelShader!(pDevice, out IntPtr savedPS);
_getFVF!(pDevice, out uint savedFVF);
_getTexture!(pDevice, 0, out IntPtr savedTex0);
_getTexStageState!(pDevice, 0, D3DTSS_COLOROP, out uint savedTSS_ColorOp);
_getTexStageState!(pDevice, 0, D3DTSS_COLORARG1, out uint savedTSS_ColorArg1);
_getTexStageState!(pDevice, 0, D3DTSS_COLORARG2, out uint savedTSS_ColorArg2);
_getTexStageState!(pDevice, 0, D3DTSS_ALPHAOP, out uint savedTSS_AlphaOp);
_getTexStageState!(pDevice, 0, D3DTSS_ALPHAARG1, out uint savedTSS_AlphaArg1);
_getTexStageState!(pDevice, 0, D3DTSS_ALPHAARG2, out uint savedTSS_AlphaArg2);
_getSamplerState!(pDevice, 0, D3DSAMP_MINFILTER, out uint savedSamp_Min);
_getSamplerState!(pDevice, 0, D3DSAMP_MAGFILTER, out uint savedSamp_Mag);
try
{
// Avalonia produces premultiplied BGRA, so the right blend is
// ONE / INVSRCALPHA. SRCALPHA would square the alpha and dim the
// overlay; ONE matches the premul invariant exactly.
_setRenderState!(pDevice, D3DRS_ALPHABLENDENABLE, 1);
_setRenderState!(pDevice, D3DRS_SRCBLEND, D3DBLEND_ONE);
_setRenderState!(pDevice, D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
_setRenderState!(pDevice, D3DRS_BLENDOP, D3DBLENDOP_ADD);
_setRenderState!(pDevice, D3DRS_ZENABLE, 0);
_setRenderState!(pDevice, D3DRS_ALPHATESTENABLE, 0);
_setRenderState!(pDevice, D3DRS_CULLMODE, D3DCULL_NONE);
_setRenderState!(pDevice, D3DRS_LIGHTING, 0);
// AC enables fog (often white) for portal-space and dungeon
// particle effects; without disabling it our quad gets
// fog-blended toward white. Same for scissor (AC clips), stencil
// (UI passes), and separate-alpha-blend (would override our blend).
_setRenderState!(pDevice, D3DRS_FOGENABLE, 0);
_setRenderState!(pDevice, D3DRS_STENCILENABLE, 0);
_setRenderState!(pDevice, D3DRS_SCISSORTESTENABLE, 0);
_setRenderState!(pDevice, D3DRS_SRGBWRITEENABLE, 0);
_setRenderState!(pDevice, D3DRS_SEPARATEALPHABLENDENABLE, 0);
_setRenderState!(pDevice, D3DRS_COLORWRITEENABLE, 0xF);
_setVertexShader!(pDevice, IntPtr.Zero);
_setPixelShader!(pDevice, IntPtr.Zero);
_setFVF!(pDevice, FVF);
_setTexture!(pDevice, 0, _texture);
// Use SELECTARG1 (texture only) instead of MODULATE so a stale
// per-vertex DIFFUSE left over from ImGui's previous DrawPrimitiveUP
// call can't tint the overlay — our FVF doesn't include DIFFUSE,
// making its value undefined under MODULATE.
_setTexStageState!(pDevice, 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
_setTexStageState!(pDevice, 0, D3DTSS_COLORARG1, D3DTA_TEXTURE);
_setTexStageState!(pDevice, 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
_setTexStageState!(pDevice, 0, D3DTSS_ALPHAARG1, D3DTA_TEXTURE);
// POINT filter is crisper than LINEAR when the texture and the
// target backbuffer have the same dimensions — each output pixel
// maps to exactly one texel, so we don't want any blending.
_setSamplerState!(pDevice, 0, D3DSAMP_MINFILTER, D3DTEXF_POINT);
_setSamplerState!(pDevice, 0, D3DSAMP_MAGFILTER, D3DTEXF_POINT);
// D3D9 half-texel offset: pixel centers are at integer + 0.5, but
// texel coords are at integer indexes. Without -0.5 vertex offset,
// each output pixel samples *between* two texels, blending them
// (visible blur even with POINT filter due to rasterization rules).
QuadVertex* 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 };
_drawPrimitiveUP!(pDevice, D3DPT_TRIANGLESTRIP, 2,
new IntPtr(verts), (uint)sizeof(QuadVertex));
}
finally
{
// Restore changed state. Anything we touched must be put back —
// AC re-enters EndScene mid-frame for additional passes (post-fx,
// particles, fog) and inherits whatever device state we left.
_setRenderState!(pDevice, D3DRS_ALPHABLENDENABLE, savedAlpha);
_setRenderState!(pDevice, D3DRS_SRCBLEND, savedSrcBlend);
_setRenderState!(pDevice, D3DRS_DESTBLEND, savedDstBlend);
_setRenderState!(pDevice, D3DRS_BLENDOP, savedBlendOp);
_setRenderState!(pDevice, D3DRS_ZENABLE, savedZ);
_setRenderState!(pDevice, D3DRS_ALPHATESTENABLE, savedAlphaTest);
_setRenderState!(pDevice, D3DRS_CULLMODE, savedCull);
_setRenderState!(pDevice, D3DRS_LIGHTING, savedLighting);
_setRenderState!(pDevice, D3DRS_FOGENABLE, savedFog);
_setRenderState!(pDevice, D3DRS_STENCILENABLE, savedStencil);
_setRenderState!(pDevice, D3DRS_SCISSORTESTENABLE, savedScissor);
_setRenderState!(pDevice, D3DRS_SRGBWRITEENABLE, savedSrgb);
_setRenderState!(pDevice, D3DRS_SEPARATEALPHABLENDENABLE, savedSeparateAlpha);
_setRenderState!(pDevice, D3DRS_COLORWRITEENABLE, savedColorWrite);
_setVertexShader!(pDevice, savedVS);
_setPixelShader!(pDevice, savedPS);
_setFVF!(pDevice, savedFVF);
_setTexStageState!(pDevice, 0, D3DTSS_COLOROP, savedTSS_ColorOp);
_setTexStageState!(pDevice, 0, D3DTSS_COLORARG1, savedTSS_ColorArg1);
_setTexStageState!(pDevice, 0, D3DTSS_COLORARG2, savedTSS_ColorArg2);
_setTexStageState!(pDevice, 0, D3DTSS_ALPHAOP, savedTSS_AlphaOp);
_setTexStageState!(pDevice, 0, D3DTSS_ALPHAARG1, savedTSS_AlphaArg1);
_setTexStageState!(pDevice, 0, D3DTSS_ALPHAARG2, savedTSS_AlphaArg2);
_setSamplerState!(pDevice, 0, D3DSAMP_MINFILTER, savedSamp_Min);
_setSamplerState!(pDevice, 0, D3DSAMP_MAGFILTER, savedSamp_Mag);
_setTexture!(pDevice, 0, savedTex0);
if (savedVS != IntPtr.Zero) ReleaseComObject(savedVS);
if (savedPS != IntPtr.Zero) ReleaseComObject(savedPS);
if (savedTex0 != IntPtr.Zero) ReleaseComObject(savedTex0);
}
}
// ─── Helpers ──────────────────────────────────────────────────────────
private static void ReleaseTexture()
{
if (_texture == IntPtr.Zero)
return;
IntPtr texVtbl = Marshal.ReadIntPtr(_texture);
var release = (delegate* unmanaged[Stdcall]<IntPtr, uint>)
Marshal.ReadIntPtr(texVtbl, TextureVTableIndex.Release * IntPtr.Size);
release(_texture);
_texture = IntPtr.Zero;
_sharedTextureHandle = IntPtr.Zero;
_texW = 0;
_texH = 0;
}
private static void ReleaseComObject(IntPtr pObj)
{
if (pObj == IntPtr.Zero) return;
IntPtr vtbl = Marshal.ReadIntPtr(pObj);
// Raw function pointer — avoids GC delegate alloc on every per-frame Release.
var rel = (delegate* unmanaged[Stdcall]<IntPtr, uint>)
Marshal.ReadIntPtr(vtbl, 2 * IntPtr.Size);
rel(pObj);
}
private static void CacheDelegates(IntPtr pDevice)
{
IntPtr vtable = Marshal.ReadIntPtr(pDevice);
_createTexture = Get<CreateTextureD>(vtable, DeviceVTableIndex.CreateTexture);
_setTexture = Get<SetTextureD>(vtable, DeviceVTableIndex.SetTexture);
_getTexture = Get<GetTextureD>(vtable, DeviceVTableIndex.GetTexture);
_setTexStageState = Get<SetTextureStageStateD>(vtable, DeviceVTableIndex.SetTextureStageState);
_getTexStageState = Get<GetTextureStageStateD>(vtable, DeviceVTableIndex.GetTextureStageState);
_setSamplerState = Get<SetSamplerStateD>(vtable, DeviceVTableIndex.SetSamplerState);
_getSamplerState = Get<GetSamplerStateD>(vtable, DeviceVTableIndex.GetSamplerState);
_setFVF = Get<SetFVFD>(vtable, DeviceVTableIndex.SetFVF);
_getFVF = Get<GetFVFD>(vtable, DeviceVTableIndex.GetFVF);
_setRenderState = Get<SetRenderStateD>(vtable, DeviceVTableIndex.SetRenderState);
_getRenderState = Get<GetRenderStateD>(vtable, DeviceVTableIndex.GetRenderState);
_setVertexShader = Get<SetVertexShaderD>(vtable, DeviceVTableIndex.SetVertexShader);
_getVertexShader = Get<GetVertexShaderD>(vtable, DeviceVTableIndex.GetVertexShader);
_setPixelShader = Get<SetPixelShaderD>(vtable, DeviceVTableIndex.SetPixelShader);
_getPixelShader = Get<GetPixelShaderD>(vtable, DeviceVTableIndex.GetPixelShader);
_getViewport = Get<GetViewportD>(vtable, DeviceVTableIndex.GetViewport);
_drawPrimitiveUP = Get<DrawPrimitiveUPD>(vtable, DeviceVTableIndex.DrawPrimitiveUP);
_queryInterface = Get<QueryInterfaceD>(vtable, 0);
}
private static T Get<T>(IntPtr vtable, int index) where T : Delegate
{
IntPtr addr = Marshal.ReadIntPtr(vtable, index * IntPtr.Size);
return Marshal.GetDelegateForFunctionPointer<T>(addr);
}
private static T GetTexMethod<T>(IntPtr pTex, int index) where T : Delegate
{
IntPtr vtable = Marshal.ReadIntPtr(pTex);
IntPtr addr = Marshal.ReadIntPtr(vtable, index * IntPtr.Size);
return Marshal.GetDelegateForFunctionPointer<T>(addr);
}
}

View file

@ -0,0 +1,175 @@
// ═══════════════════════════════════════════════════════════════════════════
// RynthCore.Engine — D3D9/TestRenderer.cs
// Draws a small colored rectangle in the top-left corner of the game.
// Pure D3D9 via vtable calls — no dependencies on any overlay framework.
//
// Uses pre-transformed vertices (D3DFVF_XYZRHW | D3DFVF_DIFFUSE) so no
// world/view/projection matrices needed. The rectangle is screen-space.
// ═══════════════════════════════════════════════════════════════════════════
using System;
using System.Runtime.InteropServices;
namespace RynthCore.Engine.D3D9;
internal static unsafe class TestRenderer
{
// ─── D3D9 constants ───────────────────────────────────────────────
private const uint D3DFVF_XYZRHW = 0x0004;
private const uint D3DFVF_DIFFUSE = 0x0040;
private const uint D3DFVF_CUSTOM = D3DFVF_XYZRHW | D3DFVF_DIFFUSE;
private const uint D3DPT_TRIANGLESTRIP = 5;
// D3DRENDERSTATETYPE
private const uint D3DRS_LIGHTING = 137;
private const uint D3DRS_ALPHABLENDENABLE = 27;
private const uint D3DRS_SRCBLEND = 19;
private const uint D3DRS_DESTBLEND = 20;
private const uint D3DRS_ZENABLE = 7;
private const uint D3DRS_FOGENABLE = 28;
// D3DBLEND
private const uint D3DBLEND_SRCALPHA = 5;
private const uint D3DBLEND_INVSRCALPHA = 6;
// D3DTRANSFORMSTATETYPE
private const uint D3DTS_WORLD = 256;
private const uint D3DTS_VIEW = 2;
private const uint D3DTS_PROJECTION = 3;
// ─── Vertex structure ─────────────────────────────────────────────
[StructLayout(LayoutKind.Sequential)]
private struct Vertex
{
public float X, Y, Z, RHW;
public uint Color; // ARGB
public Vertex(float x, float y, uint color)
{
X = x; Y = y; Z = 0f; RHW = 1f;
Color = color;
}
}
// ─── Device method delegates (COM/stdcall) ────────────────────────
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int SetRenderStateDelegate(IntPtr pDevice, uint state, uint value);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int GetRenderStateDelegate(IntPtr pDevice, uint state, out uint pValue);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int SetTextureDelegate(IntPtr pDevice, uint stage, IntPtr pTexture);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int SetFVFDelegate(IntPtr pDevice, uint fvf);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int DrawPrimitiveUPDelegate(
IntPtr pDevice, uint primitiveType, uint primitiveCount,
IntPtr pVertexStreamZeroData, uint vertexStreamZeroStride);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int SetVertexShaderDelegate(IntPtr pDevice, IntPtr pShader);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int SetPixelShaderDelegate(IntPtr pDevice, IntPtr pShader);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int SetTextureStageStateDelegate(IntPtr pDevice, uint stage, uint type, uint value);
// ─── Cached delegates (created once from vtable on first frame) ──
private static SetRenderStateDelegate? _setRenderState;
private static GetRenderStateDelegate? _getRenderState;
private static SetTextureDelegate? _setTexture;
private static SetFVFDelegate? _setFVF;
private static DrawPrimitiveUPDelegate? _drawPrimitiveUP;
private static SetVertexShaderDelegate? _setVertexShader;
private static SetPixelShaderDelegate? _setPixelShader;
private static SetTextureStageStateDelegate? _setTextureStageState;
private static bool _delegatesCached;
// ─── Rectangle config ─────────────────────────────────────────────
// Bright green semi-transparent rectangle, top-left corner
private const float RectX = 10f;
private const float RectY = 10f;
private const float RectW = 120f;
private const float RectH = 40f;
private const uint RectColor = 0xCC00FF00; // ARGB: green, ~80% opaque
// ─── Public API ───────────────────────────────────────────────────
public static void Draw(IntPtr pDevice)
{
if (pDevice == IntPtr.Zero) return;
// Cache vtable delegates on first call
if (!_delegatesCached)
CacheDelegates(pDevice);
// Save render states we'll modify
_getRenderState!(pDevice, D3DRS_LIGHTING, out uint oldLighting);
_getRenderState(pDevice, D3DRS_ALPHABLENDENABLE, out uint oldAlphaBlend);
_getRenderState(pDevice, D3DRS_SRCBLEND, out uint oldSrcBlend);
_getRenderState(pDevice, D3DRS_DESTBLEND, out uint oldDestBlend);
_getRenderState(pDevice, D3DRS_ZENABLE, out uint oldZEnable);
_getRenderState(pDevice, D3DRS_FOGENABLE, out uint oldFogEnable);
// Set up for 2D overlay drawing
_setRenderState!(pDevice, D3DRS_LIGHTING, 0); // no lighting
_setRenderState(pDevice, D3DRS_ZENABLE, 0); // no depth test
_setRenderState(pDevice, D3DRS_FOGENABLE, 0); // no fog
_setRenderState(pDevice, D3DRS_ALPHABLENDENABLE, 1); // alpha blend on
_setRenderState(pDevice, D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
_setRenderState(pDevice, D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
_setTexture!(pDevice, 0, IntPtr.Zero); // no texture
_setVertexShader!(pDevice, IntPtr.Zero); // fixed function
_setPixelShader!(pDevice, IntPtr.Zero); // fixed function
_setFVF!(pDevice, D3DFVF_CUSTOM);
// Build quad (triangle strip: TL, TR, BL, BR)
var verts = stackalloc Vertex[4];
verts[0] = new Vertex(RectX, RectY, RectColor);
verts[1] = new Vertex(RectX + RectW, RectY, RectColor);
verts[2] = new Vertex(RectX, RectY + RectH, RectColor);
verts[3] = new Vertex(RectX + RectW, RectY + RectH, RectColor);
_drawPrimitiveUP!(pDevice, D3DPT_TRIANGLESTRIP, 2, (IntPtr)verts, (uint)sizeof(Vertex));
// Restore saved render states
_setRenderState(pDevice, D3DRS_LIGHTING, oldLighting);
_setRenderState(pDevice, D3DRS_ALPHABLENDENABLE, oldAlphaBlend);
_setRenderState(pDevice, D3DRS_SRCBLEND, oldSrcBlend);
_setRenderState(pDevice, D3DRS_DESTBLEND, oldDestBlend);
_setRenderState(pDevice, D3DRS_ZENABLE, oldZEnable);
_setRenderState(pDevice, D3DRS_FOGENABLE, oldFogEnable);
}
// ─── Internals ────────────────────────────────────────────────────
private static void CacheDelegates(IntPtr pDevice)
{
IntPtr vtable = Marshal.ReadIntPtr(pDevice);
_setRenderState = GetMethod<SetRenderStateDelegate>(vtable, DeviceVTableIndex.SetRenderState);
_getRenderState = GetMethod<GetRenderStateDelegate>(vtable, DeviceVTableIndex.GetRenderState);
_setTexture = GetMethod<SetTextureDelegate>(vtable, DeviceVTableIndex.SetTexture);
_setFVF = GetMethod<SetFVFDelegate>(vtable, DeviceVTableIndex.SetFVF);
_drawPrimitiveUP = GetMethod<DrawPrimitiveUPDelegate>(vtable, DeviceVTableIndex.DrawPrimitiveUP);
_setVertexShader = GetMethod<SetVertexShaderDelegate>(vtable, DeviceVTableIndex.SetVertexShader);
_setPixelShader = GetMethod<SetPixelShaderDelegate>(vtable, DeviceVTableIndex.SetPixelShader);
_setTextureStageState = GetMethod<SetTextureStageStateDelegate>(vtable, DeviceVTableIndex.SetTextureStageState);
_delegatesCached = true;
RynthLog.D3D9("TestRenderer: D3D9 delegates cached.");
}
private static T GetMethod<T>(IntPtr vtable, int index) where T : Delegate
{
IntPtr addr = Marshal.ReadIntPtr(vtable, index * IntPtr.Size);
return Marshal.GetDelegateForFunctionPointer<T>(addr);
}
}

View file

@ -0,0 +1,706 @@
// ═══════════════════════════════════════════════════════════════════════════
// RynthCore.Engine — D3D9/VitalHud.cs
//
// "Hot HUD" — draws player Health / Stamina / Mana bars directly in the D3D9
// EndScene path, on AC's render thread, every frame. Ported from RynthCore2's
// overlay/hud_overlay.cpp; the D3D9 plumbing mirrors TestRenderer.cs (cached
// vtable delegates + full render-state save/restore).
//
// Visuals: a translucent panel with a drop shadow, three gradient-filled bars
// (track + fill + gloss + border) with an HP/STAM/MANA label and a right-
// aligned "cur/max" number drawn from the dependency-free BitmapFont.
// Everything is colored 2D quads (D3DFVF_XYZRHW | D3DFVF_DIFFUSE, no texture)
// accumulated into one static vertex batch flushed with a single
// DrawPrimitiveUP — no per-frame heap allocation (avoids the LFH per-frame-
// alloc AV class).
//
// Interactive: drag the panel to move it, drag the bottom-right grip to resize.
// Win32Backend routes mouse messages to TryHandleMouse, which consumes the ones
// that land on the HUD so they never reach AC (no stray camera spin). Position +
// scale persist to %APPDATA%\RynthCore\vitalhud.cfg.
//
// Data source: Compatibility.PlayerVitalsHooks.TryGetSnapshot — the same
// buffed-effective values AC's own bars render, maintained on AC's main thread.
// Draw and TryHandleMouse both run on that thread (EndScene / WndProc), so the
// shared geometry state needs no cross-thread synchronization.
// ═══════════════════════════════════════════════════════════════════════════
using System;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using RynthCore.Engine.Compatibility;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.D3D9;
internal static unsafe class VitalHud
{
// ─── D3D9 constants ───────────────────────────────────────────────
private const uint D3DFVF_XYZRHW = 0x0004;
private const uint D3DFVF_DIFFUSE = 0x0040;
private const uint HudFvf = D3DFVF_XYZRHW | D3DFVF_DIFFUSE;
private const uint D3DPT_TRIANGLELIST = 4;
// D3DRENDERSTATETYPE
private const uint D3DRS_ZENABLE = 7;
private const uint D3DRS_ZWRITEENABLE = 14;
private const uint D3DRS_ALPHATESTENABLE = 15;
private const uint D3DRS_SRCBLEND = 19;
private const uint D3DRS_DESTBLEND = 20;
private const uint D3DRS_CULLMODE = 22;
private const uint D3DRS_ALPHABLENDENABLE = 27;
private const uint D3DRS_FOGENABLE = 28;
private const uint D3DRS_STENCILENABLE = 52;
private const uint D3DRS_LIGHTING = 137;
private const uint D3DRS_COLORWRITEENABLE = 168;
private const uint D3DRS_BLENDOP = 171;
private const uint D3DRS_SCISSORTESTENABLE = 174;
// D3DTEXTURESTAGESTATETYPE
private const uint D3DTSS_COLOROP = 1;
private const uint D3DTSS_COLORARG1 = 2;
private const uint D3DTSS_ALPHAOP = 4;
private const uint D3DTSS_ALPHAARG1 = 6;
// values
private const uint D3DBLEND_SRCALPHA = 5;
private const uint D3DBLEND_INVSRCALPHA = 6;
private const uint D3DBLENDOP_ADD = 1;
private const uint D3DCULL_NONE = 1;
private const uint D3DTOP_DISABLE = 1;
private const uint D3DTOP_SELECTARG1 = 2;
private const uint D3DTA_DIFFUSE = 0;
// ─── Win32 messages + capture P/Invoke ────────────────────────────
private const uint WM_LBUTTONDOWN = 0x0201;
private const uint WM_LBUTTONUP = 0x0202;
private const uint WM_MOUSEMOVE = 0x0200;
[DllImport("user32.dll")]
private static extern IntPtr SetCapture(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool ReleaseCapture();
// ─── Vertex ───────────────────────────────────────────────────────
[StructLayout(LayoutKind.Sequential)]
private struct Vertex
{
public float X, Y, Z, Rhw;
public uint Color; // ARGB
}
[StructLayout(LayoutKind.Sequential)]
private struct D3DVIEWPORT9
{
public uint X, Y, Width, Height;
public float MinZ, MaxZ;
}
// ─── Device method delegates (COM/stdcall) ────────────────────────
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int SetRenderStateDelegate(IntPtr dev, uint state, uint value);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int GetRenderStateDelegate(IntPtr dev, uint state, out uint pValue);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int SetTextureStageStateDelegate(IntPtr dev, uint stage, uint type, uint value);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int GetTextureStageStateDelegate(IntPtr dev, uint stage, uint type, out uint pValue);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int SetTextureDelegate(IntPtr dev, uint stage, IntPtr pTexture);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int GetTextureDelegate(IntPtr dev, uint stage, out IntPtr ppTexture);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int SetFVFDelegate(IntPtr dev, uint fvf);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int GetFVFDelegate(IntPtr dev, out uint fvf);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int SetVertexShaderDelegate(IntPtr dev, IntPtr pShader);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int GetVertexShaderDelegate(IntPtr dev, out IntPtr ppShader);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int SetPixelShaderDelegate(IntPtr dev, IntPtr pShader);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int GetPixelShaderDelegate(IntPtr dev, out IntPtr ppShader);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int DrawPrimitiveUPDelegate(IntPtr dev, uint primitiveType, uint primitiveCount, IntPtr pData, uint stride);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int GetViewportDelegate(IntPtr dev, out D3DVIEWPORT9 vp);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate uint ReleaseComDelegate(IntPtr pUnk);
private static SetRenderStateDelegate? _setRenderState;
private static GetRenderStateDelegate? _getRenderState;
private static SetTextureStageStateDelegate? _setTextureStageState;
private static GetTextureStageStateDelegate? _getTextureStageState;
private static SetTextureDelegate? _setTexture;
private static GetTextureDelegate? _getTexture;
private static SetFVFDelegate? _setFVF;
private static GetFVFDelegate? _getFVF;
private static SetVertexShaderDelegate? _setVertexShader;
private static GetVertexShaderDelegate? _getVertexShader;
private static SetPixelShaderDelegate? _setPixelShader;
private static GetPixelShaderDelegate? _getPixelShader;
private static DrawPrimitiveUPDelegate? _drawPrimitiveUP;
private static GetViewportDelegate? _getViewport;
private static bool _delegatesCached;
// ─── Geometry / interaction state (AC main thread only) ───────────
private const float MinScale = 0.6f;
private const float MaxScale = 2.5f;
private static float _hudX = 16f, _hudY = 16f, _scale = 1f;
private static float _vpW, _vpH; // last viewport, for input clamp
private static bool _geomInit;
private static bool _firstDrawLogged;
private static int _dragMode; // 0 none, 1 move, 2 resize
private static float _grabDX, _grabDY;
private static float _resizeStartScale = 1f, _resizeStartDist = 1f;
/// <summary>True while the user is dragging or resizing the HUD. Win32Backend
/// keeps routing mouse messages to <see cref="TryHandleMouse"/> while set.</summary>
public static bool IsDragging => _dragMode != 0;
// ─── Vertex batch (single static buffer; no per-frame heap alloc) ──
// Text is the big consumer — the outline pass below draws each number 9×.
private const int MaxVerts = 48000;
private static readonly Vertex[] _batch = new Vertex[MaxVerts];
private static int _batchCount;
// Cached text sink + color so BitmapFont.Emit allocates nothing per call.
private static readonly BitmapFont.CellSink _cellSink = TextCell;
private static uint _textColor;
// ─── Layout derived from the uniform scale ────────────────────────
private struct Metrics
{
public float Scale, Pad, BarW, BarH, Gap, PanelW, PanelH, Grip;
}
private static Metrics Metric(float s)
{
if (s < MinScale) s = MinScale;
if (s > MaxScale) s = MaxScale;
Metrics m;
m.Scale = s;
m.Pad = 8f * s;
m.BarW = 228f * s; // wide enough for a big "cur/max" number
m.BarH = 26f * s; // taller bars → bigger, retail-legible numbers
m.Gap = 6f * s;
m.PanelW = m.Pad * 2f + m.BarW;
m.PanelH = m.Pad * 2f + m.BarH * 3f + m.Gap * 2f;
m.Grip = 16f * s;
return m;
}
// ─── Color helpers ────────────────────────────────────────────────
private static uint Argb(int a, int r, int g, int b)
=> ((uint)a << 24) | ((uint)r << 16) | ((uint)g << 8) | (uint)b;
private static uint Lighten(uint c, int add)
{
static int Cl(int v) => v < 0 ? 0 : (v > 255 ? 255 : v);
int a = (int)((c >> 24) & 0xFF);
int r = (int)((c >> 16) & 0xFF);
int g = (int)((c >> 8) & 0xFF);
int b = (int)(c & 0xFF);
return Argb(a, Cl(r + add), Cl(g + add), Cl(b + add));
}
// ─── Batch builders ───────────────────────────────────────────────
private static void BatchReset() => _batchCount = 0;
private static void PushQuad(float x0, float y0, float x1, float y1,
uint cTL, uint cTR, uint cBR, uint cBL)
{
if (_batchCount + 6 > MaxVerts) return;
Set(ref _batch[_batchCount + 0], x0, y0, cTL);
Set(ref _batch[_batchCount + 1], x1, y0, cTR);
Set(ref _batch[_batchCount + 2], x1, y1, cBR);
Set(ref _batch[_batchCount + 3], x0, y0, cTL);
Set(ref _batch[_batchCount + 4], x1, y1, cBR);
Set(ref _batch[_batchCount + 5], x0, y1, cBL);
_batchCount += 6;
static void Set(ref Vertex v, float x, float y, uint c)
{
v.X = x; v.Y = y; v.Z = 0f; v.Rhw = 1f; v.Color = c;
}
}
private static void PushRect(float x0, float y0, float x1, float y1, uint c)
=> PushQuad(x0, y0, x1, y1, c, c, c, c);
private static void PushVGrad(float x0, float y0, float x1, float y1, uint top, uint bot)
=> PushQuad(x0, y0, x1, y1, top, top, bot, bot);
// ─── Text → batched quads via the bitmap font ─────────────────────
private static void TextCell(int x0, int y0, int x1, int y1)
=> PushRect(x0, y0, x1, y1, _textColor);
// Draws text with a full dark outline (all 8 neighbour offsets) then the
// foreground on top, so it stays legible over any bar fill color — the
// single drop-shadow was washed out on the light (yellow) bar.
private static void DrawText(ReadOnlySpan<char> s, int x, int y, int cellPx, uint color)
{
int o = cellPx >= 4 ? 2 : 1; // outline thickness in px
_textColor = Argb(235, 0, 0, 0);
BitmapFont.Emit(s, x - o, y - o, cellPx, _cellSink);
BitmapFont.Emit(s, x, y - o, cellPx, _cellSink);
BitmapFont.Emit(s, x + o, y - o, cellPx, _cellSink);
BitmapFont.Emit(s, x - o, y, cellPx, _cellSink);
BitmapFont.Emit(s, x + o, y, cellPx, _cellSink);
BitmapFont.Emit(s, x - o, y + o, cellPx, _cellSink);
BitmapFont.Emit(s, x, y + o, cellPx, _cellSink);
BitmapFont.Emit(s, x + o, y + o, cellPx, _cellSink);
_textColor = color;
BitmapFont.Emit(s, x, y, cellPx, _cellSink);
}
// "cur/max" formatted into the caller's buffer without allocating; returns
// the number of chars written (≤ buf.Length).
private static int FormatVital(uint cur, uint mx, Span<char> buf)
{
int len = 0;
if (cur.TryFormat(buf, out int w1)) len += w1;
if (len < buf.Length) buf[len++] = '/';
if (mx.TryFormat(buf.Slice(len), out int w2)) len += w2;
return len;
}
private static void EmitBar(float x, float y, in Metrics m,
uint cur, uint mx, uint baseColor)
{
float w = m.BarW, h = m.BarH;
PushRect(x, y, x + w, y + h, Argb(205, 18, 20, 26)); // track
if (mx > 0)
{
float ratio = (float)cur / mx;
if (ratio < 0f) ratio = 0f;
if (ratio > 1f) ratio = 1f;
float fw = w * ratio;
PushVGrad(x, y, x + fw, y + h, Lighten(baseColor, 55), baseColor); // fill
PushRect(x, y, x + fw, y + h * 0.32f, Argb(60, 255, 255, 255)); // gloss
}
float bw = m.Scale >= 1.5f ? 2f : 1f; // border
uint bc = Argb(180, 90, 100, 120);
PushRect(x, y, x + w, y + bw, bc);
PushRect(x, y + h - bw, x + w, y + h, bc);
PushRect(x, y, x + bw, y + h, bc);
PushRect(x + w - bw, y, x + w, y + h, bc);
// Number only (no label — the red/yellow/blue color identifies the bar).
// Sized as large as fits the bar, centered, with a dark outline so it
// reads clearly over any fill color (especially white-on-yellow).
Span<char> numBuf = stackalloc char[24];
ReadOnlySpan<char> num = numBuf[..FormatVital(cur, mx, numBuf)];
int innerPad = (int)(m.Pad * 0.4f);
if (innerPad < 2) innerPad = 2;
int availW = (int)w - 2 * innerPad;
int cellPx = (int)(h * 0.82f / BitmapFont.GlyphH); // tallest that fits the bar
if (cellPx < 1) cellPx = 1;
while (cellPx > 1 && BitmapFont.MeasureWidth(num, cellPx) > availW) cellPx--;
int tw = BitmapFont.MeasureWidth(num, cellPx);
int th = BitmapFont.Height(cellPx);
int tx = (int)(x + (w - tw) * 0.5f); // center horizontally
int ty = (int)(y + (h - th) * 0.5f); // center vertically
DrawText(num, tx, ty, cellPx, Argb(255, 245, 250, 255));
}
// ─── Public API ───────────────────────────────────────────────────
public static void Draw(IntPtr pDevice)
{
if (pDevice == IntPtr.Zero) return;
if (!PlayerVitalsHooks.TryGetSnapshot(out PlayerVitalsSnapshot snap)) return;
if (!_delegatesCached)
CacheDelegates(pDevice);
if (_drawPrimitiveUP == null) return; // delegate cache failed
if (_getViewport!(pDevice, out D3DVIEWPORT9 vp) < 0) return;
float wF = vp.Width;
float hF = vp.Height;
if (wF < 1f || hF < 1f) return;
if (!_firstDrawLogged)
{
_firstDrawLogged = true;
RynthLog.D3D9("VitalHud: first draw.");
}
// First-draw placement: prefer the saved config, else default top-right.
if (!_geomInit)
{
_geomInit = true;
if (LoadCfg(out float lx, out float ly, out float ls))
{
_scale = ls; _hudX = lx; _hudY = ly;
}
else
{
_scale = 1f;
Metrics dm = Metric(1f);
_hudX = wF - dm.PanelW - 16f;
_hudY = 16f;
}
}
// ── Save the device state we are about to clobber ──────────────
_getRenderState!(pDevice, D3DRS_ZENABLE, out uint svZE);
_getRenderState(pDevice, D3DRS_ZWRITEENABLE, out uint svZWE);
_getRenderState(pDevice, D3DRS_ALPHATESTENABLE, out uint svATE);
_getRenderState(pDevice, D3DRS_ALPHABLENDENABLE, out uint svABE);
_getRenderState(pDevice, D3DRS_SRCBLEND, out uint svSB);
_getRenderState(pDevice, D3DRS_DESTBLEND, out uint svDB);
_getRenderState(pDevice, D3DRS_BLENDOP, out uint svBO);
_getRenderState(pDevice, D3DRS_CULLMODE, out uint svCull);
_getRenderState(pDevice, D3DRS_LIGHTING, out uint svLit);
_getRenderState(pDevice, D3DRS_FOGENABLE, out uint svFog);
_getRenderState(pDevice, D3DRS_STENCILENABLE, out uint svSte);
_getRenderState(pDevice, D3DRS_SCISSORTESTENABLE, out uint svSci);
_getRenderState(pDevice, D3DRS_COLORWRITEENABLE, out uint svCW);
_getFVF!(pDevice, out uint svFvf);
_getTextureStageState!(pDevice, 0, D3DTSS_COLOROP, out uint svT0CO);
_getTextureStageState(pDevice, 0, D3DTSS_COLORARG1, out uint svT0CA1);
_getTextureStageState(pDevice, 0, D3DTSS_ALPHAOP, out uint svT0AO);
_getTextureStageState(pDevice, 0, D3DTSS_ALPHAARG1, out uint svT0AA1);
_getTextureStageState(pDevice, 1, D3DTSS_COLOROP, out uint svT1CO);
_getVertexShader!(pDevice, out IntPtr svVS);
_getPixelShader!(pDevice, out IntPtr svPS);
_getTexture!(pDevice, 0, out IntPtr svTex0);
try
{
// ── Set HUD state: 2D, alpha-blended, colored verts, no tex/shaders ──
_setRenderState!(pDevice, D3DRS_ZENABLE, 0);
_setRenderState(pDevice, D3DRS_ZWRITEENABLE, 0);
_setRenderState(pDevice, D3DRS_ALPHATESTENABLE, 0);
_setRenderState(pDevice, D3DRS_ALPHABLENDENABLE, 1);
_setRenderState(pDevice, D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
_setRenderState(pDevice, D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
_setRenderState(pDevice, D3DRS_BLENDOP, D3DBLENDOP_ADD);
_setRenderState(pDevice, D3DRS_CULLMODE, D3DCULL_NONE);
_setRenderState(pDevice, D3DRS_LIGHTING, 0);
_setRenderState(pDevice, D3DRS_FOGENABLE, 0);
_setRenderState(pDevice, D3DRS_STENCILENABLE, 0);
_setRenderState(pDevice, D3DRS_SCISSORTESTENABLE, 0);
_setRenderState(pDevice, D3DRS_COLORWRITEENABLE, 0xF);
_setTextureStageState!(pDevice, 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
_setTextureStageState(pDevice, 0, D3DTSS_COLORARG1, D3DTA_DIFFUSE);
_setTextureStageState(pDevice, 0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
_setTextureStageState(pDevice, 0, D3DTSS_ALPHAARG1, D3DTA_DIFFUSE);
_setTextureStageState(pDevice, 1, D3DTSS_COLOROP, D3DTOP_DISABLE);
_setTexture!(pDevice, 0, IntPtr.Zero);
_setVertexShader!(pDevice, IntPtr.Zero);
_setPixelShader!(pDevice, IntPtr.Zero);
_setFVF!(pDevice, HudFvf);
BuildBatch(in snap, wF, hF);
if (_batchCount >= 3)
{
fixed (Vertex* p = _batch)
{
_drawPrimitiveUP(pDevice, D3DPT_TRIANGLELIST,
(uint)(_batchCount / 3), (IntPtr)p, (uint)sizeof(Vertex));
}
}
_vpW = wF; // for input hit-test clamping
_vpH = hF;
}
finally
{
// ── Restore the saved state ────────────────────────────────
_setRenderState!(pDevice, D3DRS_ZENABLE, svZE);
_setRenderState(pDevice, D3DRS_ZWRITEENABLE, svZWE);
_setRenderState(pDevice, D3DRS_ALPHATESTENABLE, svATE);
_setRenderState(pDevice, D3DRS_ALPHABLENDENABLE, svABE);
_setRenderState(pDevice, D3DRS_SRCBLEND, svSB);
_setRenderState(pDevice, D3DRS_DESTBLEND, svDB);
_setRenderState(pDevice, D3DRS_BLENDOP, svBO);
_setRenderState(pDevice, D3DRS_CULLMODE, svCull);
_setRenderState(pDevice, D3DRS_LIGHTING, svLit);
_setRenderState(pDevice, D3DRS_FOGENABLE, svFog);
_setRenderState(pDevice, D3DRS_STENCILENABLE, svSte);
_setRenderState(pDevice, D3DRS_SCISSORTESTENABLE, svSci);
_setRenderState(pDevice, D3DRS_COLORWRITEENABLE, svCW);
_setTextureStageState!(pDevice, 0, D3DTSS_COLOROP, svT0CO);
_setTextureStageState(pDevice, 0, D3DTSS_COLORARG1, svT0CA1);
_setTextureStageState(pDevice, 0, D3DTSS_ALPHAOP, svT0AO);
_setTextureStageState(pDevice, 0, D3DTSS_ALPHAARG1, svT0AA1);
_setTextureStageState(pDevice, 1, D3DTSS_COLOROP, svT1CO);
_setFVF!(pDevice, svFvf);
_setVertexShader!(pDevice, svVS);
_setPixelShader!(pDevice, svPS);
_setTexture!(pDevice, 0, svTex0);
// GetVertexShader / GetPixelShader / GetTexture each AddRef — release.
ReleaseCom(svVS);
ReleaseCom(svPS);
ReleaseCom(svTex0);
}
}
private static void BuildBatch(in PlayerVitalsSnapshot snap, float wF, float hF)
{
Metrics m = Metric(_scale);
float px = _hudX;
float py = _hudY;
if (px > wF - m.PanelW) px = wF - m.PanelW; // keep on-screen (draw-only)
if (py > hF - m.PanelH) py = hF - m.PanelH;
if (px < 0f) px = 0f;
if (py < 0f) py = 0f;
BatchReset();
float so = 5f * m.Scale; // shadow
PushRect(px + so, py + so, px + m.PanelW + so, py + m.PanelH + so, Argb(110, 0, 0, 0));
PushVGrad(px, py, px + m.PanelW, py + m.PanelH, // backing
Argb(205, 28, 30, 38), Argb(205, 16, 17, 22));
PushRect(px, py, px + m.PanelW, py + m.Pad * 0.6f, Argb(45, 255, 255, 255)); // header hint
float pbw = m.Scale >= 1.5f ? 2f : 1f; // panel border
uint pbc = Argb(200, 120, 130, 150);
PushRect(px, py, px + m.PanelW, py + pbw, pbc);
PushRect(px, py + m.PanelH - pbw, px + m.PanelW, py + m.PanelH, pbc);
PushRect(px, py, px + pbw, py + m.PanelH, pbc);
PushRect(px + m.PanelW - pbw, py, px + m.PanelW, py + m.PanelH, pbc);
float bx = px + m.Pad;
float by = py + m.Pad;
EmitBar(bx, by, in m, snap.Health, snap.MaxHealth, Argb(235, 200, 45, 45));
by += m.BarH + m.Gap;
EmitBar(bx, by, in m, snap.Stamina, snap.MaxStamina, Argb(235, 205, 170, 45));
by += m.BarH + m.Gap;
EmitBar(bx, by, in m, snap.Mana, snap.MaxMana, Argb(235, 55, 115, 235));
// resize grip (three dots) bottom-right
float d = 3f * m.Scale;
if (d < 2f) d = 2f;
float gx = px + m.PanelW - m.Pad * 0.5f;
float gy = py + m.PanelH - m.Pad * 0.5f;
uint gc = Argb(200, 200, 205, 215);
for (int i = 1; i <= 3; i++)
{
float ox = gx - i * (d + 1f);
float oy = gy - i * (d + 1f);
PushRect(ox, oy, ox + d, oy + d, gc);
}
}
// ─── Input ────────────────────────────────────────────────────────
/// <summary>
/// Handles left-button drag (anywhere on the panel) + grip resize. Returns
/// true when the message landed on the HUD and should be swallowed so it
/// never reaches AC. Called from Win32Backend.WndProcHook on AC's main
/// thread, before the Avalonia forward. No-op (returns false) when the HUD
/// is not being drawn.
/// </summary>
public static bool TryHandleMouse(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
{
if (!_geomInit || !EngineSettings.DrawCustomVitalBars)
return false;
switch (msg)
{
case WM_LBUTTONDOWN:
{
float mxf = (short)((long)lParam & 0xFFFF);
float myf = (short)(((long)lParam >> 16) & 0xFFFF);
Metrics m = Metric(_scale);
// Clamp the same way Draw does so the hit-test matches the pixels.
float px = _hudX, py = _hudY;
if (_vpW > 0f && px > _vpW - m.PanelW) px = _vpW - m.PanelW;
if (_vpH > 0f && py > _vpH - m.PanelH) py = _vpH - m.PanelH;
if (px < 0f) px = 0f;
if (py < 0f) py = 0f;
bool inPanel = mxf >= px && mxf <= px + m.PanelW &&
myf >= py && myf <= py + m.PanelH;
if (!inPanel) return false;
// Pin the (clamped) top-left so move/resize anchor to the pixels.
_hudX = px; _hudY = py;
bool inGrip = mxf >= px + m.PanelW - m.Grip && myf >= py + m.PanelH - m.Grip;
if (inGrip)
{
float dx = mxf - px, dy = myf - py;
float dist = MathF.Sqrt(dx * dx + dy * dy);
if (dist < 8f) dist = 8f;
_resizeStartDist = dist;
_resizeStartScale = m.Scale;
_dragMode = 2;
}
else
{
_grabDX = mxf - px;
_grabDY = myf - py;
_dragMode = 1;
}
SetCapture(hWnd);
return true;
}
case WM_MOUSEMOVE:
{
if (_dragMode == 0) return false;
// Left button no longer held (we missed the UP — e.g. capture
// stolen by alt-tab): end the drag and let the move through so the
// HUD can't get stuck following the cursor.
if (((long)wParam & 0x0001 /* MK_LBUTTON */) == 0)
{
_dragMode = 0;
ReleaseCapture();
SaveCfg();
return false;
}
float mxf = (short)((long)lParam & 0xFFFF);
float myf = (short)(((long)lParam >> 16) & 0xFFFF);
if (_dragMode == 1) // move
{
float nx = mxf - _grabDX;
float ny = myf - _grabDY;
Metrics m = Metric(_scale);
if (_vpW > 0f && nx > _vpW - m.PanelW) nx = _vpW - m.PanelW;
if (_vpH > 0f && ny > _vpH - m.PanelH) ny = _vpH - m.PanelH;
if (nx < 0f) nx = 0f;
if (ny < 0f) ny = 0f;
_hudX = nx; _hudY = ny;
}
else // resize
{
float dx = mxf - _hudX, dy = myf - _hudY;
float dist = MathF.Sqrt(dx * dx + dy * dy);
float s = _resizeStartScale * dist / _resizeStartDist;
if (s < MinScale) s = MinScale;
if (s > MaxScale) s = MaxScale;
_scale = s;
}
return true;
}
case WM_LBUTTONUP:
{
if (_dragMode == 0) return false;
_dragMode = 0;
ReleaseCapture();
SaveCfg();
return true;
}
default:
return false;
}
}
// ─── Persistence: %APPDATA%\RynthCore\vitalhud.cfg ("x y scale") ──
private static string? CfgPath()
{
string? appData = Environment.GetEnvironmentVariable("APPDATA");
if (string.IsNullOrEmpty(appData)) return null;
return Path.Combine(appData, "RynthCore", "vitalhud.cfg");
}
private static bool LoadCfg(out float x, out float y, out float s)
{
x = 0f; y = 0f; s = 1f;
try
{
string? path = CfgPath();
if (path == null || !File.Exists(path)) return false;
string[] parts = File.ReadAllText(path)
.Split([' ', '\t', '\r', '\n'], StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 3) return false;
if (!float.TryParse(parts[0], NumberStyles.Float, CultureInfo.InvariantCulture, out float fx) ||
!float.TryParse(parts[1], NumberStyles.Float, CultureInfo.InvariantCulture, out float fy) ||
!float.TryParse(parts[2], NumberStyles.Float, CultureInfo.InvariantCulture, out float fs))
return false;
if (fs < MinScale) fs = MinScale;
if (fs > MaxScale) fs = MaxScale;
if (fx < 0f) fx = 0f;
if (fy < 0f) fy = 0f;
x = fx; y = fy; s = fs;
return true;
}
catch (Exception ex)
{
RynthLog.D3D9($"VitalHud: LoadCfg failed - {ex.Message}");
return false;
}
}
private static void SaveCfg()
{
try
{
string? path = CfgPath();
if (path == null) return;
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
string body = string.Format(CultureInfo.InvariantCulture, "{0:F1} {1:F1} {2:F4}", _hudX, _hudY, _scale);
File.WriteAllText(path, body);
}
catch (Exception ex)
{
RynthLog.D3D9($"VitalHud: SaveCfg failed - {ex.Message}");
}
}
// ─── Internals ────────────────────────────────────────────────────
private static void CacheDelegates(IntPtr pDevice)
{
IntPtr vtable = Marshal.ReadIntPtr(pDevice);
_setRenderState = Get<SetRenderStateDelegate>(vtable, DeviceVTableIndex.SetRenderState);
_getRenderState = Get<GetRenderStateDelegate>(vtable, DeviceVTableIndex.GetRenderState);
_setTextureStageState = Get<SetTextureStageStateDelegate>(vtable, DeviceVTableIndex.SetTextureStageState);
_getTextureStageState = Get<GetTextureStageStateDelegate>(vtable, DeviceVTableIndex.GetTextureStageState);
_setTexture = Get<SetTextureDelegate>(vtable, DeviceVTableIndex.SetTexture);
_getTexture = Get<GetTextureDelegate>(vtable, DeviceVTableIndex.GetTexture);
_setFVF = Get<SetFVFDelegate>(vtable, DeviceVTableIndex.SetFVF);
_getFVF = Get<GetFVFDelegate>(vtable, DeviceVTableIndex.GetFVF);
_setVertexShader = Get<SetVertexShaderDelegate>(vtable, DeviceVTableIndex.SetVertexShader);
_getVertexShader = Get<GetVertexShaderDelegate>(vtable, DeviceVTableIndex.GetVertexShader);
_setPixelShader = Get<SetPixelShaderDelegate>(vtable, DeviceVTableIndex.SetPixelShader);
_getPixelShader = Get<GetPixelShaderDelegate>(vtable, DeviceVTableIndex.GetPixelShader);
_drawPrimitiveUP = Get<DrawPrimitiveUPDelegate>(vtable, DeviceVTableIndex.DrawPrimitiveUP);
_getViewport = Get<GetViewportDelegate>(vtable, DeviceVTableIndex.GetViewport);
_delegatesCached = true;
RynthLog.D3D9("VitalHud: D3D9 delegates cached.");
}
private static T Get<T>(IntPtr vtable, int index) where T : Delegate
{
IntPtr addr = Marshal.ReadIntPtr(vtable, index * IntPtr.Size);
return Marshal.GetDelegateForFunctionPointer<T>(addr);
}
private static void ReleaseCom(IntPtr pUnk)
{
if (pUnk == IntPtr.Zero) return;
IntPtr vtbl = Marshal.ReadIntPtr(pUnk);
IntPtr releaseAddr = Marshal.ReadIntPtr(vtbl, 2 * IntPtr.Size); // IUnknown::Release
var release = Marshal.GetDelegateForFunctionPointer<ReleaseComDelegate>(releaseAddr);
release(pUnk);
}
}

View file

@ -0,0 +1,196 @@
// ============================================================================
// RynthCore.Engine - EngineLifecycle.cs
// Orderly engine teardown so the loader can FreeLibrary RynthCore.Engine.dll
// without crashing acclient.exe.
//
// Order matters. Each phase is wrapped so a failure does not abort the rest:
//
// 1. EndSceneHook.Uninstall — chains into EngineFrameController.Shutdown which
// tears down PluginManager (RynthPluginShutdown + FreeLibrary plugins),
// OverlayTextureRenderer, ViewportRendererBackend, ViewportPlatformBackend,
// DX9Backend, Win32Backend (restores WndProc), and destroys ImGui context.
// 2. Drain — sleep so any in-flight EndScene call has returned through the
// trampoline before we tear down anything else.
// 3. AvaloniaOverlay.Stop — Dispatcher shutdown, join STA thread.
// 4. PluginManager.ShutdownAll — defensive (no-op if step 1 already ran).
// 5. MH_DisableHook(ALL) + MH_Uninitialize — safety net for Compatibility/*
// hooks that aren't in the ImGui chain.
//
// After this returns, the engine has stopped reading game memory, stopped
// drawing, and stopped servicing callbacks. The loader may now FreeLibrary
// the engine module.
//
// IMPORTANT: do not call from the AC render thread (an EndScene detour) —
// the caller must be on a separate thread so the detour can return cleanly
// before we disable the hook.
// ============================================================================
using System;
using System.Runtime.InteropServices;
using System.Threading;
using RynthCore.Engine.D3D9;
using RynthCore.Engine.Hooking;
using RynthCore.Engine.Plugins;
using RynthCore.Engine.UI;
namespace RynthCore.Engine;
internal static class EngineLifecycle
{
private static int _shuttingDown;
private static int _hasShutDown;
/// <summary>
/// Named auto-reset event the loader (RynthCore.Loader.dll) waits on.
/// Signaling it triggers shutdown + FreeLibrary + LoadLibrary + re-init.
/// Must match the helper in RynthCore.Loader.EntryPoint.
/// PID-suffixed so a reload click on one acclient.exe doesn't trigger
/// reload in every other acclient.exe in the same login session
/// (which is the broadcast scope of "Local\" without the suffix).
/// </summary>
private static string ReloadEventName => $"Local\\RynthCore.Engine.RequestReload.p{Environment.ProcessId}";
private const uint EVENT_MODIFY_STATE = 0x0002;
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr OpenEventW(uint dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, string lpName);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetEvent(IntPtr hEvent);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr hObject);
internal static bool IsShuttingDown => Volatile.Read(ref _shuttingDown) != 0;
internal static bool HasShutDown => Volatile.Read(ref _hasShutDown) != 0;
/// <summary>
/// Asks the loader to reload the engine. Returns immediately; the loader's
/// watcher thread runs the actual shutdown+reload sequence so the caller
/// (typically the ImGui shell on the render thread) can finish its frame.
/// </summary>
public static bool SignalReload()
{
IntPtr hEvent = OpenEventW(EVENT_MODIFY_STATE, false, ReloadEventName);
if (hEvent == IntPtr.Zero)
{
int err = Marshal.GetLastWin32Error();
RynthLog.Info($"SignalReload: OpenEventW failed (error {err}). Loader watcher may not be running.");
return false;
}
try
{
bool ok = SetEvent(hEvent);
if (!ok)
RynthLog.Info($"SignalReload: SetEvent failed (error {Marshal.GetLastWin32Error()}).");
else
RynthLog.Info("SignalReload: reload event signaled — loader will run reload sequence.");
return ok;
}
finally
{
CloseHandle(hEvent);
}
}
public static void Shutdown()
{
if (Interlocked.CompareExchange(ref _shuttingDown, 1, 0) != 0)
{
RynthLog.Info("EngineLifecycle: Shutdown already in progress — ignoring repeat call.");
return;
}
RynthLog.Info("EngineLifecycle: Shutdown beginning.");
// Stop the hang watchdog BEFORE its beat source (the EndScene detour)
// is uninstalled. A still-running old-generation watchdog sees the beat
// go silent, declares a false hang ~4s later, suspends AC's healthy main
// thread for stack samples, and writes a spurious minidump — all while
// the next engine generation is initializing.
Step("MainThreadHangWatchdog.Stop", () => MainThreadHangWatchdog.Stop());
// Disarm the marshalled-action queue BEFORE anything else tears down.
// The UseTime/EndScene detours stay live until MH_DisableHook(ALL), so
// without this a queued plugin mutation (SetAutoRun etc.) executes on
// AC's main thread mid-teardown against state the plugin Shutdowns are
// concurrently freeing — a heap-corruption window adjacent to the
// 2026-06-11 DINPUT8 reload wedge.
Step("AcMainThreadQueue.Disarm", () => Compatibility.AcMainThreadQueue.Disarm());
Step("EndSceneHook.Uninstall", () => EndSceneHook.Uninstall());
// Give in-flight EndScene calls a chance to drain. AC's render thread
// may still be inside our detour right now; sleeping a few frames is
// a cheap way to ensure it has returned through the trampoline before
// we tear down anything else.
Thread.Sleep(80);
Step("AvaloniaOverlay.Stop", () => AvaloniaOverlay.Stop());
// Restore AC's original window WndProc. EngineFrameController.Shutdown
// also calls Win32Backend.Shutdown, but it early-returns when ImGui
// never initialized (EnableImGuiBackend=false) — and in that mode the
// subclass is installed by AvaloniaOverlay.Start()'s GameHwnd poller,
// so it would otherwise never be removed. It then leaks across hot
// reloads (each gen stacks on the last; the frozen gen swallows WM_CHAR
// → AC chat box stops receiving input after a reload). Idempotent —
// no-ops if Init never ran or the ImGui path already tore it down.
Step("Win32Backend.Shutdown (input subclass)", () => ImGuiBackend.Win32Backend.Shutdown());
// Stop the dispatch-file watcher and the auto-ID drain timer before the
// tick pump and plugins go away — both otherwise keep firing in the old
// generation's (intentionally still-mapped) module across hot-reloads.
Step("ChatFileDispatcher.Stop", () => Compatibility.ChatFileDispatcher.Stop());
Step("AutoIdService.Stop", () => Compatibility.AutoIdService.Stop());
// Stop the headless tick pump BEFORE plugin shutdown / FreeLibrary.
// Otherwise the pump's TickAll/ProcessPendingActions can be mid-call
// into a plugin whose code pages we're about to unmap → AV.
Step("TickPump.StopAndJoin", () => EntryPoint.StopTickPumpAndJoin());
Step("PluginManager.ShutdownAll (defensive)", () => PluginManager.ShutdownAll());
// Stop HeartbeatLogger BEFORE MinHook teardown — it's a managed thread
// that keeps running and would execute code pages the loader is about to
// unmap (FreeLibrary on the engine module right after RynthCoreShutdown
// returns). Without this, hot-reload fires a CLR exception in the dying
// module's code at the moment of FreeLibrary.
Step("HeartbeatLogger.StopAndJoin", () => Compatibility.HeartbeatLogger.StopAndJoin());
Step("MH_DisableHook(ALL)", () =>
{
// DisableHook restores the original code at every hooked function — that's
// what we actually need for safety. Do NOT call MH_Uninitialize: it frees
// the trampoline pool memory, and AC's CRT atexit chain (or cached engine
// delegates) can still reference those addresses during the rest of
// shutdown → AV at the trampoline block (e.g. 0x04CE0F60). Leaving the
// trampoline memory allocated for the remainder of the process lifetime
// is harmless; OS reclaims it on actual exit. On hot-reload, the new
// engine re-Initializes MinHook; existing process-wide state is fine.
int disable = MinHook.MH_DisableHook(MinHook.MH_ALL_HOOKS);
RynthLog.Info($"MH_DisableHook(ALL) = {MinHook.StatusString(disable)}");
});
Volatile.Write(ref _hasShutDown, 1);
RynthLog.Info("EngineLifecycle: Shutdown complete.");
}
private static void Step(string name, Action action)
{
try
{
RynthLog.Info($"EngineLifecycle: -> {name}");
long t0 = Environment.TickCount64;
action();
RynthLog.Info($"EngineLifecycle: {name} ok ({Environment.TickCount64 - t0} ms)");
}
catch (Exception ex)
{
RynthLog.Info($"EngineLifecycle: {name} FAILED: {ex.GetType().Name}: {ex.Message}");
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,160 @@
// ═══════════════════════════════════════════════════════════════════════════
// RynthCore.Engine — Hooking/MinHook.cs
// Minimal P/Invoke wrapper for MinHook (minhook.x86.dll).
//
// Get the DLL from:
// https://github.com/TsudaKageworthy/minhook/releases
// Download minhook.x86.dll → place next to RynthCore.Engine.dll
// ═══════════════════════════════════════════════════════════════════════════
using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace RynthCore.Engine.Hooking;
internal static class MinHook
{
private const string DLL = "minhook.x86.dll";
// ─── Status codes (must match MinHook's MH_STATUS enum) ────────────
public const int MH_OK = 0;
public const int MH_ERROR_ALREADY_INITIALIZED = 1;
public const int MH_ERROR_NOT_INITIALIZED = 2;
public const int MH_ERROR_ALREADY_CREATED = 3;
public const int MH_ERROR_NOT_CREATED = 4;
// ─── Core API ─────────────────────────────────────────────────────
[DllImport(DLL, CallingConvention = CallingConvention.StdCall)]
public static extern int MH_Initialize();
[DllImport(DLL, CallingConvention = CallingConvention.StdCall)]
public static extern int MH_Uninitialize();
[DllImport(DLL, CallingConvention = CallingConvention.StdCall)]
public static extern int MH_CreateHook(
IntPtr pTarget,
IntPtr pDetour,
out IntPtr ppOriginal);
[DllImport(DLL, CallingConvention = CallingConvention.StdCall)]
public static extern int MH_RemoveHook(IntPtr pTarget);
[DllImport(DLL, CallingConvention = CallingConvention.StdCall)]
public static extern int MH_EnableHook(IntPtr pTarget);
[DllImport(DLL, CallingConvention = CallingConvention.StdCall)]
public static extern int MH_DisableHook(IntPtr pTarget);
/// <summary>Enable/disable all hooks at once.</summary>
public static readonly IntPtr MH_ALL_HOOKS = IntPtr.Zero;
// ─── Status to string ─────────────────────────────────────────────
[DllImport(DLL, CallingConvention = CallingConvention.StdCall)]
private static extern IntPtr MH_StatusToString(int status);
public static string StatusString(int status)
{
IntPtr ptr = MH_StatusToString(status);
return ptr != IntPtr.Zero
? Marshal.PtrToStringAnsi(ptr) ?? $"Unknown({status})"
: $"Unknown({status})";
}
/// <summary>
/// Race-safe hook install for <c>[UnmanagedCallersOnly]</c> detours that store the
/// original as an <c>IntPtr</c> field.
///
/// Writes <paramref name="original"/> (the trampoline pointer) BEFORE enabling the
/// hook so a detour that fires immediately on the game thread never reads a zero
/// original pointer. A memory barrier separates the write from MH_EnableHook.
/// Throws on failure.
/// </summary>
public static void Hook(IntPtr target, IntPtr detour, out IntPtr original)
{
EnsureInitialized();
// MH_CreateHook writes the trampoline through the ref — the caller's field
// is populated here, before the hook goes live.
int status = CreateHookWithReloadRecovery(target, detour, out original);
if (status != MH_OK)
throw new InvalidOperationException($"MH_CreateHook failed: {StatusString(status)}");
// Full fence: ensure the write above is globally visible before
// MH_EnableHook patches the target instruction.
Thread.MemoryBarrier();
status = MH_EnableHook(target);
if (status != MH_OK)
throw new InvalidOperationException($"MH_EnableHook failed: {StatusString(status)}");
}
/// <summary>
/// Race-safe hook install for delegate-based detours (two-step pattern).
/// Call this first, then build and store the original delegate, add a
/// <c>Thread.MemoryBarrier()</c>, then call <see cref="Enable"/>.
///
/// <code>
/// IntPtr trampoline = MinHook.HookCreate(target, detourPtr);
/// _originalDelegate = Marshal.GetDelegateForFunctionPointer&lt;T&gt;(trampoline);
/// Thread.MemoryBarrier();
/// MinHook.Enable(target);
/// </code>
/// </summary>
public static IntPtr HookCreate(IntPtr target, IntPtr detour)
{
EnsureInitialized();
int status = CreateHookWithReloadRecovery(target, detour, out IntPtr original);
if (status != MH_OK)
throw new InvalidOperationException($"MH_CreateHook failed: {StatusString(status)}");
return original;
}
/// <summary>
/// Wraps <see cref="MH_CreateHook"/> with hot-reload recovery: when the
/// process has been hot-reloaded (gen2 engine init), the previous engine's
/// trampolines for the same target are still in MinHook's pool and a fresh
/// CreateHook returns <see cref="MH_ERROR_ALREADY_CREATED"/>. We disable +
/// remove the stale hook and retry.
///
/// Safety contract: caller (gen2 init) must run AFTER gen1 has gone through
/// EngineLifecycle.Shutdown — which calls MH_DisableHook(MH_ALL_HOOKS) and
/// joins all known engine threads (TickPump, HeartbeatLogger, plugin
/// shutdowns, AvaloniaOverlay.Stop). After that point no live caller is in
/// flight through the dangling trampoline, so MH_RemoveHook is safe.
/// </summary>
private static int CreateHookWithReloadRecovery(IntPtr target, IntPtr detour, out IntPtr original)
{
int status = MH_CreateHook(target, detour, out original);
if (status != MH_ERROR_ALREADY_CREATED)
return status;
// Stale hook from a previous engine generation. Disable (idempotent if
// already disabled), remove (frees the trampoline), then retry.
MH_DisableHook(target);
int rmStatus = MH_RemoveHook(target);
if (rmStatus != MH_OK)
return rmStatus; // surface as failure — caller throws
return MH_CreateHook(target, detour, out original);
}
/// <summary>Enables a hook previously created with <see cref="HookCreate"/>.</summary>
public static void Enable(IntPtr target)
{
int status = MH_EnableHook(target);
if (status != MH_OK)
throw new InvalidOperationException($"MH_EnableHook failed: {StatusString(status)}");
}
private static void EnsureInitialized()
{
int status = MH_Initialize();
if (status != MH_OK && status != MH_ERROR_ALREADY_INITIALIZED)
throw new InvalidOperationException($"MH_Initialize failed: {StatusString(status)}");
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,582 @@
// ============================================================================
// RynthCore.Engine - ImGui/EngineFrameController.cs
// Top-level orchestrator: drives the per-frame engine pipeline from EndScene.
//
// Per-frame work splits into two layers:
// * Always-on (when EndScene fires): GameMatrixCapture, Nav3DRenderInjector
// install/reset, PluginManager init/pending/delete/tick, DX9Backend.RenderNav3D
// fallback. These run regardless of EngineSettings.EnableImGuiBackend so
// world→screen, nav markers, and plugin lifecycle stay alive even when
// the ImGui surface is disabled.
// * ImGui-gated (only when EngineSettings.EnableImGuiBackend is true):
// Win32Backend.NewFrame / DX9Backend.NewFrame, ImGui.NewFrame/EndFrame/
// Render, RynthCoreShell + plugin RenderAll, DX9Backend.RenderDrawData,
// mouse/keyboard capture flag updates, multi-viewport platform pump.
//
// Renamed 2026-05-10 from ImGuiController — the type now owns more than
// ImGui's frame; the ImGui block is just one branch of its work.
// ============================================================================
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using ImGuiNET;
using RynthCore.Engine.D3D9;
using RynthCore.Engine.Plugins;
namespace RynthCore.Engine.ImGuiBackend;
internal static class EngineFrameController
{
[DllImport("kernel32.dll")]
private static extern uint GetCurrentProcessId();
[DllImport("user32.dll")]
private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool IsWindowVisible(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool GetClientRect(IntPtr hWnd, out ClientRect lpRect);
[DllImport("user32.dll")]
private static extern bool ClientToScreen(IntPtr hWnd, ref ClientPoint lpPoint);
[StructLayout(LayoutKind.Sequential)]
private struct ClientRect { public int Left, Top, Right, Bottom; }
[StructLayout(LayoutKind.Sequential)]
private struct ClientPoint { public int X, Y; }
private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
private static bool _imguiInitialized;
private static bool _imguiInitFailed;
private static bool _coreResolved;
private static bool _pluginsInitialized;
private static IntPtr _context;
private static IntPtr _gameHwnd;
/// <summary>
/// Live D3D9 device pointer, published by <see cref="OnEndScene"/> on AC's
/// render thread and consumed by <see cref="PumpPluginFrame"/> on the
/// dedicated plugin pump thread. Zero until the first real backbuffer
/// frame — the pump no-ops until then (we need the HWND/core resolved and
/// a device to hand plugins). Volatile: written by render thread, read by
/// pump thread; IntPtr writes are atomic on this platform.
/// </summary>
internal static volatile IntPtr CachedDevice;
private static int _pluginPumpInFrame; // re-entrancy guard for the pump
private static long _lastFrameTicks;
private static int _frameCount;
/// <summary>
/// Resolves the AC game HWND (via the D3D9 device, falling back to
/// EnumWindows) and seeds <see cref="EntryPoint.GameHwnd"/>. Required by
/// the always-on path (Nav3DRenderInjector + DX9Backend core delegates)
/// and by the ImGui init path. Idempotent — safe to call every frame.
/// </summary>
public static bool EnsureCore(IntPtr pDevice)
{
if (_coreResolved && _gameHwnd != IntPtr.Zero)
return true;
// Prefer the actual D3D device window so startup does not latch onto a splash/loading HWND.
_gameHwnd = DX9Backend.GetDeviceWindow(pDevice);
if (_gameHwnd == IntPtr.Zero)
{
RynthLog.Render("EngineFrameController: D3D device window unavailable, falling back to EnumWindows.");
_gameHwnd = FindGameWindow();
}
if (_gameHwnd == IntPtr.Zero)
{
RynthLog.Render("EngineFrameController: Could not find game window.");
return false;
}
RynthLog.Render($"EngineFrameController: Game HWND = 0x{_gameHwnd:X8}");
EntryPoint.GameHwnd = _gameHwnd;
_coreResolved = true;
return true;
}
public static bool Init(IntPtr pDevice)
{
if (_imguiInitialized)
return true;
if (!EnsureCore(pDevice))
return false;
IntPtr previousContext = ImGuiNET.ImGui.GetCurrentContext();
if (previousContext != IntPtr.Zero)
RynthLog.Render($"EngineFrameController: Existing ImGui context detected (0x{previousContext:X8}) - isolating RynthCore context.");
_context = ImGuiNET.ImGui.CreateContext();
bool initSucceeded = false;
try
{
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($"EngineFrameController: imgui.ini pinned to {iniPath}");
}
catch (Exception ex)
{
RynthLog.Render($"EngineFrameController: failed to pin imgui.ini path - {ex.Message}");
}
io.ConfigFlags |= ImGuiConfigFlags.DockingEnable;
// ViewportsEnable was enabling ImGui multi-viewport platform/renderer
// callbacks against a cimgui.dll that is NOT built with
// IMGUI_ENABLE_VIEWPORTS. The platform/renderer callback chain then
// recursed (Platform → Renderer → Platform → ...) on AC's render
// thread, eating the 1MB stack in ~17s and AV'ing in ntdll mid-push.
// CLAUDE.md flags this: Multi-viewport "requires cimgui built with
// IMGUI_ENABLE_VIEWPORTS" — flag re-introduced this in the engine
// and triggered the silent stack-overflow on every login.
// io.ConfigFlags |= ImGuiConfigFlags.ViewportsEnable;
// Popped-out plugin windows use WS_EX_TOOLWINDOW so they don't show
// up as extra "Asheron's Call" entries in the taskbar — critical for
// users running many clients side by side.
io.ConfigViewportsNoTaskBarIcon = true;
ImGuiNET.ImGui.StyleColorsDark();
// One-shot offset probe for diagnostics — safe to keep installed.
ViewportProbe.Run();
if (!Win32Backend.Init(_gameHwnd))
return false;
if (!DX9Backend.InitImGui(pDevice))
return false;
// Viewport backends only run when ViewportsEnable is on. Installing
// their callbacks on PlatformIO without the flag has no upside and
// just expands the crash surface.
if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) != 0)
{
bool platformOk = ViewportPlatformBackend.Init(_gameHwnd);
bool rendererOk = platformOk && ViewportRendererBackend.Init(pDevice);
if (!platformOk || !rendererOk)
{
RynthLog.Render($"EngineFrameController: viewport init failed (platform={platformOk}, renderer={rendererOk}) — disabling ViewportsEnable.");
io.ConfigFlags &= ~ImGuiConfigFlags.ViewportsEnable;
}
ViewportPlatformBackend.ImGuiContext = _context;
}
_lastFrameTicks = Stopwatch.GetTimestamp();
_imguiInitialized = true;
initSucceeded = true;
RynthLog.Render("EngineFrameController: Fully initialized - RynthCore shell active.");
return true;
}
finally
{
if (!initSucceeded && _context != IntPtr.Zero)
{
ImGuiNET.ImGui.DestroyContext(_context);
_context = IntPtr.Zero;
}
ImGuiNET.ImGui.SetCurrentContext(previousContext);
}
}
public static void Shutdown()
{
if (!_imguiInitialized)
return;
IntPtr previousContext = ImGuiNET.ImGui.GetCurrentContext();
IntPtr contextToDestroy = _context;
try
{
ImGuiNET.ImGui.SetCurrentContext(contextToDestroy);
// Zero the WndProc context guard BEFORE DestroyContext so any
// deferred OS messages that arrive at viewport HWNDs during or
// after teardown don't try to call into freed ImGui memory.
ViewportPlatformBackend.ImGuiContext = IntPtr.Zero;
PluginManager.ShutdownAll();
OverlayTextureRenderer.Shutdown();
ViewportRendererBackend.Shutdown();
ViewportPlatformBackend.Shutdown();
DX9Backend.Shutdown();
// Do NOT call Win32Backend.Shutdown() here. EngineLifecycle.Shutdown
// owns that step explicitly, AFTER AvaloniaOverlay.Stop — floating
// panels are destroyed via RunOnGameThread (a SendMessage handled by
// our subclass WndProc), so restoring AC's original WndProc this
// early makes that SendMessage land on AC's proc, get ignored, and
// "succeed" — DestroyWindow never runs and the orphaned panel HWND
// outlives the engine module with its WndProc pointing at freed code.
ImGuiNET.ImGui.DestroyContext(contextToDestroy);
_imguiInitialized = false;
_coreResolved = false;
_context = IntPtr.Zero;
}
finally
{
ImGuiNET.ImGui.SetCurrentContext(previousContext == contextToDestroy ? IntPtr.Zero : previousContext);
}
}
public static void OnEndScene(IntPtr pDevice)
{
// ── Always-on engine pipeline ────────────────────────────────────
// These run on every EndScene tick, regardless of
// EngineSettings.EnableImGuiBackend, so world→screen capture, nav-
// marker rendering, and plugin lifecycle stay alive when the ImGui
// surface is disabled.
try
{
// Resolve game HWND and seed EntryPoint.GameHwnd. Required even
// in ImGui-off mode so Avalonia owner-window binding works.
EnsureCore(pDevice);
// Cache the D3D9 device function pointers used by Nav3DRenderInjector,
// RenderNav3D, and the always-on render path. This is a strict subset
// of what InitImGui needs and is safe to run without ImGui state.
DX9Backend.InitCore(pDevice);
// Install the DrawIndexedPrimitive hook that injects Nav3D markers at
// the 3D→UI ZENABLE transition so they render BEHIND AC's UI. Idempotent
// (installs once); placed here because its Detour reads the device
// delegates InitCore (above) just cached. WITHOUT THIS the injector never
// accumulates, RenderedThisFrame stays false on every frame, and the
// end-of-frame fallback below paints markers OVER the UI. This call was
// dropped in the v0.19 Nav3D double-buffer refactor — restored here.
D3D9.Nav3DRenderInjector.Install(pDevice);
// Capture the game's View/Projection matrices before ImGui touches them
GameMatrixCapture.CaptureFrame(pDevice);
// Refresh the player-skill snapshot on AC's main thread (this
// EndScene runs on it). The plugin tick is pumped off-thread and
// can't read skills live (TryGetObjectQualitiesPtr fail-closes);
// without this it gets (0,0) → tier-1 casts and never buffs.
// Throttled internally.
Compatibility.ClientObjectHooks.PrefetchPlayerSkills();
// Same rationale + same main-thread guard: snapshot the spellbook
// so the off-thread pump can resolve tiers against spells the char
// actually knows (throttled internally).
Compatibility.ClientObjectHooks.PrefetchKnownSpells();
// Same main-thread guard + rationale: snapshot AC's real
// ObjectIsAttackable for every live object so the off-thread pump
// can tell NPC/vendor (attackable=false) from monster. Without it
// the pump got hardcoded true and the classifier promoted NPCs to
// attackable creatures → war magic cast at NPCs (throttled
// internally).
Compatibility.ClientObjectHooks.PrefetchAttackable();
// Same main-thread guard + rationale: snapshot object names and
// item types for every live object so the off-thread plugin pump
// can classify objects without walking AC's live CObjectMaint
// table (0x0067E779 READ-AV class; throttled internally at 3 s).
Compatibility.ClientObjectHooks.PrefetchObjectIdentity();
// Same main-thread guard: snapshot every live object's POSITION so the
// off-thread plugin pump reads position from cache instead of resolving
// _getWeenieObject live — that resolution is AC's CObjectMaint walk and
// is the dump-verified 0x0067E779 READ-AV when done on the pump thread.
// Sampled every frame (positions are volatile), zero-alloc.
Compatibility.ClientObjectHooks.PrefetchPositions();
// Same main-thread guard: snapshot XP/luminance/deaths/vitae (main-thread-only
// Inq* reads) so the GetEngineStatusJson host bridge can serve them off-thread (throttled).
Compatibility.ClientObjectHooks.PrefetchPlayerStats();
// Cold-login object backfill on the SAME AC main thread as the
// skill prefetch above: deliver objects already present at login
// (the incremental CreateObject hook only catches NEW spawns, so
// login-present mobs were never reaching the plugin — proven via
// per-id ClassifyTrace). One-shot per login, IsOnMainThread-gated
// and attempt-bounded internally; reuses the guarded
// QueueCreateObject delivery path. EndScene is a build-independent
// anchor (D3D9 hook, not string-resolved like SmartBox).
try { Plugins.PluginManager.TrySeedLiveObjectsFromCObjectMaintOnce(); }
catch (Exception ex) { RynthLog.Plugin($"CObjectMaint seed threw {ex.GetType().Name}: {ex.Message}"); }
// P1: drain off-thread bot actions (UseObject / ChangeCombatMode / melee /
// missile / movement / jump) here on AC's MAIN thread. The pump enqueues
// them instead of calling AC directly, so AC mutates its single-threaded
// object/animation (CSequence) state on the same thread that updates it —
// closing the off-thread-mutation corruption class (the CSequence::
// update_internal AV captured 2026-06-03, the 0x0055FA24 range-list AV, etc).
// CastSpell is deliberately NOT routed here (stays off-thread + SEH).
try { Compatibility.AcMainThreadQueue.Drain(); }
catch (Exception ex) { RynthLog.Plugin($"AcMainThreadQueue.Drain threw {ex.GetType().Name}: {ex.Message}"); }
// Nav3DRenderInjector fires mid-frame at the 3D→UI ZENABLE
// transition — that's the only pipeline position where markers
// can render BEHIND AC's UI (the UI pass draws after ZENABLE
// turns off, and the end-of-frame fallback is past it entirely).
//
// The injector accumulates state per-frame via DrawIndexedPrimitive
// callbacks during AC's draws (which fire before this EndScene),
// so by the time we check RenderedThisFrame here, its decision
// for the current frame is final. ResetFrame at the END of
// OnEndScene primes it for the next frame's accumulation.
//
// Historically the engine forced the end-of-frame fallback ONLY
// because the injector's hit-rate varied across motion, producing
// flicker when some frames painted at the 3D→UI boundary and
// others at end-of-frame. We accept that risk here: the user
// wants markers behind the UI, and a frame the injector misses
// simply doesn't render markers (less jarring than a Z-order flip).
bool nav3DAlreadyRendered = D3D9.Nav3DRenderInjector.RenderedThisFrame;
// Publish the live device pointer for the off-render-thread plugin
// pump (see PumpPluginFrame). The D3D9 device is a stable COM
// pointer for the session, so caching it is safe; the pump only
// passes it opaquely to plugins (RynthAi in Avalonia-only mode
// never dereferences it). Atomic IntPtr write; volatile read.
CachedDevice = pDevice;
// NOTE (2026-05-16): PluginManager.InitPlugins / ProcessPendingActions
// / FlushPendingDeletes / TickAll are NO LONGER called here. The
// 2026-05-10 refactor put them on this EndScene reverse-P/Invoke
// (AC's D3D9 render thread); a GC during the plugin tick on that
// AC-owned thread fail-fasts in NativeAOT's
// RhpReversePInvokeAttachOrTrapThread2 (proven from the
// 2026-05-16 09:39 dump). They now run on the dedicated managed
// plugin pump thread (EntryPoint.StartNormalPluginPump →
// PumpPluginFrame), which mirrors the proven DecalCoexistence
// pump. EXACTLY ONE TickAll driver: this render path no longer
// calls it at all.
// ── ImGui-gated work ─────────────────────────────────────────
if (Plugins.EngineSettings.EnableImGuiBackend)
RunImGuiFrame(pDevice);
// Fallback render — only fires when the injector missed this
// frame's 3D→UI transition. _coreInitialized is enough — this
// does not touch font / vertex buffer state.
if (!nav3DAlreadyRendered)
DX9Backend.RenderNav3D(pDevice);
// Custom D3D9 vital HUD (Health/Stamina/Mana). Always-on (independent
// of EnableImGuiBackend) so it shows even in Avalonia-only mode; drawn
// last so it sits on top of the world + AC UI. Reads the vitals
// snapshot maintained on this same (AC main) thread and does its own
// device state save/restore. No-op until vitals are seeded.
if (Plugins.EngineSettings.DrawCustomVitalBars)
D3D9.VitalHud.Draw(pDevice);
}
catch (Exception ex)
{
RynthLog.Info($"EngineFrameController: frame {_frameCount} engine error: {ex.GetType().Name}: {ex.Message}");
}
finally
{
// Prime the injector for the next frame's DIP accumulation.
// Without this, _markersRenderedThisFrame latches true after
// the first 3D→UI transition in the session and the injector
// never fires again — every subsequent frame falls back to the
// end-of-frame draw (which paints over the UI).
D3D9.Nav3DRenderInjector.ResetFrame();
}
}
/// <summary>
/// The plugin lifecycle/tick work that used to run inline in
/// <see cref="OnEndScene"/>. Driven by the dedicated managed plugin pump
/// thread (EntryPoint.StartNormalPluginPump) — NOT AC's render thread —
/// so a GC during the plugin tick can't fail-fast NativeAOT's reverse-
/// P/Invoke transition on an AC-owned thread (the 2026-05-16 root cause).
///
/// No-ops until the render path has resolved the game HWND and published
/// a device (CachedDevice != 0). Single-threaded by contract: only the
/// one pump thread calls this; the render path no longer touches
/// PluginManager at all, so there is exactly one TickAll driver. The
/// re-entrancy guard is belt-and-braces against an accidental second
/// caller.
/// </summary>
public static void PumpPluginFrame()
{
IntPtr device = CachedDevice;
if (device == IntPtr.Zero || _gameHwnd == IntPtr.Zero)
return; // render path hasn't established core state yet
if (System.Threading.Interlocked.Exchange(ref _pluginPumpInFrame, 1) != 0)
return; // never re-enter PluginManager from two stacks
try
{
if (!_pluginsInitialized)
{
_pluginsInitialized = true;
PluginManager.InitPlugins(_context, device, _gameHwnd);
}
PluginManager.ProcessPendingActions(_context, device, _gameHwnd);
PluginManager.FlushPendingDeletes(); // closes the create→delete race window
PluginManager.TickAll();
}
catch (Exception ex)
{
RynthLog.Plugin($"EngineFrameController.PumpPluginFrame: {ex.GetType().Name}: {ex.Message}");
}
finally
{
System.Threading.Interlocked.Exchange(ref _pluginPumpInFrame, 0);
}
}
/// <summary>
/// Runs the ImGui-specific portion of the per-frame pipeline:
/// backend NewFrame plumbing, ImGui frame open/close, RynthCore shell +
/// plugin RenderAll, draw-data submission, capture flag update, and the
/// multi-viewport platform pump. Bypassed entirely when
/// EngineSettings.EnableImGuiBackend is false.
/// </summary>
private static void RunImGuiFrame(IntPtr pDevice)
{
if (_imguiInitFailed) return;
if (!_imguiInitialized)
{
if (!Init(pDevice))
{
_imguiInitFailed = true;
return;
}
}
IntPtr previousContext = ImGuiNET.ImGui.GetCurrentContext();
ImGuiNET.ImGui.SetCurrentContext(_context);
bool frameStarted = false;
bool frameEnded = false;
try
{
_frameCount++;
DX9Backend.NewFrame();
Win32Backend.NewFrame();
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
// Fallback: if Win32Backend could not determine display size, read from the D3D9 viewport.
if (io.DisplaySize.X <= 1 || io.DisplaySize.Y <= 1)
{
DX9Backend.GetViewportSize(pDevice, out int vpW, out int vpH);
if (vpW > 1 && vpH > 1)
io.DisplaySize = new System.Numerics.Vector2(vpW, vpH);
}
long now = Stopwatch.GetTimestamp();
float dt = (float)(now - _lastFrameTicks) / Stopwatch.Frequency;
_lastFrameTicks = now;
io.DeltaTime = dt > 0f ? dt : 1f / 60f;
// With ViewportsEnable on, ImGui routes mouse and window positions in
// absolute screen coords. The main viewport's Pos must equal the game
// client's screen origin so clicks over the main viewport map to the
// correct windows, and popped-out viewports share a coord system with
// the main one.
if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) != 0)
{
int screenX = 0, screenY = 0;
if (_gameHwnd != IntPtr.Zero)
{
ClientPoint p = new ClientPoint { X = 0, Y = 0 };
if (ClientToScreen(_gameHwnd, ref p)) { screenX = p.X; screenY = p.Y; }
}
ImGuiViewportPtr mainVp = ImGuiNET.ImGui.GetMainViewport();
mainVp.Pos = new System.Numerics.Vector2(screenX, screenY);
mainVp.Size = io.DisplaySize;
mainVp.WorkPos = new System.Numerics.Vector2(screenX, screenY);
mainVp.WorkSize = io.DisplaySize;
}
ImGuiNET.ImGui.NewFrame();
frameStarted = true;
// EnableImGuiShell gates the in-AC ImGui surface as a whole: both the
// RynthCore overlay bar and any plugin-drawn ImGui windows. Plugins
// still load, init, and tick when this is off — they just don't
// draw, so Avalonia panels can drive them via the plugin's C exports.
if (Plugins.EngineSettings.EnableImGuiShell)
{
RynthCoreShell.Render(_frameCount);
PluginManager.RenderAll();
}
bool captureMouse =
ImGuiNET.ImGui.IsWindowHovered(ImGuiHoveredFlags.AnyWindow) ||
ImGuiNET.ImGui.IsAnyItemActive();
bool captureKeyboard = ImGuiNET.ImGui.IsAnyItemActive();
ImGuiNET.ImGui.EndFrame();
frameEnded = true;
ImGuiNET.ImGui.Render();
Win32Backend.UpdateCaptureFlags(captureMouse, captureKeyboard);
ImDrawDataPtr drawData = ImGuiNET.ImGui.GetDrawData();
DX9Backend.RenderDrawData(drawData, pDevice);
// OverlayTextureRenderer.Render is now driven from EndSceneHook.EndSceneDetour
// directly so the Avalonia compositor runs even when EnableImGuiBackend=false.
// Leaving it out of this call site avoids double-blit when ImGui is also active.
if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) != 0)
{
ImGuiNET.ImGui.UpdatePlatformWindows();
ImGuiNET.ImGui.RenderPlatformWindowsDefault();
}
}
catch (Exception ex)
{
try
{
// Keep Dear ImGui's frame state balanced so the next frame does not assert.
if (frameStarted && !frameEnded && ImGuiNET.ImGui.GetCurrentContext() == _context)
ImGuiNET.ImGui.EndFrame();
}
catch
{
}
RynthLog.Info($"EngineFrameController: frame {_frameCount} ImGui error: {ex.GetType().Name}: {ex.Message}");
}
finally
{
ImGuiNET.ImGui.SetCurrentContext(previousContext);
}
}
internal static IntPtr FindGameWindow()
{
uint pid = GetCurrentProcessId();
IntPtr found = IntPtr.Zero;
EnumWindows((hWnd, _) =>
{
GetWindowThreadProcessId(hWnd, out uint windowPid);
if (windowPid == pid && IsWindowVisible(hWnd))
{
found = hWnd;
return false;
}
return true;
}, IntPtr.Zero);
return found;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,53 @@
// ═══════════════════════════════════════════════════════════════════════════
// RynthCore.Engine — ImGui/ViewportOffsets.cs
// Byte offsets of ImGuiPlatformIO callback fields in the cimgui.dll shipped
// with ImGui.NET 1.91.6.1 (docking branch).
//
// WARNING: these do NOT match ImGui.NET's compiled struct layout. ImGui.NET
// prepends 36 bytes of clipboard/IME/OpenInShell fields that this cimgui.dll
// build does not have. Writing via ImGui.NET's ref properties lands 36 bytes
// past the native field, so the native library sees NULL and asserts
// "Platform init didn't install handlers".
//
// Source of truth (disassembled cimgui.dll 1.91.6.1, x86):
// ImGuiPlatformIO_Set_Platform_GetWindowPos → mov [pio+0x10], shim
// ImGuiPlatformIO_Set_Platform_GetWindowSize → mov [pio+0x18], shim
// igUpdatePlatformWindows first callback dispatch → call [g+0x37B8]
// with ImGuiContext PlatformIO offset → pio field 0 = Platform_CreateWindow
//
// Struct size (from constructor memset): 0x74 (116 bytes). Fields 0x00..0x5F
// hold 24 callback pointers; 0x60..0x73 hold Monitors + Viewports ImVectors.
// ═══════════════════════════════════════════════════════════════════════════
namespace RynthCore.Engine.ImGuiBackend;
internal static class ViewportOffsets
{
// Platform_* (18 callbacks — this cimgui.dll build lacks GetWindowWorkAreaInsets)
public const int PlatformCreateWindow = 0;
public const int PlatformDestroyWindow = 4;
public const int PlatformShowWindow = 8;
public const int PlatformSetWindowPos = 12;
public const int PlatformGetWindowPos = 16; // confirmed via _Set_ helper disasm
public const int PlatformSetWindowSize = 20;
public const int PlatformGetWindowSize = 24; // confirmed via _Set_ helper disasm
public const int PlatformSetWindowFocus = 28;
public const int PlatformGetWindowFocus = 32;
public const int PlatformGetWindowMinimized = 36;
public const int PlatformSetWindowTitle = 40;
public const int PlatformSetWindowAlpha = 44;
public const int PlatformUpdateWindow = 48;
public const int PlatformRenderWindow = 52;
public const int PlatformSwapBuffers = 56;
public const int PlatformGetWindowDpiScale = 60;
public const int PlatformOnChangedViewport = 64;
public const int PlatformCreateVkSurface = 68;
// Renderer_* (5 callbacks) — RendererCreateWindow at +72 confirmed by
// igUpdatePlatformWindows disasm: [ebx+0x3800] = [pio + 0x48] = +72.
public const int RendererCreateWindow = 72;
public const int RendererDestroyWindow = 76;
public const int RendererSetWindowSize = 80;
public const int RendererRenderWindow = 84;
public const int RendererSwapBuffers = 88;
}

View file

@ -0,0 +1,829 @@
// ═══════════════════════════════════════════════════════════════════════════
// RynthCore.Engine — ImGui/ViewportPlatformBackend.cs
// Win32 platform backend for Dear ImGui multi-viewport (equivalent of
// imgui_impl_win32's viewport-capable portion). Installs Platform_* callbacks
// into the native ImGuiPlatformIO struct, registers a window class for
// popped-out ImGui windows, and proxies the required Win32 calls.
//
// Input for viewport HWNDs is forwarded into the existing Dear ImGui IO
// event queue via a dedicated WndProc.
// ═══════════════════════════════════════════════════════════════════════════
using System;
using System.Collections.Generic;
using System.Numerics;
using System.Runtime.InteropServices;
using ImGuiNET;
namespace RynthCore.Engine.ImGuiBackend;
internal static unsafe class ViewportPlatformBackend
{
// ── Delegate types (cdecl; ImGui callbacks on x86 use the default C ABI) ──
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void ViewportVoidDelegate(ImGuiViewport* vp);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void ViewportGetVec2Delegate(ImGuiViewport* vp, Vector2* outVec);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void ViewportSetVec2Delegate(ImGuiViewport* vp, Vector2 value);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate byte ViewportGetBoolDelegate(ImGuiViewport* vp);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void ViewportSetStringDelegate(ImGuiViewport* vp, IntPtr str);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void ViewportSetFloatDelegate(ImGuiViewport* vp, float value);
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern ushort RegisterClassExW(ref WNDCLASSEXW lpwcx);
[DllImport("user32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr CreateWindowExW(
uint dwExStyle, string lpClassName, string lpWindowName, uint dwStyle,
int X, int Y, int nWidth, int nHeight,
IntPtr hWndParent, IntPtr hMenu, IntPtr hInstance, IntPtr lpParam);
[DllImport("user32.dll")]
private static extern bool DestroyWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
[DllImport("user32.dll")]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter,
int X, int Y, int cx, int cy, uint uFlags);
[DllImport("user32.dll")]
private static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect);
[DllImport("user32.dll")]
private static extern bool GetClientRect(IntPtr hWnd, out RECT lpRect);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern int SetWindowTextW(IntPtr hWnd, string lpString);
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
private static extern bool IsIconic(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern IntPtr SetWindowLongW(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
[DllImport("user32.dll")]
private static extern IntPtr GetWindowLongW(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
private static extern bool SetLayeredWindowAttributes(IntPtr hWnd, uint crKey, byte bAlpha, uint dwFlags);
[DllImport("user32.dll")]
private static extern IntPtr DefWindowProcW(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
private static extern bool AdjustWindowRectEx(ref RECT lpRect, uint dwStyle, bool bMenu, uint dwExStyle);
[DllImport("user32.dll")]
private static extern bool PostMessageW(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
private static extern bool ClientToScreen(IntPtr hWnd, ref POINT lpPoint);
[DllImport("user32.dll")]
private static extern IntPtr SetCapture(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern bool ReleaseCapture();
[StructLayout(LayoutKind.Sequential)]
private struct POINT { public int X, Y; }
[DllImport("kernel32.dll")]
private static extern IntPtr GetModuleHandleW(string? lpModuleName);
[DllImport("user32.dll")]
private static extern IntPtr LoadCursorW(IntPtr hInstance, IntPtr lpCursorName);
[DllImport("user32.dll")]
private static extern int GetSystemMetrics(int nIndex);
[DllImport("user32.dll")]
private static extern bool EnumDisplayMonitors(IntPtr hdc, IntPtr lprcClip, MonitorEnumProc lpfnEnum, IntPtr dwData);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern bool GetMonitorInfoW(IntPtr hMonitor, ref MONITORINFO lpmi);
private delegate bool MonitorEnumProc(IntPtr hMonitor, IntPtr hdcMonitor, ref RECT lprcMonitor, IntPtr dwData);
[StructLayout(LayoutKind.Sequential)]
private struct MONITORINFO
{
public uint cbSize;
public RECT rcMonitor;
public RECT rcWork;
public uint dwFlags;
}
private const int SM_CXSCREEN = 0;
private const int SM_CYSCREEN = 1;
private const uint MONITORINFOF_PRIMARY = 0x00000001;
// ImGuiPlatformIO Monitors ImVector (native cimgui.dll layout).
// Native has 18 Platform_* + 5 Renderer_* = 23 callback pointers = 92 bytes,
// then Monitors ImVector{ int Size; int Capacity; void* Data; } at +92..+103,
// then Viewports ImVector at +104..+115. (ImGui.NET's compiled layout adds
// GetWindowWorkAreaInsets and so puts Monitors at +96 — do NOT use that.)
// Confirmed by probe dump showing Viewports.Size=1, Cap=8, Data=ptr at
// +104..+115 when native had just seeded the main viewport.
private const int MonitorsSize = 92;
private const int MonitorsCapacity = 96;
private const int MonitorsData = 100;
// ImGuiPlatformMonitor is 40 bytes (confirmed by cimgui.dll ctor "push 28h"):
// +0 MainPos (ImVec2, 8)
// +8 MainSize (ImVec2, 8)
// +16 WorkPos (ImVec2, 8)
// +24 WorkSize (ImVec2, 8)
// +32 DpiScale (float, 4)
// +36 PlatformHandle (void*, 4)
private const int MonitorStructSize = 40;
private static IntPtr _monitorArrayPtr;
private static int _monitorCount;
private delegate IntPtr WndProcDelegate(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private 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;
[MarshalAs(UnmanagedType.LPWStr)] public string? lpszMenuName;
[MarshalAs(UnmanagedType.LPWStr)] public string? lpszClassName;
public IntPtr hIconSm;
}
[StructLayout(LayoutKind.Sequential)]
private struct RECT { public int Left, Top, Right, Bottom; }
// Win32 constants
private const int GWL_STYLE = -16;
private const int GWL_EXSTYLE = -20;
private const int SW_SHOWNA = 8;
private const int SW_HIDE = 0;
private const uint SWP_NOMOVE = 0x0002;
private const uint SWP_NOSIZE = 0x0001;
private const uint SWP_NOZORDER = 0x0004;
private const uint SWP_NOACTIVATE = 0x0010;
private const uint WS_POPUP = 0x80000000;
private const uint WS_OVERLAPPEDWINDOW = 0x00CF0000;
private const uint WS_CLIPCHILDREN = 0x02000000;
private const uint WS_CLIPSIBLINGS = 0x04000000;
private const uint WS_EX_TOOLWINDOW = 0x00000080;
private const uint WS_EX_LAYERED = 0x00080000;
private const uint WS_EX_APPWINDOW = 0x00040000;
private const uint WS_EX_TOPMOST = 0x00000008;
private const uint WS_EX_NOACTIVATE = 0x08000000;
private const uint LWA_ALPHA = 0x00000002;
private const uint WM_CLOSE = 0x0010;
private const uint WM_MOVE = 0x0003;
private const uint WM_SIZE = 0x0005;
private const uint WM_MOUSEACTIVATE = 0x0021;
private const uint WM_NCHITTEST = 0x0084;
private const uint WM_MOUSEMOVE = 0x0200;
private const uint WM_LBUTTONDOWN = 0x0201;
private const uint WM_LBUTTONUP = 0x0202;
private const uint WM_LBUTTONDBLCLK = 0x0203;
private const uint WM_RBUTTONDOWN = 0x0204;
private const uint WM_RBUTTONUP = 0x0205;
private const uint WM_RBUTTONDBLCLK = 0x0206;
private const uint WM_MBUTTONDOWN = 0x0207;
private const uint WM_MBUTTONUP = 0x0208;
private const uint WM_MBUTTONDBLCLK = 0x0209;
private const uint WM_MOUSEWHEEL = 0x020A;
private const uint WM_XBUTTONDOWN = 0x020B;
private const uint WM_XBUTTONUP = 0x020C;
private const uint WM_MOUSEHWHEEL = 0x020E;
private const uint WM_KEYDOWN = 0x0100;
private const uint WM_KEYUP = 0x0101;
private const uint WM_CHAR = 0x0102;
private const uint WM_SYSKEYDOWN = 0x0104;
private const uint WM_SYSKEYUP = 0x0105;
private const int MA_NOACTIVATE = 3;
private const int HTCLIENT = 1;
private const IntPtr IDC_ARROW = 0x7F00; // MAKEINTRESOURCE(32512)
private const string WindowClassName = "RynthCoreImGuiViewport";
// Pinned delegate instances — prevent GC while ImGui holds function pointers.
private static readonly List<Delegate> _delegateRoots = new();
private static WndProcDelegate? _viewportWndProc;
private static IntPtr _viewportWndProcPtr;
private static bool _initialized;
private static bool _classRegistered;
private static IntPtr _hInstance;
private static IntPtr _mainHwnd;
// Per-viewport state kept on the managed side.
// Keyed by the native ImGuiViewport* pointer.
private static readonly Dictionary<IntPtr, ViewportState> _viewports = new();
private class ViewportState
{
public IntPtr Hwnd;
public bool HwndOwned;
public uint DwStyle;
public uint DwExStyle;
}
public static bool Init(IntPtr mainHwnd)
{
if (_initialized) return true;
_mainHwnd = mainHwnd;
_hInstance = GetModuleHandleW(null);
if (!EnsureWindowClassRegistered())
{
RynthLog.Info($"ViewportPlatform: RegisterClassEx failed (err {Marshal.GetLastWin32Error()})");
return false;
}
ImGuiPlatformIOPtr pio = ImGuiNET.ImGui.GetPlatformIO();
InstallCallbacks(pio);
PopulateMonitors(pio);
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
io.BackendFlags |= ImGuiBackendFlags.PlatformHasViewports;
// Do NOT set HasMouseHoveredViewport: that flag tells ImGui the backend
// will route hovered-viewport info via AddMouseViewportEvent each frame.
// We don't call that, so setting the flag causes mouse input to drop on
// the floor (IsWindowHovered returns false for every window).
// The main viewport's PlatformHandle points to the game window; store it
// so the very first frame doesn't try to create a new HWND for viewport 0.
ImGuiViewportPtr mainViewport = ImGuiNET.ImGui.GetMainViewport();
mainViewport.PlatformHandle = _mainHwnd;
mainViewport.PlatformHandleRaw = _mainHwnd;
_viewports[(IntPtr)mainViewport.NativePtr] = new ViewportState
{
Hwnd = _mainHwnd,
HwndOwned = false,
DwStyle = unchecked((uint)(long)GetWindowLongW(_mainHwnd, GWL_STYLE)),
DwExStyle = unchecked((uint)(long)GetWindowLongW(_mainHwnd, GWL_EXSTYLE)),
};
_initialized = true;
RynthLog.Info("ViewportPlatform: initialized.");
return true;
}
public static void Shutdown()
{
if (!_initialized) return;
// Destroy any viewport windows we created.
foreach (var kv in _viewports)
{
if (kv.Value.HwndOwned && kv.Value.Hwnd != IntPtr.Zero)
DestroyWindow(kv.Value.Hwnd);
}
_viewports.Clear();
// Clear the Monitors ImVector pointer in PlatformIO before freeing our
// backing buffer — native ImGui otherwise keeps a stale Data pointer.
if (_monitorArrayPtr != IntPtr.Zero)
{
try
{
ImGuiPlatformIOPtr pio = ImGuiNET.ImGui.GetPlatformIO();
IntPtr pioNative = (IntPtr)pio.NativePtr;
Marshal.WriteInt32(pioNative, MonitorsSize, 0);
Marshal.WriteInt32(pioNative, MonitorsCapacity, 0);
Marshal.WriteIntPtr(pioNative, MonitorsData, IntPtr.Zero);
}
catch { /* context may already be torn down */ }
Marshal.FreeHGlobal(_monitorArrayPtr);
_monitorArrayPtr = IntPtr.Zero;
_monitorCount = 0;
}
_initialized = false;
}
// Dear ImGui asserts Monitor.Size > 0 before the first UpdatePlatformWindows
// call when ViewportsEnable is on. Populate the Monitors ImVector with the
// primary (and any secondary) displays so windows can pop out correctly.
private static void PopulateMonitors(ImGuiPlatformIOPtr pio)
{
var rects = new List<(RECT mon, RECT work, bool primary)>();
MonitorEnumProc cb = (IntPtr hMon, IntPtr hdc, ref RECT r, IntPtr _) =>
{
MONITORINFO mi = default;
mi.cbSize = (uint)Marshal.SizeOf<MONITORINFO>();
if (GetMonitorInfoW(hMon, ref mi))
rects.Add((mi.rcMonitor, mi.rcWork, (mi.dwFlags & MONITORINFOF_PRIMARY) != 0));
return true;
};
if (!EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, cb, IntPtr.Zero) || rects.Count == 0)
{
// Fallback: single primary display via GetSystemMetrics.
int w = GetSystemMetrics(SM_CXSCREEN);
int h = GetSystemMetrics(SM_CYSCREEN);
RECT r = new RECT { Left = 0, Top = 0, Right = w > 0 ? w : 1920, Bottom = h > 0 ? h : 1080 };
rects.Add((r, r, true));
}
GC.KeepAlive(cb);
_monitorCount = rects.Count;
_monitorArrayPtr = Marshal.AllocHGlobal(_monitorCount * MonitorStructSize);
// Primary monitor must be at index 0 for Dear ImGui's viewport code.
rects.Sort((a, b) => (b.primary ? 1 : 0) - (a.primary ? 1 : 0));
for (int i = 0; i < _monitorCount; i++)
{
var (mon, work, _) = rects[i];
IntPtr mp = _monitorArrayPtr + i * MonitorStructSize;
WriteFloat(mp, 0, mon.Left);
WriteFloat(mp, 4, mon.Top);
WriteFloat(mp, 8, mon.Right - mon.Left);
WriteFloat(mp, 12, mon.Bottom - mon.Top);
WriteFloat(mp, 16, work.Left);
WriteFloat(mp, 20, work.Top);
WriteFloat(mp, 24, work.Right - work.Left);
WriteFloat(mp, 28, work.Bottom - work.Top);
WriteFloat(mp, 32, 1.0f);
Marshal.WriteIntPtr(mp, 36, IntPtr.Zero);
}
IntPtr pioNative = (IntPtr)pio.NativePtr;
Marshal.WriteInt32(pioNative, MonitorsSize, _monitorCount);
Marshal.WriteInt32(pioNative, MonitorsCapacity, _monitorCount);
Marshal.WriteIntPtr(pioNative, MonitorsData, _monitorArrayPtr);
RynthLog.Info($"ViewportPlatform: populated {_monitorCount} monitor(s) at 0x{_monitorArrayPtr.ToInt64():X8}");
}
private static bool EnsureWindowClassRegistered()
{
if (_classRegistered) return true;
_viewportWndProc = ViewportWndProc;
_viewportWndProcPtr = Marshal.GetFunctionPointerForDelegate(_viewportWndProc);
WNDCLASSEXW wc = default;
wc.cbSize = (uint)Marshal.SizeOf<WNDCLASSEXW>();
wc.style = 0x0020 /*CS_OWNDC*/ | 0x0002 /*CS_HREDRAW*/ | 0x0001 /*CS_VREDRAW*/;
wc.lpfnWndProc = _viewportWndProcPtr;
wc.hInstance = _hInstance;
wc.hCursor = LoadCursorW(IntPtr.Zero, IDC_ARROW);
wc.hbrBackground = IntPtr.Zero;
wc.lpszClassName = WindowClassName;
ushort atom = RegisterClassExW(ref wc);
if (atom == 0)
{
int err = Marshal.GetLastWin32Error();
// 1410 = ERROR_CLASS_ALREADY_EXISTS; fine if we were re-initialized.
if (err != 1410) return false;
}
_classRegistered = true;
return true;
}
// ─── Callback installation ────────────────────────────────────────────
private static void InstallCallbacks(ImGuiPlatformIOPtr pio)
{
IntPtr pioNative = (IntPtr)pio.NativePtr;
IntPtr createPtr = RootAndGetPointer<ViewportVoidDelegate>(ViewportCreate);
IntPtr destroyPtr = RootAndGetPointer<ViewportVoidDelegate>(ViewportDestroy);
IntPtr showPtr = RootAndGetPointer<ViewportVoidDelegate>(ViewportShow);
IntPtr setPosPtr = RootAndGetPointer<ViewportSetVec2Delegate>(ViewportSetPos);
IntPtr setSizePtr = RootAndGetPointer<ViewportSetVec2Delegate>(ViewportSetSize);
IntPtr setFocusPtr = RootAndGetPointer<ViewportVoidDelegate>(ViewportSetFocus);
IntPtr getFocusPtr = RootAndGetPointer<ViewportGetBoolDelegate>(ViewportGetFocus);
IntPtr getMinPtr = RootAndGetPointer<ViewportGetBoolDelegate>(ViewportGetMinimized);
IntPtr setTitlePtr = RootAndGetPointer<ViewportSetStringDelegate>(ViewportSetTitle);
IntPtr setAlphaPtr = RootAndGetPointer<ViewportSetFloatDelegate>(ViewportSetAlpha);
IntPtr updatePtr = RootAndGetPointer<ViewportVoidDelegate>(ViewportUpdate);
// Direct writes at native cimgui.dll offsets (NOT ImGui.NET's compiled
// layout offsets — those are off by 36 bytes). Void-return and
// small-return callbacks match the cdecl ABI naturally.
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformCreateWindow, createPtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformDestroyWindow, destroyPtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformShowWindow, showPtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformSetWindowPos, setPosPtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformSetWindowSize, setSizePtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformSetWindowFocus, setFocusPtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformGetWindowFocus, getFocusPtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformGetWindowMinimized, getMinPtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformSetWindowTitle, setTitlePtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformSetWindowAlpha, setAlphaPtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.PlatformUpdateWindow, updatePtr);
// GetWindowPos / GetWindowSize return ImVec2 by value (x86 cdecl struct
// return — hidden first arg on stack). Our C# delegates take an out-ptr
// instead; cimgui ships a wrapper helper that adapts the ABI and writes
// the wrapper at the right offset for us. Must install via helper, not
// Marshal.WriteIntPtr, or native crashes on the first call.
IntPtr getPosPtr = RootAndGetPointer<ViewportGetVec2Delegate>(ViewportGetPos);
IntPtr getSizePtr = RootAndGetPointer<ViewportGetVec2Delegate>(ViewportGetSize);
ImGuiNative.ImGuiPlatformIO_Set_Platform_GetWindowPos(pio.NativePtr, getPosPtr);
ImGuiNative.ImGuiPlatformIO_Set_Platform_GetWindowSize(pio.NativePtr, getSizePtr);
// Read back and log so a silent mismatch surfaces as a log line, not an IM_ASSERT.
IntPtr verifyCreate = Marshal.ReadIntPtr(pioNative, ViewportOffsets.PlatformCreateWindow);
IntPtr verifyGetPos = Marshal.ReadIntPtr(pioNative, ViewportOffsets.PlatformGetWindowPos);
RynthLog.Info($"ViewportPlatform: installed handlers (CreateWindow readback=0x{verifyCreate.ToInt64():X8}, expected=0x{createPtr.ToInt64():X8}, GetWindowPos shim=0x{verifyGetPos.ToInt64():X8})");
}
private static IntPtr RootAndGetPointer<TDelegate>(TDelegate del) where TDelegate : Delegate
{
_delegateRoots.Add(del);
return Marshal.GetFunctionPointerForDelegate<TDelegate>(del);
}
private static void WriteFloat(IntPtr basePtr, int offset, float value)
{
Marshal.WriteInt32(basePtr, offset, BitConverter.SingleToInt32Bits(value));
}
// ─── Callback implementations ─────────────────────────────────────────
private static void ViewportCreate(ImGuiViewport* vp)
{
uint flags = unchecked((uint)vp->Flags);
bool noDecoration = (flags & (uint)ImGuiViewportFlags.NoDecoration) != 0;
bool topMost = (flags & (uint)ImGuiViewportFlags.TopMost) != 0;
uint dwStyle = noDecoration
? WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS
: WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS;
// 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;
// Compute outer window rect that yields the requested client size.
RECT rect;
rect.Left = (int)vp->Pos.X;
rect.Top = (int)vp->Pos.Y;
rect.Right = rect.Left + (int)vp->Size.X;
rect.Bottom = rect.Top + (int)vp->Size.Y;
AdjustWindowRectEx(ref rect, dwStyle, false, dwExStyle);
IntPtr hwnd = CreateWindowExW(
dwExStyle, WindowClassName, "RynthCore Viewport", dwStyle,
rect.Left, rect.Top, rect.Right - rect.Left, rect.Bottom - rect.Top,
_mainHwnd, IntPtr.Zero, _hInstance, IntPtr.Zero);
if (hwnd == IntPtr.Zero)
{
RynthLog.Info($"ViewportPlatform: CreateWindowEx failed (err {Marshal.GetLastWin32Error()})");
return;
}
var state = new ViewportState { Hwnd = hwnd, HwndOwned = true, DwStyle = dwStyle, DwExStyle = dwExStyle };
_viewports[(IntPtr)vp] = state;
vp->PlatformHandle = (void*)hwnd;
vp->PlatformHandleRaw = (void*)hwnd;
}
private static void ViewportDestroy(ImGuiViewport* vp)
{
IntPtr key = (IntPtr)vp;
if (_viewports.TryGetValue(key, out var state))
{
if (state.HwndOwned && state.Hwnd != IntPtr.Zero)
DestroyWindow(state.Hwnd);
_viewports.Remove(key);
}
vp->PlatformHandle = (void*)IntPtr.Zero;
vp->PlatformHandleRaw = (void*)IntPtr.Zero;
}
private static void ViewportShow(ImGuiViewport* vp)
{
if (!TryGetState(vp, out var state)) return;
ShowWindow(state.Hwnd, SW_SHOWNA);
}
private static void ViewportSetPos(ImGuiViewport* vp, Vector2 pos)
{
if (!TryGetState(vp, out var state)) return;
RECT rect;
rect.Left = (int)pos.X;
rect.Top = (int)pos.Y;
rect.Right = rect.Left;
rect.Bottom = rect.Top;
AdjustWindowRectEx(ref rect, state.DwStyle, false, state.DwExStyle);
SetWindowPos(state.Hwnd, IntPtr.Zero, rect.Left, rect.Top, 0, 0,
SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
}
private static void ViewportSetSize(ImGuiViewport* vp, Vector2 size)
{
if (!TryGetState(vp, out var state)) return;
RECT rect;
rect.Left = 0; rect.Top = 0;
rect.Right = (int)size.X;
rect.Bottom = (int)size.Y;
AdjustWindowRectEx(ref rect, state.DwStyle, false, state.DwExStyle);
SetWindowPos(state.Hwnd, IntPtr.Zero, 0, 0,
rect.Right - rect.Left, rect.Bottom - rect.Top,
SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
}
private static void ViewportGetPos(ImGuiViewport* vp, Vector2* outPos)
{
*outPos = new Vector2(0, 0);
if (!TryGetState(vp, out var state)) return;
// Return the CLIENT-area origin in screen coords, not the outer window
// rect. ImGui's hit-testing uses this as the viewport origin; if we
// include the title-bar height, every click misses by that offset.
POINT p = new POINT { X = 0, Y = 0 };
if (!ClientToScreen(state.Hwnd, ref p)) return;
*outPos = new Vector2(p.X, p.Y);
}
private static void ViewportGetSize(ImGuiViewport* vp, Vector2* outSize)
{
*outSize = new Vector2(0, 0);
if (!TryGetState(vp, out var state)) return;
if (!GetClientRect(state.Hwnd, out RECT r)) return;
*outSize = new Vector2(r.Right - r.Left, r.Bottom - r.Top);
}
private static void ViewportSetFocus(ImGuiViewport* vp)
{
if (!TryGetState(vp, out var state)) return;
SetForegroundWindow(state.Hwnd);
}
private static byte ViewportGetFocus(ImGuiViewport* vp)
{
if (!TryGetState(vp, out var state)) return 0;
return GetForegroundWindow() == state.Hwnd ? (byte)1 : (byte)0;
}
private static byte ViewportGetMinimized(ImGuiViewport* vp)
{
if (!TryGetState(vp, out var state)) return 0;
return IsIconic(state.Hwnd) ? (byte)1 : (byte)0;
}
private static void ViewportSetTitle(ImGuiViewport* vp, IntPtr strPtr)
{
if (!TryGetState(vp, out var state)) return;
string title = Marshal.PtrToStringUTF8(strPtr) ?? "RynthCore Viewport";
SetWindowTextW(state.Hwnd, title);
}
private static void ViewportSetAlpha(ImGuiViewport* vp, float alpha)
{
if (!TryGetState(vp, out var state)) return;
IntPtr exStyle = GetWindowLongW(state.Hwnd, GWL_EXSTYLE);
long exs = (long)exStyle;
if (alpha < 1.0f)
SetWindowLongW(state.Hwnd, GWL_EXSTYLE, (IntPtr)(exs | WS_EX_LAYERED));
byte a = (byte)Math.Clamp((int)(alpha * 255f + 0.5f), 0, 255);
SetLayeredWindowAttributes(state.Hwnd, 0, a, LWA_ALPHA);
}
private static void ViewportUpdate(ImGuiViewport* vp)
{
// No-op on Win32 — imgui_impl_win32 handles monitor updates and other
// housekeeping elsewhere. We refresh monitors from EngineFrameController.
}
private static bool TryGetState(ImGuiViewport* vp, out ViewportState state)
{
return _viewports.TryGetValue((IntPtr)vp, out state!);
}
// ─── WndProc for viewport HWNDs ───────────────────────────────────────
internal static IntPtr ImGuiContext;
private static IntPtr ViewportWndProc(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam)
{
// If the ImGui context has been torn down (Shutdown already ran), don't
// touch any ImGui API — the context memory is freed and any call into it
// is a use-after-free. Just forward to the default handler.
if (ImGuiContext == IntPtr.Zero)
return DefWindowProcW(hWnd, msg, wParam, lParam);
// OS delivers messages (WM_GETICON, WM_PAINT, etc.) asynchronously outside
// of EndScene. By then our saved context has been restored → GImGui is null,
// and any ImGui call here AVs. Temporarily set our context for the message.
IntPtr saved = ImGuiNET.ImGui.GetCurrentContext();
if (saved != ImGuiContext)
ImGuiNET.ImGui.SetCurrentContext(ImGuiContext);
try
{
ImGuiViewportPtr vp = ImGuiNET.ImGui.FindViewportByPlatformHandle(hWnd);
if (vp.NativePtr == null)
return DefWindowProcW(hWnd, msg, wParam, lParam);
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
// ── Mouse position: forward in screen coords (multi-viewport) ────
if (msg == WM_MOUSEMOVE || msg == WM_LBUTTONDOWN || msg == WM_LBUTTONUP
|| msg == WM_LBUTTONDBLCLK || msg == WM_RBUTTONDOWN || msg == WM_RBUTTONUP
|| msg == WM_RBUTTONDBLCLK || msg == WM_MBUTTONDOWN || msg == WM_MBUTTONUP
|| msg == WM_MBUTTONDBLCLK || msg == WM_XBUTTONDOWN || msg == WM_XBUTTONUP)
{
short cx = (short)((long)lParam & 0xFFFF);
short cy = (short)(((long)lParam >> 16) & 0xFFFF);
POINT pt = new POINT { X = cx, Y = cy };
ClientToScreen(hWnd, ref pt);
io.AddMouseSourceEvent(ImGuiMouseSource.Mouse);
io.AddMousePosEvent(pt.X, pt.Y);
}
switch (msg)
{
case WM_LBUTTONDOWN:
case WM_LBUTTONDBLCLK:
if (SetCapture(hWnd) == IntPtr.Zero) { /* ignore */ }
io.AddMouseButtonEvent(0, true);
return IntPtr.Zero;
case WM_LBUTTONUP:
io.AddMouseButtonEvent(0, false);
ReleaseCapture();
return IntPtr.Zero;
case WM_RBUTTONDOWN:
case WM_RBUTTONDBLCLK:
SetCapture(hWnd);
io.AddMouseButtonEvent(1, true);
return IntPtr.Zero;
case WM_RBUTTONUP:
io.AddMouseButtonEvent(1, false);
ReleaseCapture();
return IntPtr.Zero;
case WM_MBUTTONDOWN:
case WM_MBUTTONDBLCLK:
SetCapture(hWnd);
io.AddMouseButtonEvent(2, true);
return IntPtr.Zero;
case WM_MBUTTONUP:
io.AddMouseButtonEvent(2, false);
ReleaseCapture();
return IntPtr.Zero;
case WM_XBUTTONDOWN:
{
int btn = (((int)(long)wParam >> 16) & 0xFFFF) == 1 ? 3 : 4;
SetCapture(hWnd);
io.AddMouseButtonEvent(btn, true);
return IntPtr.Zero;
}
case WM_XBUTTONUP:
{
int btn = (((int)(long)wParam >> 16) & 0xFFFF) == 1 ? 3 : 4;
io.AddMouseButtonEvent(btn, false);
ReleaseCapture();
return IntPtr.Zero;
}
case WM_MOUSEWHEEL:
io.AddMouseWheelEvent(0f, (short)(((long)wParam >> 16) & 0xFFFF) / 120f);
return IntPtr.Zero;
case WM_MOUSEHWHEEL:
io.AddMouseWheelEvent((short)(((long)wParam >> 16) & 0xFFFF) / 120f, 0f);
return IntPtr.Zero;
case WM_KEYDOWN:
case WM_SYSKEYDOWN:
{
ImGuiKey key = VkToImGuiKey((int)(long)wParam);
if (key != ImGuiKey.None) io.AddKeyEvent(key, true);
// Let DefWindowProc run so system keys still function (Alt+F4 etc.).
break;
}
case WM_KEYUP:
case WM_SYSKEYUP:
{
ImGuiKey key = VkToImGuiKey((int)(long)wParam);
if (key != ImGuiKey.None) io.AddKeyEvent(key, false);
break;
}
case WM_CHAR:
{
uint ch = (uint)(long)wParam;
if (ch > 0 && ch < 0x10000) io.AddInputCharacter(ch);
return IntPtr.Zero;
}
case WM_CLOSE:
vp.PlatformRequestClose = true;
return IntPtr.Zero;
case WM_MOVE:
vp.PlatformRequestMove = true;
break;
case WM_SIZE:
vp.PlatformRequestResize = true;
break;
case WM_MOUSEACTIVATE:
{
// 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:
{
uint flags = unchecked((uint)vp.Flags);
if ((flags & (uint)ImGuiViewportFlags.NoInputs) != 0)
return new IntPtr(-1 /*HTTRANSPARENT*/);
break;
}
}
}
catch (Exception ex)
{
RynthLog.Info($"ViewportPlatform.WndProc: {ex.GetType().Name}: {ex.Message}");
}
finally
{
if (ImGuiContext != IntPtr.Zero && saved != ImGuiContext)
ImGuiNET.ImGui.SetCurrentContext(saved);
}
return DefWindowProcW(hWnd, msg, wParam, lParam);
}
private static ImGuiKey VkToImGuiKey(int vk)
{
return vk switch
{
0x09 => ImGuiKey.Tab,
0x25 => ImGuiKey.LeftArrow,
0x27 => ImGuiKey.RightArrow,
0x26 => ImGuiKey.UpArrow,
0x28 => ImGuiKey.DownArrow,
0x21 => ImGuiKey.PageUp,
0x22 => ImGuiKey.PageDown,
0x24 => ImGuiKey.Home,
0x23 => ImGuiKey.End,
0x2D => ImGuiKey.Insert,
0x2E => ImGuiKey.Delete,
0x08 => ImGuiKey.Backspace,
0x20 => ImGuiKey.Space,
0x0D => ImGuiKey.Enter,
0x1B => ImGuiKey.Escape,
0xBE => ImGuiKey.Period,
0xBC => ImGuiKey.Comma,
0xBD => ImGuiKey.Minus,
0xBB => ImGuiKey.Equal,
0xBA => ImGuiKey.Semicolon,
0xBF => ImGuiKey.Slash,
0xC0 => ImGuiKey.GraveAccent,
0xDB => ImGuiKey.LeftBracket,
0xDC => ImGuiKey.Backslash,
0xDD => ImGuiKey.RightBracket,
0xDE => ImGuiKey.Apostrophe,
>= 0x30 and <= 0x39 => ImGuiKey._0 + (vk - 0x30),
>= 0x41 and <= 0x5A => ImGuiKey.A + (vk - 0x41),
>= 0x60 and <= 0x69 => ImGuiKey.Keypad0 + (vk - 0x60),
>= 0x70 and <= 0x7B => ImGuiKey.F1 + (vk - 0x70),
0x10 => ImGuiKey.LeftShift,
0x11 => ImGuiKey.LeftCtrl,
0x12 => ImGuiKey.LeftAlt,
_ => ImGuiKey.None,
};
}
}

View file

@ -0,0 +1,200 @@
// ═══════════════════════════════════════════════════════════════════════════
// RynthCore.Engine — ImGui/ViewportProbe.cs
// One-shot diagnostic run at startup. Determines the byte offsets of each
// ImGuiPlatformIO callback field in the running cimgui.dll, so that we can
// install Win32/DX9 platform callbacks by writing IntPtrs directly into
// the native struct (ImGui.NET exposes callback fields as get-only).
//
// Remove/gate this once offsets are documented and wired into a static table.
// ═══════════════════════════════════════════════════════════════════════════
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;
using ImGuiNET;
namespace RynthCore.Engine.ImGuiBackend;
internal static class ViewportProbe
{
// Every Platform_* and Renderer_* callback field ImGui.NET exposes.
// Probing strategy: write a unique sentinel at each 4-byte slot, read
// every getter, record which getter sees the sentinel, restore the slot.
private static readonly string[] FieldsToProbe =
{
"Platform_CreateWindow",
"Platform_DestroyWindow",
"Platform_ShowWindow",
"Platform_SetWindowPos",
"Platform_GetWindowPos",
"Platform_SetWindowSize",
"Platform_GetWindowSize",
"Platform_SetWindowFocus",
"Platform_GetWindowFocus",
"Platform_GetWindowMinimized",
"Platform_SetWindowTitle",
"Platform_SetWindowAlpha",
"Platform_UpdateWindow",
"Platform_RenderWindow",
"Platform_SwapBuffers",
"Platform_GetWindowDpiScale",
"Platform_OnChangedViewport",
"Platform_GetWindowWorkAreaInsets",
"Platform_CreateVkSurface",
"Renderer_CreateWindow",
"Renderer_DestroyWindow",
"Renderer_SetWindowSize",
"Renderer_RenderWindow",
"Renderer_SwapBuffers",
};
// ImGuiViewport fields worth locating so we know where ImGui.NET reads from
// vs the authoritative bytes. These are read-back tests — no writes.
private static readonly string[] ViewportFieldsToLog =
{
"ID",
"Flags",
"Pos",
"Size",
"WorkPos",
"WorkSize",
"DpiScale",
"ParentViewportId",
"DrawData",
"RendererUserData",
"PlatformUserData",
"PlatformHandle",
"PlatformHandleRaw",
"PlatformWindowCreated",
"PlatformRequestMove",
"PlatformRequestResize",
"PlatformRequestClose",
};
private const int ScanBytes = 768;
public static void Run()
{
try
{
RynthLog.Info("ViewportProbe: ---- begin ----");
RunPlatformIOProbe();
RunMainViewportDump();
RynthLog.Info("ViewportProbe: ---- end ----");
}
catch (Exception ex)
{
RynthLog.Info($"ViewportProbe: FAILED {ex.GetType().Name}: {ex.Message}");
}
}
private static unsafe void RunPlatformIOProbe()
{
ImGuiPlatformIOPtr pio = ImGuiNET.ImGui.GetPlatformIO();
IntPtr pioNative = (IntPtr)pio.NativePtr;
RynthLog.Info($"ViewportProbe: PlatformIO native = 0x{pioNative.ToInt64():X8}");
// Log what each getter returns BEFORE probing, so we can see the stock zero state.
var propertyCache = new Dictionary<string, PropertyInfo>(StringComparer.Ordinal);
Type ptrType = typeof(ImGuiPlatformIOPtr);
foreach (string name in FieldsToProbe)
{
PropertyInfo? prop = ptrType.GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
bool intptrLike = prop != null && (
prop.PropertyType == typeof(IntPtr) ||
(prop.PropertyType.IsByRef && prop.PropertyType.GetElementType() == typeof(IntPtr)));
if (intptrLike)
{
propertyCache[name] = prop!;
}
else
{
RynthLog.Info($"ViewportProbe: {name}: NOT FOUND on ImGuiPlatformIOPtr (type={prop?.PropertyType.Name ?? "null"})");
}
}
var discovered = new Dictionary<string, int>(StringComparer.Ordinal);
for (int off = 0; off < ScanBytes; off += 4)
{
IntPtr orig = Marshal.ReadIntPtr(pioNative, off);
IntPtr sentinel = new IntPtr(unchecked((int)0xAB000000) | off);
Marshal.WriteIntPtr(pioNative, off, sentinel);
foreach (var kv in propertyCache)
{
IntPtr read;
try
{
read = (IntPtr)kv.Value.GetValue(pio)!;
}
catch
{
continue;
}
if (read == sentinel && !discovered.ContainsKey(kv.Key))
{
discovered[kv.Key] = off;
}
}
Marshal.WriteIntPtr(pioNative, off, orig);
}
// Emit in ascending offset order so the mapping is obvious in the log.
var sorted = new List<KeyValuePair<string, int>>(discovered);
sorted.Sort((a, b) => a.Value.CompareTo(b.Value));
RynthLog.Info($"ViewportProbe: discovered {sorted.Count}/{propertyCache.Count} offsets:");
foreach (var kv in sorted)
RynthLog.Info($"ViewportProbe: +{kv.Value,4} {kv.Key}");
foreach (string name in FieldsToProbe)
{
if (propertyCache.ContainsKey(name) && !discovered.ContainsKey(name))
RynthLog.Info($"ViewportProbe: MISSING {name} (getter exists but sentinel never matched)");
}
// Hex dump of the first chunk so we can visually scan for anomalies.
DumpRange(pioNative, 0, 256, "PlatformIO");
}
private static unsafe void RunMainViewportDump()
{
ImGuiViewportPtr main = ImGuiNET.ImGui.GetMainViewport();
IntPtr vp = (IntPtr)main.NativePtr;
RynthLog.Info($"ViewportProbe: MainViewport native = 0x{vp.ToInt64():X8}");
Type vptrType = typeof(ImGuiViewportPtr);
foreach (string name in ViewportFieldsToLog)
{
PropertyInfo? prop = vptrType.GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
if (prop == null)
{
RynthLog.Info($"ViewportProbe: MainViewport.{name}: (no such property)");
continue;
}
object? val;
try { val = prop.GetValue(main); }
catch (Exception ex) { val = $"<throw {ex.GetType().Name}>"; continue; }
RynthLog.Info($"ViewportProbe: MainViewport.{name} ({prop.PropertyType.Name}) = {val}");
}
DumpRange(vp, 0, 160, "MainViewport");
}
private static void DumpRange(IntPtr basePtr, int startOffset, int length, string label)
{
for (int off = startOffset; off < startOffset + length; off += 16)
{
uint w0 = unchecked((uint)Marshal.ReadInt32(basePtr, off + 0));
uint w1 = unchecked((uint)Marshal.ReadInt32(basePtr, off + 4));
uint w2 = unchecked((uint)Marshal.ReadInt32(basePtr, off + 8));
uint w3 = unchecked((uint)Marshal.ReadInt32(basePtr, off + 12));
RynthLog.Info($"ViewportProbe: {label} +{off,4} {w0:X8} {w1:X8} {w2:X8} {w3:X8}");
}
}
}

View file

@ -0,0 +1,367 @@
// ═══════════════════════════════════════════════════════════════════════════
// RynthCore.Engine — ImGui/ViewportRendererBackend.cs
// Per-viewport D3D9 renderer backend for ImGui multi-viewport.
// Installs Renderer_* callbacks on ImGuiPlatformIO: for each viewport we
// create an additional swap chain on the game's device, render the viewport's
// ImDrawData into that swap chain's back buffer, and Present it so the
// viewport's OS window displays the ImGui content.
// ═══════════════════════════════════════════════════════════════════════════
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using ImGuiNET;
using RynthCore.Engine.D3D9;
namespace RynthCore.Engine.ImGuiBackend;
internal static unsafe class ViewportRendererBackend
{
// ─── D3D9 constants ───────────────────────────────────────────────
private const uint D3DFMT_UNKNOWN = 0;
private const uint D3DFMT_A8R8G8B8 = 21;
private const uint D3DFMT_X8R8G8B8 = 22;
private const uint D3DSWAPEFFECT_DISCARD = 1;
private const uint D3DBACKBUFFER_TYPE_MONO = 0;
private const uint D3DCLEAR_TARGET = 0x00000001;
private const uint D3DPRESENT_INTERVAL_IMMEDIATE = 0x80000000;
[StructLayout(LayoutKind.Sequential)]
private 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; // BOOL
public int EnableAutoDepthStencil; // BOOL
public uint AutoDepthStencilFormat;
public uint Flags;
public uint FullScreen_RefreshRateInHz;
public uint PresentationInterval;
}
[StructLayout(LayoutKind.Sequential)]
private struct RECT { public int L, T, R, B; }
// ─── Device method delegates ──────────────────────────────────────
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int CreateAdditionalSwapChainD(IntPtr pDevice, D3DPRESENT_PARAMETERS* pp, out IntPtr ppSwapChain);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int SetRenderTargetD(IntPtr pDevice, uint rtIndex, IntPtr pSurface);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int GetRenderTargetD(IntPtr pDevice, uint rtIndex, out IntPtr ppSurface);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int ClearD(IntPtr pDevice, uint count, RECT* pRects, uint flags, uint color, float z, uint stencil);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate uint ReleaseD(IntPtr pObj);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int SwapChainGetBackBufferD(IntPtr pSwapChain, uint backBufIdx, uint type, out IntPtr ppBackBuffer);
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int SwapChainPresentD(IntPtr pSwapChain, RECT* src, RECT* dest, IntPtr hDestWnd, IntPtr dirtyRgn, uint flags);
// ─── Callback delegates (must match imgui types) ──────────────────
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void ViewportCallbackD(ImGuiViewport* vp);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void ViewportSizeCallbackD(ImGuiViewport* vp, System.Numerics.Vector2 size);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
private delegate void ViewportRenderD(ImGuiViewport* vp, IntPtr renderArg);
// ─── State ────────────────────────────────────────────────────────
private sealed class ViewportGpuState
{
public IntPtr SwapChain;
public int Width;
public int Height;
}
private static IntPtr _device;
private static CreateAdditionalSwapChainD? _createAdditionalSwapChain;
private static SetRenderTargetD? _setRenderTarget;
private static GetRenderTargetD? _getRenderTarget;
private static ClearD? _clear;
private static readonly Dictionary<IntPtr, ViewportGpuState> _viewports = new();
private static readonly List<Delegate> _delegateRoots = new();
private static bool _initialized;
// Diagnostic one-shot logging counters — limited to a few calls so log doesn't explode.
private static int _logCreate;
private static int _logRender;
private static int _logSwap;
private const int MaxLog = 3;
public static bool Init(IntPtr pDevice)
{
if (_initialized) return true;
if (pDevice == IntPtr.Zero)
{
RynthLog.Info("ViewportRenderer: Init called with null device.");
return false;
}
_device = pDevice;
IntPtr vtable = Marshal.ReadIntPtr(pDevice);
_createAdditionalSwapChain = GetMethod<CreateAdditionalSwapChainD>(vtable, DeviceVTableIndex.CreateAdditionalSwapChain);
_setRenderTarget = GetMethod<SetRenderTargetD>(vtable, DeviceVTableIndex.SetRenderTarget);
_getRenderTarget = GetMethod<GetRenderTargetD>(vtable, DeviceVTableIndex.GetRenderTarget);
_clear = GetMethod<ClearD>(vtable, DeviceVTableIndex.Clear);
InstallCallbacks();
ImGuiIOPtr io = ImGuiNET.ImGui.GetIO();
io.BackendFlags |= ImGuiBackendFlags.RendererHasViewports;
_initialized = true;
RynthLog.Info("ViewportRenderer: initialized.");
return true;
}
public static void Shutdown()
{
foreach (var kv in _viewports)
{
if (kv.Value.SwapChain != IntPtr.Zero)
ReleaseCom(kv.Value.SwapChain);
}
_viewports.Clear();
_delegateRoots.Clear();
_initialized = false;
}
private static void InstallCallbacks()
{
ImGuiPlatformIOPtr pio = ImGuiNET.ImGui.GetPlatformIO();
IntPtr pioNative = (IntPtr)pio.NativePtr;
ViewportCallbackD createFn = RendererCreateWindow;
ViewportCallbackD destroyFn = RendererDestroyWindow;
ViewportSizeCallbackD setSizeFn = RendererSetWindowSize;
ViewportRenderD renderFn = RendererRenderWindow;
ViewportRenderD swapFn = RendererSwapBuffers;
_delegateRoots.Add(createFn);
_delegateRoots.Add(destroyFn);
_delegateRoots.Add(setSizeFn);
_delegateRoots.Add(renderFn);
_delegateRoots.Add(swapFn);
IntPtr createPtr = Marshal.GetFunctionPointerForDelegate(createFn);
IntPtr destroyPtr = Marshal.GetFunctionPointerForDelegate(destroyFn);
IntPtr setSizePtr = Marshal.GetFunctionPointerForDelegate(setSizeFn);
IntPtr renderPtr = Marshal.GetFunctionPointerForDelegate(renderFn);
IntPtr swapPtr = Marshal.GetFunctionPointerForDelegate(swapFn);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.RendererCreateWindow, createPtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.RendererDestroyWindow, destroyPtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.RendererSetWindowSize, setSizePtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.RendererRenderWindow, renderPtr);
Marshal.WriteIntPtr(pioNative, ViewportOffsets.RendererSwapBuffers, swapPtr);
IntPtr verify = Marshal.ReadIntPtr(pioNative, ViewportOffsets.RendererRenderWindow);
RynthLog.Info($"ViewportRenderer: installed handlers (RenderWindow readback=0x{verify.ToInt64():X8}, expected=0x{renderPtr.ToInt64():X8})");
}
// ─── Callback implementations ─────────────────────────────────────
private static void RendererCreateWindow(ImGuiViewport* vp)
{
IntPtr key = (IntPtr)vp;
if (_viewports.ContainsKey(key)) return;
var state = new ViewportGpuState();
_viewports[key] = state;
int w = Math.Max(1, (int)vp->Size.X);
int h = Math.Max(1, (int)vp->Size.Y);
CreateSwapChainForViewport(vp, state, w, h);
if (_logCreate++ < MaxLog)
{
IntPtr hwnd = (IntPtr)vp->PlatformHandleRaw;
if (hwnd == IntPtr.Zero) hwnd = (IntPtr)vp->PlatformHandle;
RynthLog.Info($"ViewportRenderer: CreateWindow vp=0x{key.ToInt64():X8} hwnd=0x{hwnd.ToInt64():X8} size={w}x{h} swapChain=0x{state.SwapChain.ToInt64():X8}");
}
}
private static void RendererDestroyWindow(ImGuiViewport* vp)
{
IntPtr key = (IntPtr)vp;
if (!_viewports.TryGetValue(key, out var state)) return;
if (state.SwapChain != IntPtr.Zero)
{
ReleaseCom(state.SwapChain);
state.SwapChain = IntPtr.Zero;
}
_viewports.Remove(key);
}
private static void RendererSetWindowSize(ImGuiViewport* vp, System.Numerics.Vector2 size)
{
IntPtr key = (IntPtr)vp;
if (!_viewports.TryGetValue(key, out var state)) return;
int w = Math.Max(1, (int)size.X);
int h = Math.Max(1, (int)size.Y);
if (w == state.Width && h == state.Height) return;
if (state.SwapChain != IntPtr.Zero)
{
ReleaseCom(state.SwapChain);
state.SwapChain = IntPtr.Zero;
}
CreateSwapChainForViewport(vp, state, w, h);
}
private static void RendererRenderWindow(ImGuiViewport* vp, IntPtr renderArg)
{
IntPtr key = (IntPtr)vp;
bool diag = _logRender < MaxLog;
if (!_viewports.TryGetValue(key, out var state))
{
if (diag) { RynthLog.Info($"ViewportRenderer: RenderWindow vp=0x{key.ToInt64():X8} NO STATE"); _logRender++; }
return;
}
if (state.SwapChain == IntPtr.Zero)
{
if (diag) { RynthLog.Info($"ViewportRenderer: RenderWindow vp=0x{key.ToInt64():X8} NO SWAPCHAIN"); _logRender++; }
return;
}
if (_setRenderTarget == null || _getRenderTarget == null || _clear == null)
{
if (diag) { RynthLog.Info("ViewportRenderer: RenderWindow device methods null"); _logRender++; }
return;
}
// Get the swap chain's back-buffer surface
var getBB = GetMethodFromObj<SwapChainGetBackBufferD>(state.SwapChain, SwapChain9VTableIndex.GetBackBuffer);
int hrBB = getBB(state.SwapChain, 0, D3DBACKBUFFER_TYPE_MONO, out IntPtr backBuffer);
if (hrBB < 0 || backBuffer == IntPtr.Zero)
{
if (diag) { RynthLog.Info($"ViewportRenderer: GetBackBuffer failed hr=0x{hrBB:X8}"); _logRender++; }
return;
}
IntPtr oldRenderTarget = IntPtr.Zero;
int cmdCount = 0;
float ddW = 0, ddH = 0, ddX = 0, ddY = 0;
try
{
_getRenderTarget(_device, 0, out oldRenderTarget);
int hrSRT = _setRenderTarget(_device, 0, backBuffer);
// Clear unless the ImGui viewport asked us not to.
uint flags = unchecked((uint)vp->Flags);
if ((flags & (uint)ImGuiViewportFlags.NoRendererClear) == 0)
{
_clear(_device, 0, null, D3DCLEAR_TARGET, 0x00000000u, 1.0f, 0);
}
// Render the viewport's own draw data through the main DX9 backend,
// which already handles full state save/restore.
ImDrawDataPtr draw = new ImDrawDataPtr((ImDrawData*)vp->DrawData);
if ((IntPtr)draw.NativePtr != IntPtr.Zero)
{
IntPtr dd = (IntPtr)draw.NativePtr;
cmdCount = Marshal.ReadInt32(dd, 4);
ddX = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(dd, 20));
ddY = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(dd, 24));
ddW = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(dd, 28));
ddH = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(dd, 32));
DX9Backend.RenderDrawData(draw, _device);
}
if (diag)
{
RynthLog.Info($"ViewportRenderer: RenderWindow vp=0x{key.ToInt64():X8} setRT=0x{hrSRT:X8} bb=0x{backBuffer.ToInt64():X8} cmds={cmdCount} ddPos=({ddX},{ddY}) ddSize=({ddW},{ddH})");
_logRender++;
}
}
finally
{
if (oldRenderTarget != IntPtr.Zero)
{
_setRenderTarget(_device, 0, oldRenderTarget);
ReleaseCom(oldRenderTarget);
}
ReleaseCom(backBuffer);
}
}
private static void RendererSwapBuffers(ImGuiViewport* vp, IntPtr renderArg)
{
IntPtr key = (IntPtr)vp;
if (!_viewports.TryGetValue(key, out var state)) return;
if (state.SwapChain == IntPtr.Zero) return;
var present = GetMethodFromObj<SwapChainPresentD>(state.SwapChain, SwapChain9VTableIndex.Present);
int hr = present(state.SwapChain, null, null, IntPtr.Zero, IntPtr.Zero, 0);
if (_logSwap++ < MaxLog)
RynthLog.Info($"ViewportRenderer: SwapBuffers vp=0x{key.ToInt64():X8} Present hr=0x{hr:X8}");
}
// ─── Helpers ──────────────────────────────────────────────────────
private static void CreateSwapChainForViewport(ImGuiViewport* vp, ViewportGpuState state, int w, int h)
{
if (_createAdditionalSwapChain == null) return;
IntPtr hwnd = (IntPtr)vp->PlatformHandleRaw;
if (hwnd == IntPtr.Zero) hwnd = (IntPtr)vp->PlatformHandle;
if (hwnd == IntPtr.Zero)
{
RynthLog.Info("ViewportRenderer: viewport has no HWND — cannot create swap chain.");
return;
}
var pp = new D3DPRESENT_PARAMETERS
{
BackBufferWidth = (uint)w,
BackBufferHeight = (uint)h,
BackBufferFormat = D3DFMT_UNKNOWN, // match device default
BackBufferCount = 1,
SwapEffect = D3DSWAPEFFECT_DISCARD,
hDeviceWindow = hwnd,
Windowed = 1,
// Don't wait for vblank — each popped viewport adds another Present
// per frame, and stacking vsyncs cuts the effective frame rate.
PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE,
};
int hr = _createAdditionalSwapChain(_device, &pp, out IntPtr swapChain);
if (hr < 0 || swapChain == IntPtr.Zero)
{
RynthLog.Info($"ViewportRenderer: CreateAdditionalSwapChain failed (hr=0x{hr:X8}) for {w}x{h} hwnd=0x{hwnd:X}");
return;
}
state.SwapChain = swapChain;
state.Width = w;
state.Height = h;
}
private static T GetMethod<T>(IntPtr vtable, int index) where T : Delegate
{
IntPtr addr = Marshal.ReadIntPtr(vtable, index * IntPtr.Size);
return Marshal.GetDelegateForFunctionPointer<T>(addr);
}
private static T GetMethodFromObj<T>(IntPtr pObj, int index) where T : Delegate
{
IntPtr vtable = Marshal.ReadIntPtr(pObj);
IntPtr addr = Marshal.ReadIntPtr(vtable, index * IntPtr.Size);
return Marshal.GetDelegateForFunctionPointer<T>(addr);
}
private static void ReleaseCom(IntPtr pObj)
{
if (pObj == IntPtr.Zero) return;
IntPtr vtable = Marshal.ReadIntPtr(pObj);
IntPtr addr = Marshal.ReadIntPtr(vtable, 2 * IntPtr.Size); // Release is index 2
var release = Marshal.GetDelegateForFunctionPointer<ReleaseD>(addr);
release(pObj);
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,211 @@
// ============================================================================
// RynthCore.Engine - LogPaths.cs
// Log file layout under C:\Games\RynthCore\Logs\:
//
// RynthCore.log SHARED launch/orchestration log. Written by the
// injector and launcher (separate processes), plus
// a one-line session pointer from each engine at
// startup. This is the human entry point / index.
// RynthCore.<pid>.log PER-CLIENT session log. Written by the loader,
// engine, and plugins inside one acclient.exe
// (they all share that client's PID). One file per
// running client.
//
// Why per-client: a daily multi-boxer runs N acclient.exe at once. With one
// shared file their lines interleave, the "scan hb #N for a gap" silent-death
// check is defeated (other clients' heartbeats fill every gap), and startup
// rotation from one client can truncate the log out from under the others.
// Per-PID files give each client an independent, gap-detectable session log
// with no cross-process rotation race.
// ============================================================================
using System;
using System.IO;
namespace RynthCore.Engine;
internal static class LogPaths
{
/// <summary>Unified log directory for all RynthCore components.</summary>
internal const string LogDirectory = @"C:\Games\RynthCore\Logs";
/// <summary>Shared launch/orchestration log (injector + launcher + per-engine session pointer).</summary>
internal const string SharedLogFileName = "RynthCore.log";
/// <summary>Rotate the active per-client log when it grows beyond this size at engine startup.</summary>
internal const long MaxLogBytes = 5L * 1024 * 1024;
/// <summary>Delete per-client logs older than this during startup prune.</summary>
private static readonly TimeSpan MaxLogAge = TimeSpan.FromDays(7);
/// <summary>Per-client session log filename, keyed on this process's PID.</summary>
internal static string LogFileName => $"RynthCore.{Environment.ProcessId}.log";
/// <summary>Full path to this client's per-PID session log (loader + engine + plugins).</summary>
internal static string LogFilePath => Path.Combine(LogDirectory, LogFileName);
/// <summary>Rotated previous copy of this client's session log.</summary>
internal static string RotatedLogFilePath => Path.Combine(LogDirectory, LogFileName + ".old");
/// <summary>Full path to the shared launch/orchestration log.</summary>
internal static string SharedLogFilePath => Path.Combine(LogDirectory, SharedLogFileName);
// Per-client status log files (Logs\status\RynthCore.<pid>.status.json) are written by the private
// RynthRemote plugin; the engine only knows the directory + filename so the startup log-pruner below
// can clean up stale files left by crashed clients. The engine writes no status file and never networks.
/// <summary>Directory for per-client status JSON files (Logs\status).</summary>
internal static string StatusDirectory => Path.Combine(LogDirectory, "status");
/// <summary>This process's per-PID status filename (so the pruner skips our own live file).</summary>
internal static string StatusFileName => $"RynthCore.{Environment.ProcessId}.status.json";
/// <summary>
/// Best-effort: create the log directory. Safe to call repeatedly. Never throws.
/// </summary>
internal static void EnsureLogDirectory()
{
try
{
Directory.CreateDirectory(LogDirectory);
}
catch
{
// No fallback — if C:\Games\RynthCore\Logs can't be created the
// sink will silently swallow writes. We deliberately do NOT fall
// back to Desktop because that scatters logs across machines.
}
}
/// <summary>
/// Engine-startup rotation: if THIS client's per-PID log exceeds
/// <see cref="MaxLogBytes"/>, move it to RynthCore.&lt;pid&gt;.log.old. With per-PID
/// files this only ever touches the current client's own file, so there is no
/// cross-process rotation race (the bug the old shared-file design had). Rotation
/// still matters because Windows reuses PIDs across launches.
/// </summary>
internal static void RotateAtStartup()
{
try
{
EnsureLogDirectory();
string active = LogFilePath;
if (!File.Exists(active)) return;
long size;
try { size = new FileInfo(active).Length; }
catch { return; }
if (size < MaxLogBytes) return;
string rotated = RotatedLogFilePath;
try { if (File.Exists(rotated)) File.Delete(rotated); } catch { }
try { File.Move(active, rotated); }
catch
{
// A hot-reloaded engine generation in this same process may hold
// the handle. Best-effort truncate so the file doesn't grow without
// bound. Safe under per-PID: only ever our own client's file.
try { File.WriteAllText(active, string.Empty); } catch { }
}
}
catch
{
}
}
/// <summary>
/// Startup housekeeping: delete per-client session logs (and their .old
/// rotations) older than <see cref="MaxLogAge"/>. Each client launch produces a
/// new RynthCore.&lt;pid&gt;.log, so without this the directory grows without bound.
/// Never touches the shared RynthCore.log or the current client's own file.
/// Best-effort; never throws.
/// </summary>
internal static void PruneOldLogs()
{
try
{
EnsureLogDirectory();
string self = LogFileName;
DateTime cutoff = DateTime.Now - MaxLogAge;
foreach (string path in Directory.GetFiles(LogDirectory, "RynthCore.*.log*"))
{
string name = Path.GetFileName(path);
// Skip the shared log and our own current session file.
if (name.Equals(SharedLogFileName, StringComparison.OrdinalIgnoreCase)) continue;
if (name.StartsWith(self, StringComparison.OrdinalIgnoreCase)) continue;
try
{
if (File.GetLastWriteTime(path) < cutoff)
File.Delete(path);
}
catch { /* locked by a live client or already gone — skip */ }
}
// Stale status files: a crashed client leaves its RynthCore.<pid>.status.json behind. The
// StatusAgent deletes dead-PID files itself, but prune here too so they never accumulate if
// the agent isn't running. Never touches our own current file.
string statusDir = StatusDirectory;
if (Directory.Exists(statusDir))
{
string selfStatus = StatusFileName;
foreach (string sf in Directory.GetFiles(statusDir, "RynthCore.*.status.json"))
{
if (Path.GetFileName(sf).Equals(selfStatus, StringComparison.OrdinalIgnoreCase)) continue;
try { if (File.GetLastWriteTime(sf) < cutoff) File.Delete(sf); }
catch { /* locked by a live client or already gone — skip */ }
}
}
// Dump retention: hang/crash minidumps under Logs\dumps otherwise
// accumulate forever, and a failed write attempt leaves a 0-byte
// .dmp that reads as a crash marker during triage.
string dumps = Path.Combine(LogDirectory, "dumps");
if (Directory.Exists(dumps))
{
foreach (string dmp in Directory.GetFiles(dumps, "*.dmp"))
{
try
{
var fi = new FileInfo(dmp);
if (fi.Length == 0 || fi.LastWriteTime < cutoff)
fi.Delete();
}
catch { }
}
}
}
catch
{
}
}
/// <summary>
/// Mid-session rotation — same size-gated rotate as startup, safe to call
/// while the client runs (the writer opens per-append; on a held handle it
/// falls back to truncate). Called from the heartbeat loop ~once/minute:
/// startup-only rotation never ran on a 10h+ soak and was skipped entirely
/// on hot-reload (initCount > 1), so the per-PID log grew without bound.
/// </summary>
internal static void RotateIfOversized() => RotateAtStartup();
/// <summary>
/// Append a single best-effort line to the SHARED RynthCore.log so it acts as
/// an index of client sessions ("which PID, which build, which file"). Keeps
/// "start at RynthCore.log" discoverability after the per-PID split.
/// </summary>
internal static void WriteSessionPointer(string line)
{
try
{
EnsureLogDirectory();
using var fs = new FileStream(SharedLogFilePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(line + "\r\n");
fs.Write(bytes, 0, bytes.Length);
}
catch
{
}
}
}

View file

@ -0,0 +1,262 @@
// ============================================================================
// RynthCore.Engine - MainThreadHangWatchdog.cs
// Diagnostic for the "client freezes / character heartbeat stops while the
// bot keeps trying" class of bug: AC's MAIN thread wedges while our off-thread
// engine threads keep running, so the freeze never surfaces as a crash and we
// could only guess where it stuck.
//
// How it works:
// * EndSceneDetour (which runs on AC's main/render thread, every frame, even
// with the ImGui backend disabled) calls MainThreadBeat() — stamping a
// "last seen alive" tick and recording the main thread id once.
// * A dedicated background thread polls that tick. If the main thread hasn't
// beaten in > HangThresholdMs, it is wedged. We OpenThread + SuspendThread
// just long enough to GetThreadContext (an accurate EIP/EBP/ESP snapshot),
// immediately ResumeThread, then walk + log the native stack via
// CrashLogger. (Logging happens AFTER resume so a main thread hung while
// holding the log-file lock can't deadlock the watchdog. The thread is
// hung, so its stack memory stays stable for the post-resume walk.)
//
// This captures the exact wedge location for every client, on every freeze,
// with no external debugger and no per-PID coordination.
// ============================================================================
using System;
using System.Runtime.InteropServices;
using System.Threading;
namespace RynthCore.Engine;
internal static class MainThreadHangWatchdog
{
[DllImport("kernel32.dll")]
private static extern uint GetCurrentThreadId();
[DllImport("kernel32.dll", SetLastError = true)]
private static extern IntPtr OpenThread(uint dwDesiredAccess, bool bInheritHandle, uint dwThreadId);
[DllImport("kernel32.dll")]
private static extern uint SuspendThread(IntPtr hThread);
[DllImport("kernel32.dll")]
private static extern uint ResumeThread(IntPtr hThread);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool GetThreadContext(IntPtr hThread, IntPtr lpContext);
[DllImport("kernel32.dll")]
private static extern bool CloseHandle(IntPtr hObject);
private const uint THREAD_GET_CONTEXT = 0x0008;
private const uint THREAD_SUSPEND_RESUME = 0x0002;
private const uint THREAD_QUERY_INFORMATION = 0x0040;
// x86 CONTEXT_FULL = CONTEXT_i386(0x10000) | CONTROL(1) | INTEGER(2) | SEGMENTS(4).
private const int CONTEXT_FULL = 0x10007;
// x86 CONTEXT is 716 bytes; over-allocate for safety. ContextFlags is at offset 0.
private const int CONTEXT_SIZE = 1232;
// Stalls longer than this with no EndScene beat = main thread wedged.
private const long HangThresholdMs = 4000;
// Max stack samples to take during a single hang (1/sec). A permanent freeze
// shows a stable eip across these = the true wedge; a transient stall logs
// RECOVERED. Capped to keep the log readable.
private const int MaxSamplesPerHang = 6;
private const int CTX_OFF_EIP = 184; // x86 CONTEXT.Eip
private static volatile uint _mainThreadId;
private static long _lastBeatTick;
private static int _running;
// EndScene frame tally — single-writer (AC render thread via MainThreadBeat),
// read by HeartbeatLogger to report fps (0 fps = render dead but process alive).
private static int _frameCount;
// Once-per-session latch so a permanent wedge writes exactly one minidump.
private static int _dumpWritten;
/// <summary>Monotonic EndScene frame count since engine init.</summary>
internal static int FrameCount => _frameCount;
/// <summary>
/// Called from EndSceneDetour on AC's main thread, every frame. Must be
/// cheap and never throw.
/// </summary>
internal static void MainThreadBeat()
{
if (_mainThreadId == 0)
_mainThreadId = GetCurrentThreadId();
_frameCount++;
Volatile.Write(ref _lastBeatTick, Environment.TickCount64);
}
/// <summary>
/// Second beat source: the Client::UseTime game-logic tick. Does NOT bump
/// the frame counter (fps must keep meaning rendered frames). Closes the
/// watchdog's blind spot where the main thread wedges BEFORE the new
/// generation's EndScene hook ever fires (the 2026-06-11 reload wedge ran
/// for ~60s with no hang detection and therefore no minidump) — with this
/// beat, a wedged main thread always goes silent on BOTH sources and the
/// watchdog produces the dump that names where the thread sits.
/// </summary>
internal static void MainThreadBeatNoFrame()
{
if (_mainThreadId == 0)
_mainThreadId = GetCurrentThreadId();
Volatile.Write(ref _lastBeatTick, Environment.TickCount64);
}
private static Thread? _thread;
internal static void Start()
{
if (Interlocked.Exchange(ref _running, 1) != 0) return;
Volatile.Write(ref _lastBeatTick, Environment.TickCount64);
_thread = new Thread(Loop) { Name = "RynthCore.MainThreadHangWatchdog", IsBackground = true };
_thread.Start();
RynthLog.Info($"MainThreadHangWatchdog: armed (threshold={HangThresholdMs}ms).");
}
/// <summary>
/// Stop the watchdog thread. Must run during EngineLifecycle.Shutdown: once
/// the EndScene detour is uninstalled the beat goes silent, and a still-running
/// old-generation watchdog declares a false hang within 4s of every hot-reload —
/// suspending AC's healthy main thread and writing a spurious minidump while
/// the next engine generation is initializing.
/// </summary>
internal static void Stop()
{
if (Interlocked.Exchange(ref _running, 0) == 0) return;
var t = _thread;
_thread = null;
if (t != null && !t.Join(1500))
RynthLog.Warn("MainThreadHangWatchdog: thread did not exit within 1500ms — continuing shutdown.");
else
RynthLog.Info("MainThreadHangWatchdog: stopped.");
}
private static void Loop()
{
bool inHang = false;
int sample = 0;
long hangStartBeat = 0;
while (Volatile.Read(ref _running) != 0)
{
try
{
Thread.Sleep(1000);
uint tid = _mainThreadId;
if (tid == 0) continue; // EndScene hasn't beaten yet
long lastBeat = Volatile.Read(ref _lastBeatTick);
long stale = Environment.TickCount64 - lastBeat;
if (stale >= HangThresholdMs)
{
if (!inHang)
{
inHang = true;
sample = 0;
hangStartBeat = lastBeat;
RynthLog.Info("================================================================");
RynthLog.Error($"==== MAIN THREAD HANG DETECTED tid={tid} build={EntryPoint.BuildStamp} initCount={EntryPoint.InitCount} (stalled {stale}ms) ====");
}
if (sample < MaxSamplesPerHang)
{
sample++;
// Full stack on the first sample; one-line eip on the rest.
CaptureMainThreadStack(tid, stale, sample, fullStack: sample == 1);
}
else if (sample == MaxSamplesPerHang)
{
sample++;
RynthLog.Info($" (still hung after {MaxSamplesPerHang} samples — suppressing further samples until recovery)");
// Confirmed permanent wedge (~10s+): write one targeted
// minidump for WinDbg post-mortem if the log stack walk
// isn't enough. Once per session.
TryWriteHangDump(tid, stale);
}
}
else if (inHang)
{
inHang = false;
RynthLog.Info($"==== MAIN THREAD RECOVERED after ~{Environment.TickCount64 - hangStartBeat}ms ({Math.Min(sample, MaxSamplesPerHang)} sample(s) taken) ====");
RynthLog.Info("================================================================");
}
}
catch { /* a diagnostic must never destabilize the host */ }
}
}
/// <summary>
/// On the first confirmed permanent hang of the session, write a minidump
/// (gated by EngineSettings.EnableHangMinidump). Best-effort; never throws.
/// </summary>
private static void TryWriteHangDump(uint tid, long staleMs)
{
if (Interlocked.Exchange(ref _dumpWritten, 1) != 0) return; // once per session
try
{
if (!Plugins.EngineSettings.EnableHangMinidump)
{
RynthLog.Info(" (hang minidump disabled via EngineSettings.EnableHangMinidump)");
return;
}
CrashDump.WriteSelfDump(
$"main-thread hang tid={tid} stale={staleMs}ms build={EntryPoint.BuildStamp}", out _);
}
catch { /* a diagnostic must never destabilize the host */ }
}
private static void CaptureMainThreadStack(uint tid, long staleMs, int sampleNum, bool fullStack)
{
IntPtr h = OpenThread(THREAD_GET_CONTEXT | THREAD_SUSPEND_RESUME | THREAD_QUERY_INFORMATION, false, tid);
if (h == IntPtr.Zero)
{
RynthLog.Info($" sample#{sampleNum}: OpenThread failed err={Marshal.GetLastWin32Error()}");
return;
}
IntPtr ctx = Marshal.AllocHGlobal(CONTEXT_SIZE);
bool ctxOk = false;
uint suspendCount = 0xFFFFFFFF;
try
{
for (int i = 0; i < CONTEXT_SIZE; i += 4)
Marshal.WriteInt32(ctx, i, 0);
Marshal.WriteInt32(ctx, 0, CONTEXT_FULL); // ContextFlags @ offset 0
// Minimal suspend window: snapshot the register context, then resume
// immediately so the (possibly log-lock-holding) main thread isn't
// frozen while we do file I/O below.
suspendCount = SuspendThread(h);
if (suspendCount != 0xFFFFFFFF)
{
ctxOk = GetThreadContext(h, ctx);
ResumeThread(h);
}
if (!ctxOk)
{
RynthLog.Info($" sample#{sampleNum}: GetThreadContext failed (suspendCount={suspendCount})");
return;
}
uint eip = (uint)Marshal.ReadInt32(ctx, CTX_OFF_EIP);
RynthLog.Info($" sample#{sampleNum} (stale {staleMs}ms) eip=0x{eip:X8} {CrashLogger.ResolveCodeAddr((IntPtr)eip)}");
if (fullStack)
CrashLogger.DumpExternalContext(ctx, "HANG");
}
catch (Exception ex)
{
RynthLog.Info($" sample#{sampleNum}: capture threw {ex.GetType().Name}: {ex.Message}");
}
finally
{
Marshal.FreeHGlobal(ctx);
CloseHandle(h);
}
}
}

Binary file not shown.

Some files were not shown because too many files have changed in this diff Show more