Add door/vendor/motion hooks, auto-ID service, and int property caching

Adds engine-side support for door interaction (DoMotion, SmartBoxSetState,
physics state, bitfield reading), vendor open/close events, automatic
object identification service, int property appraisal caching, container
item counts, and property update hooks. Cleans up verbose inventory logging.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
tombohar 2026-04-14 20:24:46 -04:00
commit ccb08ecb4a
19 changed files with 1292 additions and 7 deletions

View file

@ -57,6 +57,8 @@ internal static class AppraisalHooks
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)
@ -86,6 +88,21 @@ internal static class AppraisalHooks
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).
@ -175,6 +192,15 @@ internal static class AppraisalHooks
_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);
@ -205,6 +231,48 @@ internal static class AppraisalHooks
return result;
}
private static void CacheIntProps(uint guid, IntPtr profilePtr)
{
if (profilePtr == IntPtr.Zero)
return;
// AppraisalProfile._intStatsTable* is at offset +0x18
IntPtr intTablePtr = Marshal.ReadIntPtr(profilePtr + 0x18);
if (intTablePtr == IntPtr.Zero)
return;
// PackableHashTable<uint,int>: bucket_array at +0x8, bucket_count at +0xC
IntPtr bucketArray = Marshal.ReadIntPtr(intTablePtr + 0x08);
int bucketCount = Marshal.ReadInt32(intTablePtr + 0x0C);
if (bucketArray == IntPtr.Zero || bucketCount <= 0 || bucketCount > 65536)
return;
var props = new Dictionary<uint, int>(8);
for (int i = 0; i < bucketCount; i++)
{
IntPtr node = Marshal.ReadIntPtr(bucketArray + i * 4);
while (node != IntPtr.Zero)
{
uint key = (uint)Marshal.ReadInt32(node);
int val = Marshal.ReadInt32(node + 4);
props[key] = val;
node = Marshal.ReadIntPtr(node + 8);
}
}
if (props.Count == 0)
return;
lock (_cacheLock)
{
_intCache[guid] = props;
}
RynthLog.Compat($"Compat: cached {props.Count} int prop(s) for guid=0x{guid:X8}");
}
private static void CacheBoolProps(uint guid, IntPtr profilePtr)
{
if (profilePtr == IntPtr.Zero)

View file

@ -0,0 +1,92 @@
// ============================================================================
// 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.Compat("Compat: AutoIdService started.");
}
/// <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 _);
}
private static void DrainTick(object? state)
{
try
{
if (!CombatActionHooks.HasRequestId)
return;
int sent = 0;
while (sent < MaxPerTick && _queue.TryDequeue(out uint objectId))
{
// Object may have been destroyed between enqueue and drain
if (objectId == 0)
continue;
ClientActionHooks.RequestId(objectId);
sent++;
}
}
catch { }
}
}

View file

@ -6,6 +6,14 @@ namespace RynthCore.Engine.Compatibility;
internal static class ClientObjectHooks
{
private const int ReferenceGetWeenieObject = 0x005583F0;
// ACCWeenieObject::GetNumContainedItems() — ThisCall, no args, returns int
// Source: Chorizite Weenie.cs (0x0058CCE0)
private const int ReferenceGetNumContainedItems = 0x0058CCE0;
// ACCWeenieObject::GetNumContainedContainers() — ThisCall, no args, returns int
// Source: Chorizite Weenie.cs (0x0058CCF0)
private const int ReferenceGetNumContainedContainers = 0x0058CCF0;
private const int ReferenceGetObjectNameStatic = 0x0058F840;
private const int ReferenceGetObjectNameInstance = 0x0058F510;
@ -242,7 +250,7 @@ internal static class ClientObjectHooks
/// Checks if a pointer's memory page is committed and readable via VirtualQuery.
/// Critical for NativeAOT where try/catch does NOT catch access violations.
/// </summary>
private static bool IsReadablePointer(IntPtr ptr)
internal static bool IsReadablePointer(IntPtr ptr)
{
if (ptr == IntPtr.Zero)
return false;
@ -746,6 +754,39 @@ internal static class ClientObjectHooks
}
}
/// <summary>
/// Reads PublicWeenieDesc._bitfield from the weenie struct.
/// Returns the ObjectDescriptionFlags bitfield (e.g. BF_DOOR = 0x1000).
/// Layout: PublicWeenieDesc+104 = _bitfield (26 × 4-byte fields from start).
/// </summary>
public static bool TryGetObjectBitfield(uint objectId, out uint bitfield)
{
bitfield = 0;
if (_getWeenieObject == null)
{
if (!Probe() || _getWeenieObject == null)
return false;
}
if (_weeniePhysicsObjOffset < 0)
return false;
try
{
IntPtr weeniePtr = _getWeenieObject(objectId);
if (weeniePtr == IntPtr.Zero)
return false;
int pwdBase = _weeniePhysicsObjOffset + 4;
IntPtr fieldAddr = weeniePtr + pwdBase + 104;
if (!IsReadablePointer(fieldAddr))
return false;
bitfield = (uint)Marshal.ReadInt32(fieldAddr);
return true;
}
catch
{
return false;
}
}
private static bool TryGetObjectQualitiesPtr(uint objectId, out IntPtr qualitiesPtr)
{
qualitiesPtr = IntPtr.Zero;
@ -863,6 +904,11 @@ internal static class ClientObjectHooks
public static unsafe bool TryGetObjectIntProperty(uint objectId, uint stype, out int value)
{
value = 0;
// Appraisal cache covers objects where m_pQualities is null (doors, inventory items, etc.)
if (AppraisalHooks.TryGetCachedIntProperty(objectId, stype, out value))
return true;
if (_getWeenieObject == null)
{
if (!Probe() || _getWeenieObject == null)
@ -937,6 +983,12 @@ internal static class ClientObjectHooks
value = retval;
return true;
}
// Fallback: network property cache (covers static world objects like doors
// where m_pQualities is null and InqInt returns 0).
if (PropertyUpdateHooks.TryGetCachedIntProperty(objectId, stype, out value))
return true;
return false;
}
catch
@ -1126,7 +1178,13 @@ internal static class ClientObjectHooks
int result = _inqBool(baseQualitiesPtr, stype, &retval);
if (result == 0)
{
// Fallback: network property cache (covers static world objects like doors
// where m_pQualities is null and InqBool returns 0).
if (PropertyUpdateHooks.TryGetCachedBoolProperty(objectId, stype, out value))
return true;
return false;
}
value = retval != 0;
return true;
@ -1347,6 +1405,46 @@ internal static class ClientObjectHooks
}
}
// CPhysicsObj::m_state offset — confirmed from Ghidra set_state disasm: MOV [ESI+0xa8], EAX
private const int PhysicsStateOffset = 0xA8;
/// <summary>
/// Reads CPhysicsObj::m_state directly from memory.
/// Notable bits: ETHEREAL_PS=0x4 (door open/passable), STATIC_PS=0x1, NODRAW_PS=0x20.
/// </summary>
public static bool TryGetObjectPhysicsState(uint objectId, out uint state)
{
state = 0;
if (_weeniePhysicsObjOffset < 0)
{
ProbePhysObjOffset();
if (_weeniePhysicsObjOffset < 0)
return false;
}
if (!TryGetWeenieObjectPtr(objectId, out IntPtr weeniePtr))
return false;
try
{
IntPtr physicsObj = Marshal.ReadIntPtr(weeniePtr + _weeniePhysicsObjOffset);
if (physicsObj == IntPtr.Zero)
return false;
IntPtr vtable = Marshal.ReadIntPtr(physicsObj);
if (!SmartBoxLocator.IsPointerInModule(vtable))
return false;
state = unchecked((uint)Marshal.ReadInt32(physicsObj + PhysicsStateOffset));
return true;
}
catch
{
return false;
}
}
/// <summary>
/// Reads an object's facing heading (0–360°, clockwise, 0=North) from its CPhysicsObj quaternion.
/// Same qw/qz offsets as the player position struct.
@ -1451,6 +1549,48 @@ internal static class ClientObjectHooks
}
}
/// <summary>
/// Calls ACCWeenieObject::GetNumContainedItems() — the AC client's own count of
/// items in the container. Returns -1 if the weenie is unavailable.
/// </summary>
public static int GetNumContainedItems(uint objectId)
{
if (_getWeenieObject == null && !Probe())
return -1;
if (_getWeenieObject == null)
return -1;
IntPtr weeniePtr = _getWeenieObject(objectId);
if (weeniePtr == IntPtr.Zero)
return -1;
unsafe
{
return ((delegate* unmanaged[Thiscall]<IntPtr, int>)new IntPtr(ReferenceGetNumContainedItems))(weeniePtr);
}
}
/// <summary>
/// Calls ACCWeenieObject::GetNumContainedContainers() — the AC client's own count of
/// how many packs/foci occupy container slots. Returns -1 if the weenie is unavailable.
/// </summary>
public static int GetNumContainedContainers(uint objectId)
{
if (_getWeenieObject == null && !Probe())
return -1;
if (_getWeenieObject == null)
return -1;
IntPtr weeniePtr = _getWeenieObject(objectId);
if (weeniePtr == IntPtr.Zero)
return -1;
unsafe
{
return ((delegate* unmanaged[Thiscall]<IntPtr, int>)new IntPtr(ReferenceGetNumContainedContainers))(weeniePtr);
}
}
private static void LogLookup(string message)
{
if (_lookupLogCount >= MaxLookupLogs)

View file

@ -79,6 +79,7 @@ internal static class CreateObjectHooks
RynthLog.Compat($"Compat: create object #{count} id=0x{objectId:X8} ptr=0x{result.ToInt32():X8}");
PluginManager.QueueCreateObject(objectId);
AutoIdService.Enqueue(objectId);
return result;
}
}

View file

@ -70,7 +70,10 @@ internal static class DeleteObjectHooks
private static int DeleteObjectDetour(IntPtr thisPtr, uint objectId)
{
if (objectId != 0)
{
PluginManager.QueueDeleteObject(objectId);
AutoIdService.Evict(objectId);
}
return _originalDeleteObject!(thisPtr, objectId);
}

View file

@ -0,0 +1,146 @@
// ============================================================================
// 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.
//
// VA derivation (map_offset + 0x00401000 = live VA):
// 0010FAF0 CPhysicsObj::DoMotion → 0x00510AF0
// ============================================================================
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
{
// CPhysicsObj::DoMotion(uint motion, MovementParameters* params, int sendEvent) — thiscall
// Map: 0010FAF0 → live VA: 0x00510AF0
private const int DoMotionVa = 0x00510AF0;
// Door motion commands (AC1Legacy Command enum)
private const uint MotionOn = 0x4000000B; // door opens
private const uint MotionOff = 0x4000000C; // door closes
// CPhysicsObj::weenie_obj pointer at +0x128
// Calculated from CPhysicsObj struct layout (confirmed against PhysicsPositionOffset = 0x48).
private const int WeenieObjOffset = 0x128;
// Object ID inside ACCWeenieObject (HashBaseData<UInt32>): vfptr(4) + hash_next*(4) + id(4) = offset 8
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; // held alive to prevent GC
private static bool _hookInstalled;
private static string _statusMessage = "Not initialized.";
// Per-object motion state: true = On (open/activated), false = Off (closed/deactivated).
// Only populated for objects that have had an On or Off motion applied since injection.
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;
}
int funcOff = DoMotionVa - textSection.TextBaseVa;
if (funcOff < 0 || funcOff >= textSection.Bytes.Length)
{
_statusMessage = $"CPhysicsObj::DoMotion VA out of range @ 0x{DoMotionVa:X8}.";
RynthLog.Compat($"Compat: do-motion hook failed - {_statusMessage}");
return;
}
byte firstByte = textSection.Bytes[funcOff];
if (firstByte is 0x00 or 0xCC or 0xC3)
{
_statusMessage = $"CPhysicsObj::DoMotion looks invalid @ 0x{DoMotionVa:X8} (opcode 0x{firstByte:X2}).";
RynthLog.Compat($"Compat: do-motion hook failed - {_statusMessage}");
return;
}
try
{
IntPtr targetAddress = new IntPtr(textSection.TextBaseVa + funcOff);
_doMotionDetour = DoMotionDetour;
IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_doMotionDetour);
_originalDoMotion = Marshal.GetDelegateForFunctionPointer<DoMotionDelegate>(
MinHook.HookCreate(targetAddress, detourPtr));
Thread.MemoryBarrier();
MinHook.Enable(targetAddress);
_hookInstalled = true;
_statusMessage = $"Hooked CPhysicsObj::DoMotion @ 0x{targetAddress.ToInt32():X8}.";
RynthLog.Compat($"Compat: do-motion hook ready @ 0x{targetAddress.ToInt32():X8}, firstByte=0x{firstByte:X2}");
}
catch (Exception ex)
{
_statusMessage = ex.Message;
RynthLog.Compat($"Compat: do-motion hook failed - {ex.Message}");
}
}
/// <summary>
/// Returns the last observed On/Off motion state for the given object ID.
/// Returns false (not found) if this object has never had an On or Off motion since injection.
/// </summary>
public static bool TryGetObjectMotionOn(uint objectId, out bool isOn)
{
return _objectOnState.TryGetValue(objectId, out isOn);
}
private static uint DoMotionDetour(IntPtr thisPtr, uint motion, IntPtr paramsPtr, int sendEvent)
{
try
{
if (thisPtr != IntPtr.Zero && (motion == MotionOn || motion == MotionOff))
{
uint objectId = ReadWeenieId(thisPtr);
if (objectId != 0)
_objectOnState[objectId] = motion == MotionOn;
}
}
catch { }
return _originalDoMotion!(thisPtr, motion, paramsPtr, sendEvent);
}
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,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.Compat($"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.Compat($"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.Compat($"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,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.Compat("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.Compat($"SetState#{n} obj=0x{objectId:X8} state=0x{newState:X8}");
}
catch { }
return _originalHandleSetState!(thisPtr, blobPtr, objectId, newState, timestampsPtr);
}
}

View file

@ -168,8 +168,6 @@ internal static class UpdateObjectInventoryHooks
private static int GetContainerContents(uint containerId, Span<uint> itemIds)
{
RynthLog.Compat($"Compat: GetContainerContents ENTER id=0x{containerId:X8} maxCount={itemIds.Length}");
if (containerId == 0 || itemIds.Length == 0)
return 0;
@ -198,7 +196,6 @@ internal static class UpdateObjectInventoryHooks
itemIds[written++] = id;
}
RynthLog.Compat($"Compat: ScanByContainerId(0x{containerId:X8}) found {written} item(s) in 0x8000xxxx range.");
return written;
}
@ -215,13 +212,11 @@ internal static class UpdateObjectInventoryHooks
if (itemId != 0)
{
dest[written++] = itemId;
RynthLog.Compat($"Compat: {label}[{written - 1}] = 0x{itemId:X8}");
}
node = Marshal.ReadIntPtr(node + 0x08); // next node
}
RynthLog.Compat($"Compat: GetContainerContents(0x{containerId:X8}) walked {walked} {label} node(s), wrote {written}.");
return written;
}

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 entry bytes (from Ghidra)
private static readonly byte[] OpenVendorSignature =
[
0x83, 0xEC, 0x2C, 0x53, 0x55, 0x56, 0x57 // SUB ESP,2C; PUSH EBX; PUSH EBP; PUSH ESI; PUSH EDI
];
private static readonly byte[] CloseVendorSignature =
[
0x8A, 0x44, 0x24, 0x04, 0x84, 0xC0, 0x75 // 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;
}
int openOff = RecvNoticeOpenVendorVa - textSection.TextBaseVa;
int closeOff = RecvNoticeCloseVendorVa - textSection.TextBaseVa;
if (!PatternScanner.VerifyBytes(textSection.Bytes, openOff, OpenVendorSignature))
{
_statusMessage = $"RecvNotice_OpenVendor signature mismatch @ 0x{RecvNoticeOpenVendorVa:X8}.";
RynthLog.Compat($"Compat: vendor hooks failed - {_statusMessage}");
return;
}
if (!PatternScanner.VerifyBytes(textSection.Bytes, closeOff, CloseVendorSignature))
{
_statusMessage = $"RecvNotice_CloseVendor signature mismatch @ 0x{RecvNoticeCloseVendorVa:X8}.";
RynthLog.Compat($"Compat: vendor hooks failed - {_statusMessage}");
return;
}
try
{
_openAddress = new IntPtr(textSection.TextBaseVa + openOff);
_openDetour = OpenVendorDetour;
IntPtr openPtr = Marshal.GetFunctionPointerForDelegate(_openDetour);
_originalOpen = Marshal.GetDelegateForFunctionPointer<RecvNoticeOpenVendorDelegate>(
MinHook.HookCreate(_openAddress, openPtr));
_closeAddress = new IntPtr(textSection.TextBaseVa + closeOff);
_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.Compat($"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

@ -272,6 +272,8 @@ public static class EntryPoint
RunInitStep("combat-mode hooks", CombatModeHooks.Initialize);
RunInitStep("teleport-state hooks", TeleportStateHooks.Initialize);
RunInitStep("salvage hooks", SalvageHooks.Initialize);
RunInitStep("do-motion hooks", DoMotionHooks.Initialize);
RunInitStep("smartbox-setstate hooks", SmartBoxSetStateHooks.Initialize);
RunInitStep("appraisal hooks", AppraisalHooks.Initialize);
RunInitStep("account hooks", AccountHooks.Initialize);
RunInitStep("client combat hooks", () => ClientCombatHooks.Probe());
@ -286,8 +288,11 @@ public static class EntryPoint
RunInitStep("vector-update hooks", VectorUpdateServerDispatchHooks.Initialize);
RunInitStep("update-object-inventory hooks", UpdateObjectInventoryHooks.Initialize);
RunInitStep("view-object-contents hooks", ViewObjectContentsHooks.Initialize);
RunInitStep("vendor hooks", VendorHooks.Initialize);
RunInitStep("chat callback hooks", ChatCallbackHooks.Initialize);
RunInitStep("raw packet hooks", RawPacketHooks.Initialize);
RunInitStep("property-update hooks", PropertyUpdateHooks.Initialize);
RunInitStep("auto-id service", AutoIdService.Start);
PluginManager.LoadPlugins(engineDir);
// Defer D3D9 hooking until after character login. By that point
@ -340,6 +345,11 @@ public static class EntryPoint
RecentLogLines.Enqueue(line);
while (RecentLogLines.Count > MaxRecentLogLines)
RecentLogLines.Dequeue();
string logPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
"RynthCore.log");
File.AppendAllText(logPath, line + "\n");
}
}
catch

View file

@ -37,6 +37,8 @@ internal sealed class LoadedPlugin
public PluginOnUpdateObjectInventoryDelegate? OnUpdateObjectInventory { get; set; }
public PluginOnViewObjectContentsDelegate? OnViewObjectContents { get; set; }
public PluginOnStopViewingObjectContentsDelegate? OnStopViewingObjectContents { get; set; }
public PluginOnVendorOpenDelegate? OnVendorOpen { get; set; }
public PluginOnVendorCloseDelegate? OnVendorClose { get; set; }
public IntPtr OnUpdateHealthPtr { get; set; }
public PluginOnUpdateHealthDelegate? OnUpdateHealth { get; set; }
public IntPtr OnChatWindowTextPtr { get; set; }

View file

@ -101,6 +101,12 @@ internal struct RynthCoreAPI
/// <summary>Function pointer: uint GetGroundContainerId()</summary>
public IntPtr GetGroundContainerIdFn;
/// <summary>Function pointer: int GetNumContainedItems(uint objectId)</summary>
public IntPtr GetNumContainedItemsFn;
/// <summary>Function pointer: int GetNumContainedContainers(uint objectId)</summary>
public IntPtr GetNumContainedContainersFn;
/// <summary>Function pointer: int GetCurCoords(double* northSouth, double* eastWest)</summary>
public IntPtr GetCurCoordsFn;
@ -428,6 +434,22 @@ internal struct RynthCoreAPI
/// Reads a primary attribute via InqAttribute. raw=0→buffed, raw=1→base.
/// stype: 1=Strength, 2=Endurance, 3=Quickness, 4=Coordination, 5=Focus, 6=Self.</summary>
public IntPtr GetObjectAttributeFn;
/// <summary>Function pointer: int GetObjectMotionOn(uint objectId, int* isOn)
/// Returns 1 if a DoMotion On/Off state is known for the object; isOn is 1 if On (open), 0 if Off (closed).
/// Returns 0 if no motion state has been observed for this object since injection.</summary>
public IntPtr GetObjectMotionOnFn;
/// <summary>Function pointer: int GetObjectState(uint objectId, uint* state)
/// Returns 1 if a PhysicsState has been received from the server for this object; state is the raw bitfield.
/// Returns 0 if no SetState message has been observed for this object since injection.</summary>
public IntPtr GetObjectStateFn;
/// <summary>Function pointer: uint GetObjectBitfield(uint objectId)
/// Returns the PublicWeenieDesc._bitfield (ObjectDescriptionFlags) for the given object.
/// BF_DOOR = 0x1000, BF_VENDOR = 0x200, BF_CORPSE = 0x2000, etc.
/// Returns 0 if the object is not found.</summary>
public IntPtr GetObjectBitfieldFn;
}
@ -435,7 +457,7 @@ internal struct RynthCoreAPI
/// <summary>Current API version. Bump when adding fields to RynthCoreAPI.</summary>
internal static class PluginContractVersion
{
public const uint Current = 46;
public const uint Current = 49;
}
internal static class ClientActionHookFlags
@ -512,6 +534,12 @@ internal delegate void PluginOnViewObjectContentsDelegate(uint objectId);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void PluginOnStopViewingObjectContentsDelegate(uint objectId);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void PluginOnVendorOpenDelegate(uint vendorId);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void PluginOnVendorCloseDelegate(uint vendorId);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void PluginOnUpdateHealthDelegate(uint targetId, float healthRatio, uint currentHealth, uint maxHealth);
@ -801,3 +829,12 @@ internal unsafe delegate int GetObjectSkillLevelCallbackDelegate(uint objectId,
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetObjectAttributeCallbackDelegate(uint objectId, uint stype, int raw, uint* value);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetObjectMotionOnCallbackDelegate(uint objectId, int* isOn);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal unsafe delegate int GetObjectStateCallbackDelegate(uint objectId, uint* state);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate uint GetObjectBitfieldCallbackDelegate(uint objectId);

View file

@ -219,6 +219,14 @@ internal static class PluginLoader
if (onStopViewingObjectContentsPtr != IntPtr.Zero)
plugin.OnStopViewingObjectContents = Marshal.GetDelegateForFunctionPointer<PluginOnStopViewingObjectContentsDelegate>(onStopViewingObjectContentsPtr);
IntPtr onVendorOpenPtr = GetProcAddress(handle, "RynthPluginOnVendorOpen");
if (onVendorOpenPtr != IntPtr.Zero)
plugin.OnVendorOpen = Marshal.GetDelegateForFunctionPointer<PluginOnVendorOpenDelegate>(onVendorOpenPtr);
IntPtr onVendorClosePtr = GetProcAddress(handle, "RynthPluginOnVendorClose");
if (onVendorClosePtr != IntPtr.Zero)
plugin.OnVendorClose = Marshal.GetDelegateForFunctionPointer<PluginOnVendorCloseDelegate>(onVendorClosePtr);
IntPtr onUpdateHealthPtr = GetProcAddress(handle, "RynthPluginOnUpdateHealth");
if (onUpdateHealthPtr != IntPtr.Zero)
{
@ -356,6 +364,8 @@ internal static class PluginLoader
if (p.OnUpdateObjectInventory != null) parts.Add("inventory");
if (p.OnViewObjectContents != null) parts.Add("contents-open");
if (p.OnStopViewingObjectContents != null) parts.Add("contents-close");
if (p.OnVendorOpen != null) parts.Add("vendor-open");
if (p.OnVendorClose != null) parts.Add("vendor-close");
if (p.OnUpdateHealth != null || p.OnUpdateHealthPtr != IntPtr.Zero) parts.Add("health");
if (p.OnChatWindowText != null) parts.Add("chat-in");
if (p.OnChatBarEnter != null) parts.Add("chat-out");

View file

@ -27,6 +27,8 @@ internal static class PluginManager
private readonly record struct PendingUpdateObjectInventory(uint ObjectId);
private readonly record struct PendingViewObjectContents(uint ObjectId);
private readonly record struct PendingStopViewingObjectContents(uint ObjectId);
private readonly record struct PendingVendorOpen(uint VendorId);
private readonly record struct PendingVendorClose(uint VendorId);
private readonly record struct PendingUpdateHealth(uint TargetId, float HealthRatio, uint CurrentHealth, uint MaxHealth);
private readonly record struct PendingEnchantmentAdded(uint SpellId, double DurationSeconds);
private readonly record struct PendingEnchantmentRemoved(uint EnchantmentId);
@ -44,6 +46,8 @@ internal static class PluginManager
private const int MaxPendingUpdateObjectInventory = 128;
private const int MaxPendingViewObjectContents = 128;
private const int MaxPendingStopViewingObjectContents = 128;
private const int MaxPendingVendorOpen = 32;
private const int MaxPendingVendorClose = 32;
private const int MaxPendingUpdateHealth = 512;
private const int MaxPendingEnchantmentEvents = 256;
private const int MaxPrePluginCreateObjects = 4096;
@ -63,6 +67,8 @@ internal static class PluginManager
private static readonly Queue<PendingUpdateObjectInventory> _pendingUpdateObjectInventory = new();
private static readonly Queue<PendingViewObjectContents> _pendingViewObjectContents = new();
private static readonly Queue<PendingStopViewingObjectContents> _pendingStopViewingObjectContents = new();
private static readonly Queue<PendingVendorOpen> _pendingVendorOpen = new();
private static readonly Queue<PendingVendorClose> _pendingVendorClose = new();
private static readonly Queue<PendingUpdateHealth> _pendingUpdateHealth = new();
private static readonly Queue<PendingEnchantmentAdded> _pendingEnchantmentAdded = new();
private static readonly Queue<PendingEnchantmentRemoved> _pendingEnchantmentRemoved = new();
@ -78,6 +84,8 @@ internal static class PluginManager
private static readonly object PendingUpdateObjectInventoryLock = new();
private static readonly object PendingViewObjectContentsLock = new();
private static readonly object PendingStopViewingObjectContentsLock = new();
private static readonly object PendingVendorOpenLock = new();
private static readonly object PendingVendorCloseLock = new();
private static readonly object PendingUpdateHealthLock = new();
private static readonly object PendingEnchantmentAddedLock = new();
private static readonly object PendingEnchantmentRemovedLock = new();
@ -116,6 +124,8 @@ internal static class PluginManager
private static GetItemIdCallbackDelegate? _getPreviousSelectedItemIdCallback;
private static GetItemIdCallbackDelegate? _getPlayerIdCallback;
private static GetItemIdCallbackDelegate? _getGroundContainerIdCallback;
private static QueryHealthCallbackDelegate? _getNumContainedItemsCallback;
private static QueryHealthCallbackDelegate? _getNumContainedContainersCallback;
private static GetCurCoordsCallbackDelegate? _getCurCoordsCallback;
private static UseObjectCallbackDelegate? _useObjectCallback;
private static UseObjectOnCallbackDelegate? _useObjectOnCallback;
@ -174,6 +184,9 @@ internal static class PluginManager
private static GetObjectSpellIdsCallbackDelegate? _getObjectSpellIdsCallback;
private static GetObjectSkillLevelCallbackDelegate? _getObjectSkillBuffedCallback;
private static GetObjectAttributeCallbackDelegate? _getObjectAttributeCallback;
private static GetObjectMotionOnCallbackDelegate? _getObjectMotionOnCallback;
private static GetObjectStateCallbackDelegate? _getObjectStateCallback;
private static GetObjectBitfieldCallbackDelegate? _getObjectBitfieldCallback;
private static IntPtr _accountNameScratchPtr;
private static IntPtr _worldNameScratchPtr;
[ThreadStatic] private static IntPtr _objectNameScratchPtr;
@ -276,6 +289,8 @@ internal static class PluginManager
DispatchQueuedSmartBoxEvent();
DispatchQueuedStopViewingObjectContents();
DispatchQueuedViewObjectContents();
DispatchQueuedVendorOpen();
DispatchQueuedVendorClose();
DispatchQueuedUpdateObjectInventory();
DispatchQueuedCreateObject();
DispatchQueuedUpdateObject();
@ -525,6 +540,34 @@ internal static class PluginManager
}
}
public static void QueueVendorOpen(uint vendorId)
{
if (_plugins.Count == 0)
return;
lock (PendingVendorOpenLock)
{
if (_pendingVendorOpen.Count >= MaxPendingVendorOpen)
_pendingVendorOpen.Dequeue();
_pendingVendorOpen.Enqueue(new PendingVendorOpen(vendorId));
}
}
public static void QueueVendorClose(uint vendorId)
{
if (_plugins.Count == 0)
return;
lock (PendingVendorCloseLock)
{
if (_pendingVendorClose.Count >= MaxPendingVendorClose)
_pendingVendorClose.Dequeue();
_pendingVendorClose.Enqueue(new PendingVendorClose(vendorId));
}
}
public static void QueueUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth)
{
if (_plugins.Count == 0)
@ -1257,6 +1300,78 @@ internal static class PluginManager
}
}
private static void DispatchQueuedVendorOpen()
{
if (!_initialized || _plugins.Count == 0)
return;
PendingVendorOpen[] pending;
lock (PendingVendorOpenLock)
{
if (_pendingVendorOpen.Count == 0)
return;
pending = _pendingVendorOpen.ToArray();
_pendingVendorOpen.Clear();
}
foreach (PendingVendorOpen evt in pending)
{
for (int i = 0; i < _plugins.Count; i++)
{
var plugin = _plugins[i];
if (!plugin.Initialized || plugin.Failed || plugin.OnVendorOpen == null)
continue;
try
{
plugin.OnVendorOpen(evt.VendorId);
}
catch (Exception ex)
{
plugin.Failed = true;
RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnVendorOpen threw {ex.GetType().Name}: {ex.Message}");
}
}
}
}
private static void DispatchQueuedVendorClose()
{
if (!_initialized || _plugins.Count == 0)
return;
PendingVendorClose[] pending;
lock (PendingVendorCloseLock)
{
if (_pendingVendorClose.Count == 0)
return;
pending = _pendingVendorClose.ToArray();
_pendingVendorClose.Clear();
}
foreach (PendingVendorClose evt in pending)
{
for (int i = 0; i < _plugins.Count; i++)
{
var plugin = _plugins[i];
if (!plugin.Initialized || plugin.Failed || plugin.OnVendorClose == null)
continue;
try
{
plugin.OnVendorClose(evt.VendorId);
}
catch (Exception ex)
{
plugin.Failed = true;
RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnVendorClose threw {ex.GetType().Name}: {ex.Message}");
}
}
}
}
private static void DispatchQueuedUpdateHealth()
{
if (!_initialized || _plugins.Count == 0)
@ -1546,6 +1661,8 @@ internal static class PluginManager
_getPreviousSelectedItemIdCallback ??= GetPreviousSelectedItemId;
_getPlayerIdCallback ??= GetPlayerId;
_getGroundContainerIdCallback ??= GetGroundContainerId;
_getNumContainedItemsCallback ??= GetNumContainedItemsAction;
_getNumContainedContainersCallback ??= GetNumContainedContainersAction;
_getCurCoordsCallback ??= GetCurCoords;
_useObjectCallback ??= UseObject;
_useObjectOnCallback ??= UseObjectOn;
@ -1604,6 +1721,9 @@ internal static class PluginManager
_getObjectSpellIdsCallback ??= GetObjectSpellIdsAction;
_getObjectSkillBuffedCallback ??= GetObjectSkillLevelAction;
_getObjectAttributeCallback ??= GetObjectAttributeAction;
_getObjectMotionOnCallback ??= GetObjectMotionOnAction;
_getObjectStateCallback ??= GetObjectStateAction;
_getObjectBitfieldCallback ??= GetObjectBitfieldAction;
_api.Version = PluginContractVersion.Current;
_api.LogFn = Marshal.GetFunctionPointerForDelegate(_logCallback);
@ -1631,6 +1751,8 @@ internal static class PluginManager
_api.GetPreviousSelectedItemIdFn = Marshal.GetFunctionPointerForDelegate(_getPreviousSelectedItemIdCallback);
_api.GetPlayerIdFn = Marshal.GetFunctionPointerForDelegate(_getPlayerIdCallback);
_api.GetGroundContainerIdFn = Marshal.GetFunctionPointerForDelegate(_getGroundContainerIdCallback);
_api.GetNumContainedItemsFn = Marshal.GetFunctionPointerForDelegate(_getNumContainedItemsCallback);
_api.GetNumContainedContainersFn = Marshal.GetFunctionPointerForDelegate(_getNumContainedContainersCallback);
_api.GetCurCoordsFn = Marshal.GetFunctionPointerForDelegate(_getCurCoordsCallback);
_api.UseObjectFn = Marshal.GetFunctionPointerForDelegate(_useObjectCallback);
_api.UseObjectOnFn = Marshal.GetFunctionPointerForDelegate(_useObjectOnCallback);
@ -1689,6 +1811,9 @@ internal static class PluginManager
_api.GetObjectSpellIdsFn = Marshal.GetFunctionPointerForDelegate(_getObjectSpellIdsCallback);
_api.GetObjectSkillBuffedFn = Marshal.GetFunctionPointerForDelegate(_getObjectSkillBuffedCallback);
_api.GetObjectAttributeFn = Marshal.GetFunctionPointerForDelegate(_getObjectAttributeCallback);
_api.GetObjectMotionOnFn = Marshal.GetFunctionPointerForDelegate(_getObjectMotionOnCallback);
_api.GetObjectStateFn = Marshal.GetFunctionPointerForDelegate(_getObjectStateCallback);
_api.GetObjectBitfieldFn = Marshal.GetFunctionPointerForDelegate(_getObjectBitfieldCallback);
}
private static void ProbeClientHooks()
@ -1938,6 +2063,22 @@ internal static class PluginManager
return 1;
}
private static unsafe int GetObjectMotionOnAction(uint objectId, int* isOn)
{
if (!DoMotionHooks.TryGetObjectMotionOn(objectId, out bool v))
return 0;
*isOn = v ? 1 : 0;
return 1;
}
private static unsafe int GetObjectStateAction(uint objectId, uint* state)
{
if (!ClientObjectHooks.TryGetObjectPhysicsState(objectId, out uint s))
return 0;
*state = s;
return 1;
}
private static unsafe int ReadPlayerEnchantmentsAction(uint* spellIds, double* expiryTimes, int maxCount)
{
return EnchantmentHooks.ReadPlayerEnchantments(spellIds, expiryTimes, maxCount);
@ -2079,6 +2220,16 @@ internal static class PluginManager
return ClientHelperHooks.GetGroundContainerId();
}
private static int GetNumContainedItemsAction(uint objectId)
{
return ClientObjectHooks.GetNumContainedItems(objectId);
}
private static int GetNumContainedContainersAction(uint objectId)
{
return ClientObjectHooks.GetNumContainedContainers(objectId);
}
private static unsafe int GetCurCoords(double* northSouth, double* eastWest)
{
if (northSouth == null || eastWest == null)
@ -2184,6 +2335,11 @@ internal static class PluginManager
return ClientObjectHooks.TryGetObjectWcid(objectId, out uint wcid) ? wcid : 0u;
}
private static uint GetObjectBitfieldAction(uint objectId)
{
return ClientObjectHooks.TryGetObjectBitfield(objectId, out uint bitfield) ? bitfield : 0u;
}
private static int HasAppraisalDataAction(uint objectId)
{
return AppraisalHooks.HasAppraisalData(objectId) ? 1 : 0;