From c2ca425f87897647e5cdebebe269dc677862fb98 Mon Sep 17 00:00:00 2001 From: tombohar Date: Sun, 12 Apr 2026 00:27:17 -0400 Subject: [PATCH] Add salvage, appraisal, account, teleport hooks and expand engine API New hooks: - AppraisalHooks: hook CM_Examine::SendNotice_SetAppraiseInfo (0x006B05B0) to cache bool properties from server appraisal data; fixes wobjectgetboolprop returning 0 for inventory items whose m_pQualities is null in client memory - SalvageHooks: hook gmSalvageUI::OpenSalvagePanel to capture singleton instance for use by SalvagePanelAddItem and SalvagePanelExecute - AccountHooks: capture account name and world/server name from login flow - TeleportStateHooks: track teleport/portal state via SmartBox ClientObjectHooks: check AppraisalHooks cache before CBaseQualities::InqBool in TryGetObjectBoolProperty so identified inventory items return correct values API v40 additions (PluginContract / PluginManager / PluginSdk): - GetCurrentCombatMode: direct read from ClientCombatSystem without hook - SalvagePanelOpen / SalvagePanelAddItem / SalvagePanelExecute - GetVitae: reads vitae multiplier via CACQualities::GetVitaeValue - GetAccountName / GetWorldName - GetObjectWcid: reads PublicWeenieDesc._wcid fast path Co-Authored-By: Claude Sonnet 4.6 --- .../Compatibility/AccountHooks.cs | 271 ++++++++++++++++++ .../Compatibility/AppraisalHooks.cs | 184 ++++++++++++ .../Compatibility/ClientHelperHooks.cs | 108 +++++++ .../Compatibility/ClientObjectHooks.cs | 135 ++++++++- .../Compatibility/CombatModeHooks.cs | 27 ++ .../Compatibility/SalvageHooks.cs | 100 +++++++ .../Compatibility/TeleportStateHooks.cs | 46 +++ src/RynthCore.Engine/EntryPoint.cs | 4 + .../Plugins/PluginContract.cs | 91 +++++- src/RynthCore.Engine/Plugins/PluginManager.cs | 126 ++++++++ src/RynthCore.PluginSdk/RynthCoreApiNative.cs | 9 + src/RynthCore.PluginSdk/RynthCoreHost.cs | 72 ++++- 12 files changed, 1161 insertions(+), 12 deletions(-) create mode 100644 src/RynthCore.Engine/Compatibility/AccountHooks.cs create mode 100644 src/RynthCore.Engine/Compatibility/AppraisalHooks.cs create mode 100644 src/RynthCore.Engine/Compatibility/SalvageHooks.cs create mode 100644 src/RynthCore.Engine/Compatibility/TeleportStateHooks.cs diff --git a/src/RynthCore.Engine/Compatibility/AccountHooks.cs b/src/RynthCore.Engine/Compatibility/AccountHooks.cs new file mode 100644 index 0000000..1cee7c6 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/AccountHooks.cs @@ -0,0 +1,271 @@ +using System; +using System.Runtime.InteropServices; +using System.Threading; +using RynthCore.Engine.Hooking; + +namespace RynthCore.Engine.Compatibility; + +/// +/// 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<char> (4-byte ptr to PSRefBuffer<char>). +/// +/// ECM_Login::SendNotice_WorldName — cdecl, Map: 00292A60 → live VA: 0x00693A60 +/// Called once during login when the server announces the world name. +/// Parameter: AC1Legacy::PStringBase<char> const& — same PSRefBuffer layout as account name. +/// +/// PSRefBuffer<char> 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) +/// +internal static class AccountHooks +{ + private const int ReferenceClientGetInstance = 0x004114C0; + private const int ReferenceClientGetAccountName = 0x00401D90; + private const int SendNoticeWorldNameVa = 0x00693A60; + private const int PStringBufferLenOffset = 8; + private const int PStringBufferDataOffset = 20; + + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate IntPtr ClientGetInstanceDelegate(); + + [UnmanagedFunctionPointer(CallingConvention.ThisCall)] + private delegate IntPtr ClientGetAccountNameDelegate(IntPtr clientPtr); + + // ECM_Login::SendNotice_WorldName(AC1Legacy::PStringBase 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( + new IntPtr(ReferenceClientGetInstance)); + _getAccountName = Marshal.GetDelegateForFunctionPointer( + new IntPtr(ReferenceClientGetAccountName)); + IsInitialized = true; + RynthLog.Compat("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("Compat: world-name hook skipped - acclient.exe not available."); + return; + } + + int funcOff = SendNoticeWorldNameVa - textSection.TextBaseVa; + if (funcOff < 0 || funcOff >= textSection.Bytes.Length) + { + RynthLog.Compat($"Compat: world-name hook failed - VA 0x{SendNoticeWorldNameVa:X8} out of text section range."); + return; + } + + byte firstByte = textSection.Bytes[funcOff]; + if (firstByte is 0x00 or 0xCC or 0xC3) + { + RynthLog.Compat($"Compat: world-name hook failed - invalid opcode 0x{firstByte:X2} @ 0x{SendNoticeWorldNameVa:X8}."); + return; + } + + IntPtr targetAddress = new IntPtr(textSection.TextBaseVa + funcOff); + _sendNoticeWorldNameDetour = SendNoticeWorldNameDetour; + IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_sendNoticeWorldNameDetour); + _originalSendNoticeWorldName = Marshal.GetDelegateForFunctionPointer( + MinHook.HookCreate(targetAddress, detourPtr)); + Thread.MemoryBarrier(); + MinHook.Enable(targetAddress); + + WorldHookInstalled = true; + RynthLog.Compat($"Compat: world-name hook ready - ECM_Login::SendNotice_WorldName @ 0x{targetAddress.ToInt32():X8}."); + } + catch (Exception ex) + { + RynthLog.Compat($"Compat: world-name hook failed - {ex.Message}"); + } + } + + private static byte SendNoticeWorldNameDetour(IntPtr pstringPtr) + { + byte result = 0; + try { result = _originalSendNoticeWorldName!(pstringPtr); } catch { } + + try + { + if (pstringPtr != IntPtr.Zero && IsReadable(pstringPtr)) + { + // AC1Legacy::PStringBase: first field is PSRefBuffer* + IntPtr bufferPtr = Marshal.ReadIntPtr(pstringPtr); + if (bufferPtr != IntPtr.Zero && IsReadable(bufferPtr + PStringBufferDataOffset)) + { + int len = Marshal.ReadInt32(bufferPtr + PStringBufferLenOffset); + if (len > 1) + { + string? name = Marshal.PtrToStringAnsi(bufferPtr + PStringBufferDataOffset, len - 1); + if (!string.IsNullOrEmpty(name)) + { + _cachedWorldName = name; + RynthLog.Compat($"Compat: world name captured - \"{name}\"."); + } + } + } + } + } + catch { } + + return result; + } + + /// + /// Returns the current account name. Result is cached after the first successful read. + /// + 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 — a 4-byte pointer to PSRefBuffer + IntPtr bufferPtr = Marshal.ReadIntPtr(accountIdPtr); + if (bufferPtr == IntPtr.Zero || !IsReadable(bufferPtr + PStringBufferDataOffset)) + return false; + + int len = Marshal.ReadInt32(bufferPtr + PStringBufferLenOffset); + if (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; + } + } + + /// + /// 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. + /// + 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()) == 0) return false; + if (mbi.State != MEM_COMMIT) return false; + if ((mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD)) != 0) return false; + return true; + } +} diff --git a/src/RynthCore.Engine/Compatibility/AppraisalHooks.cs b/src/RynthCore.Engine/Compatibility/AppraisalHooks.cs new file mode 100644 index 0000000..65cab62 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/AppraisalHooks.cs @@ -0,0 +1,184 @@ +// ============================================================================ +// 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 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."; + + // Bool property cache: guid → (stype → value) + private static readonly Dictionary> _boolCache = new(); + private static readonly object _cacheLock = new(); + + public static bool IsInstalled => _hookInstalled; + public static string StatusMessage => _statusMessage; + + /// + /// Returns a bool property from the last server appraisal for this object. + /// Only populated after the player has identified the item (RequestId). + /// + public static bool TryGetCachedBoolProperty(uint guid, uint stype, out bool value) + { + value = false; + lock (_cacheLock) + { + if (!_boolCache.TryGetValue(guid, out Dictionary? 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( + MinHook.HookCreate(targetAddress, detourPtr)); + Thread.MemoryBarrier(); + MinHook.Enable(targetAddress); + + _hookInstalled = true; + _statusMessage = $"Hooked CM_Examine::SendNotice_SetAppraiseInfo @ 0x{targetAddress.ToInt32():X8}."; + RynthLog.Compat($"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); + + 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 { } + } + + return result; + } + + private static void CacheBoolProps(uint guid, IntPtr profilePtr) + { + if (profilePtr == IntPtr.Zero) + return; + + // AppraisalProfile._boolStatsTable* is at offset +0x20 + IntPtr boolTablePtr = Marshal.ReadIntPtr(profilePtr + 0x20); + if (boolTablePtr == IntPtr.Zero) + return; + + // PackableHashTable: bucket_array at +0x8, bucket_count at +0xC + IntPtr bucketArray = Marshal.ReadIntPtr(boolTablePtr + 0x08); + int bucketCount = Marshal.ReadInt32(boolTablePtr + 0x0C); + + if (bucketArray == IntPtr.Zero || bucketCount <= 0 || bucketCount > 65536) + return; + + var props = new Dictionary(4); + + 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 != 0; + node = Marshal.ReadIntPtr(node + 8); + } + } + + if (props.Count == 0) + return; + + lock (_cacheLock) + { + _boolCache[guid] = props; + } + + RynthLog.Compat($"Compat: cached {props.Count} bool prop(s) for guid=0x{guid:X8}"); + } +} diff --git a/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs b/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs index 0ff2e2d..0bda22f 100644 --- a/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs @@ -21,6 +21,21 @@ internal static class ClientHelperHooks [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate byte UseWithTargetEventDelegate(uint objectId, uint targetId); + // CM_Inventory::SendNotice_OpenSalvagePanel(uint toolId) — cdecl + // Map: 002AC4F0 → live VA: 0x006AD4F0 + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] + private delegate byte SendNoticeOpenSalvagePanelDelegate(uint toolId); + + // gmSalvageUI::AddNewItem(uint itemId) — thiscall + // Map: 000CB020 → live VA: 0x004CC020 + [UnmanagedFunctionPointer(CallingConvention.ThisCall)] + private delegate void GmSalvageUIAddNewItemDelegate(IntPtr thisPtr, uint itemId); + + // gmSalvageUI::Salvage(void) — thiscall + // Map: 000CB430 → live VA: 0x004CC430 + [UnmanagedFunctionPointer(CallingConvention.ThisCall)] + private delegate void GmSalvageUISalvageDelegate(IntPtr thisPtr); + [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate void UseEquippedItemDelegate(IntPtr acPlugin, uint sourceObjectId, uint targetObjectId); @@ -87,6 +102,9 @@ internal static class ClientHelperHooks private const int CommunicationSystemVa = 0x00870BE4; private const int AddTextToScrollVa = 0x005649F0; private const int UseWithTargetEventVa = 0x006AD3E0; + private const int SendNoticeOpenSalvagePanelVa = 0x006AD4F0; + private const int GmSalvageUIAddNewItemVa = 0x004CC020; + private const int GmSalvageUISalvageVa = 0x004CC430; private static SetSelectedObjectDelegate? _setSelectedObject; private static UseObjectDelegate? _useObject; @@ -100,6 +118,9 @@ internal static class ClientHelperHooks private static GetPlayerIdDelegate? _getPlayerId; private static AddTextToScrollDelegate? _addTextToScroll; private static UseWithTargetEventDelegate? _useWithTargetEvent; + private static SendNoticeOpenSalvagePanelDelegate? _sendNoticeOpenSalvagePanel; + private static GmSalvageUIAddNewItemDelegate? _gmSalvageUIAddNewItem; + private static GmSalvageUISalvageDelegate? _gmSalvageUISalvage; private static bool _initialized; private static string _statusMessage = "Not probed yet."; private static int _interactionLogCount; @@ -122,6 +143,7 @@ internal static class ClientHelperHooks public static bool HasGetGroundContainerId => true; public static bool HasWriteToChat => _addTextToScroll != null; public static bool HasInvokeParser => true; + public static bool HasSalvagePanel => _sendNoticeOpenSalvagePanel != null && _gmSalvageUIAddNewItem != null && _gmSalvageUISalvage != null; private static int _currentGroundContainerId; public static bool Probe() @@ -140,6 +162,9 @@ internal static class ClientHelperHooks _getPlayerId = Marshal.GetDelegateForFunctionPointer(new IntPtr(GetPlayerIdVa)); _addTextToScroll = Marshal.GetDelegateForFunctionPointer(new IntPtr(AddTextToScrollVa)); _useWithTargetEvent = Marshal.GetDelegateForFunctionPointer(new IntPtr(UseWithTargetEventVa)); + _sendNoticeOpenSalvagePanel = Marshal.GetDelegateForFunctionPointer(new IntPtr(SendNoticeOpenSalvagePanelVa)); + _gmSalvageUIAddNewItem = Marshal.GetDelegateForFunctionPointer(new IntPtr(GmSalvageUIAddNewItemVa)); + _gmSalvageUISalvage = Marshal.GetDelegateForFunctionPointer(new IntPtr(GmSalvageUISalvageVa)); _initialized = true; _statusMessage = "Ready."; RynthLog.Compat("Compat: helper hooks ready - validated select/state/chat helpers plus mapped interaction and inventory helpers."); @@ -506,6 +531,86 @@ internal static class ClientHelperHooks } } + /// + /// Open the salvage panel for the given salvage tool. + /// Calls CM_Inventory::SendNotice_OpenSalvagePanel (cdecl) which dispatches + /// the UI notice asynchronously; allow ~400 ms before calling AddItem. + /// + public static bool SalvagePanelOpen(uint toolId) + { + if (_sendNoticeOpenSalvagePanel == null || toolId == 0) + return false; + + try + { + _sendNoticeOpenSalvagePanel(toolId); + return true; + } + catch (Exception ex) + { + RynthLog.Compat($"Compat: SalvagePanelOpen threw - {ex.Message}"); + return false; + } + } + + /// + /// Add an item to the salvage panel. + /// Calls gmSalvageUI::AddNewItem (thiscall) via the captured singleton. + /// Requires the panel to have been opened at least once so SalvageHooks + /// has captured the gmSalvageUI instance pointer. + /// + public static bool SalvagePanelAddItem(uint itemId) + { + if (_gmSalvageUIAddNewItem == null || itemId == 0) + return false; + + IntPtr inst = SalvageHooks.GmSalvageUIInstance; + if (inst == IntPtr.Zero) + { + RynthLog.Compat("Compat: SalvagePanelAddItem - gmSalvageUI instance not captured yet"); + return false; + } + + try + { + _gmSalvageUIAddNewItem(inst, itemId); + return true; + } + catch (Exception ex) + { + RynthLog.Compat($"Compat: SalvagePanelAddItem threw - {ex.Message}"); + return false; + } + } + + /// + /// Execute the salvage operation (click Salvage button). + /// Calls gmSalvageUI::Salvage (thiscall) via the captured singleton. + /// + public static bool SalvagePanelExecute() + { + if (_gmSalvageUISalvage == null) + return false; + + IntPtr inst = SalvageHooks.GmSalvageUIInstance; + if (inst == IntPtr.Zero) + { + RynthLog.Compat("Compat: SalvagePanelExecute - gmSalvageUI instance not captured yet"); + return false; + } + + try + { + _gmSalvageUISalvage(inst); + return true; + } + catch (Exception ex) + { + RynthLog.Compat($"Compat: SalvagePanelExecute threw - {ex.Message}"); + return false; + } + } + public static bool InvokeParser(string? text) { if (string.IsNullOrEmpty(text)) @@ -541,6 +646,9 @@ internal static class ClientHelperHooks _getPlayerId = null; _addTextToScroll = null; _useWithTargetEvent = null; + _sendNoticeOpenSalvagePanel = null; + _gmSalvageUIAddNewItem = null; + _gmSalvageUISalvage = null; _initialized = false; } diff --git a/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs b/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs index 8a98056..99760e1 100644 --- a/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs @@ -49,6 +49,10 @@ internal static class ClientObjectHooks // CACQualities::InqSkillAdvancementClass(uint stype, SKILL_ADVANCEMENT_CLASS* retval) // SKILL_ADVANCEMENT_CLASS: UNDEF=0, UNTRAINED=1, TRAINED=2, SPECIALIZED=3 private const int ReferenceInqSkillAdvancementClass = 0x00592B70; + + // CACQualities::GetVitaeValue() — ThisCall, no args, returns float (1.0=no vitae, 0.95=5% penalty) + // Map: 0018EE80 → live VA: 0x0058FE80 + private const int ReferenceGetVitaeValue = 0x0058FE80; private const int NameTypeSingular = 0; private const int MaxLookupLogs = 12; @@ -175,6 +179,10 @@ internal static class ClientObjectHooks [UnmanagedFunctionPointer(CallingConvention.ThisCall)] private delegate int IsSpellKnownDelegate(IntPtr qualitiesPtr, uint spellId); + // float __thiscall CACQualities::GetVitaeValue() + [UnmanagedFunctionPointer(CallingConvention.ThisCall)] + private delegate float GetVitaeValueDelegate(IntPtr qualitiesPtr); + // ClientCombatSystem* __cdecl ClientCombatSystem::GetCombatSystem() [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr GetCombatSystemDelegate(); @@ -233,6 +241,7 @@ internal static class ClientObjectHooks private static InqSkillLevelDelegate? _inqSkillLevel; private static InqSkillAdvancementClassDelegate? _inqSkillAdvancementClass; private static IsSpellKnownDelegate? _isSpellKnown; + private static GetVitaeValueDelegate? _getVitaeValue; private static int _lookupLogCount; public static bool IsInitialized { get; private set; } @@ -309,6 +318,7 @@ internal static class ClientObjectHooks _inqSkillLevel = Marshal.GetDelegateForFunctionPointer(new IntPtr(ReferenceInqSkillLevel)); _inqSkillAdvancementClass = Marshal.GetDelegateForFunctionPointer(new IntPtr(ReferenceInqSkillAdvancementClass)); _isSpellKnown = Marshal.GetDelegateForFunctionPointer(new IntPtr(ReferenceIsSpellKnown)); + _getVitaeValue = Marshal.GetDelegateForFunctionPointer(new IntPtr(ReferenceGetVitaeValue)); RynthLog.Compat( $"Compat: client object hooks ready - getWeenie=0x{getWeeniePtr.ToInt32():X8}, getNameStatic=0x{getNameStaticPtr.ToInt32():X8}, getNameInstance=0x{getNameInstancePtr.ToInt32():X8}"); return true; @@ -343,6 +353,36 @@ internal static class ClientObjectHooks } } + /// + /// Returns the player's vitae multiplier via CACQualities::GetVitaeValue. + /// Returns 1.0 when there is no vitae penalty. 0.95 = 5% penalty, etc. + /// + public static bool TryGetVitae(uint playerId, out float value) + { + value = 1.0f; + if (_getVitaeValue == null || _getWeenieObject == null) + { + if (!Probe() || _getVitaeValue == null || _getWeenieObject == null) + return false; + } + try + { + IntPtr weeniePtr = _getWeenieObject(playerId); + if (weeniePtr == IntPtr.Zero) + return false; + + if (!TryGetQualitiesPtr(weeniePtr, out IntPtr qualitiesPtr)) + return false; + + value = _getVitaeValue(qualitiesPtr); + return true; + } + catch + { + return false; + } + } + /// /// Called by PlayerVitalsHooks when SendNoticePlayerDescReceived fires, providing the /// known CACQualities* (== PlayerDesc*) so we can probe its offset within ACCWeenieObject. @@ -584,6 +624,40 @@ internal static class ClientObjectHooks } } + /// + /// Reads PublicWeenieDesc._wcid directly from the weenie struct. + /// Returns the Weenie Class ID (WCID) for the given object. + /// Layout: ACCWeenieObject + _phys_obj_offset + 4 = start of PublicWeenieDesc. + /// PublicWeenieDesc+12 = _wcid: WeenieDesc(4) + _name(4) + _plural_name(4) = 12. + /// + public static bool TryGetObjectWcid(uint objectId, out uint wcid) + { + wcid = 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 + 12; + if (!IsReadablePointer(fieldAddr)) + return false; + wcid = (uint)Marshal.ReadInt32(fieldAddr); + return true; + } + catch + { + return false; + } + } + private static bool TryGetObjectQualitiesPtr(uint objectId, out IntPtr qualitiesPtr) { qualitiesPtr = IntPtr.Zero; @@ -710,16 +784,20 @@ internal static class ClientObjectHooks // Fast path: stypes whose values live in PublicWeenieDesc. // PWD starts at weenie + _phys_obj_offset + 4. Layout (Chorizite Weenie.cs:1734): // +28 _containerID, +32 _wielderID, +40 _valid_locations, +44 _location, - // +48 _itemsCapacity, +52 _containersCapacity, +96 _stackSize, +100 _maxStackSize + // +48 _itemsCapacity, +52 _containersCapacity, +96 _stackSize, +100 _maxStackSize, + // +148 _material_type + // CBaseQualities::InqInt fails for inventory/corpse items (m_pQualities is null on pack wienies). + // Any stype whose value lives in PWD must be served from here instead. int pwdFieldOffset = stype switch { - 6 => 48, // ITEMS_CAPACITY → _itemsCapacity - 7 => 52, // CONTAINERS_CAPACITY → _containersCapacity - 9 => 40, // LOCATIONS → _valid_locations - 10 => 44, // CURRENT_WIELDED_LOCATION → _location - 11 => 100, // MAX_STACK_SIZE → _maxStackSize - 12 => 96, // STACK_SIZE → _stackSize - _ => -1, + 6 => 48, // ITEMS_CAPACITY → _itemsCapacity + 7 => 52, // CONTAINERS_CAPACITY → _containersCapacity + 9 => 40, // LOCATIONS → _valid_locations + 10 => 44, // CURRENT_WIELDED_LOCATION → _location + 11 => 100, // MAX_STACK_SIZE → _maxStackSize + 12 => 96, // STACK_SIZE → _stackSize + 131 => 148, // MATERIAL_TYPE → _material_type (4 bytes, int) + _ => -1, }; if (pwdFieldOffset >= 0 && _weeniePhysicsObjOffset >= 0) @@ -782,13 +860,44 @@ internal static class ClientObjectHooks /// /// Calls CBaseQualities::InqFloat on the object's weenie to read a STypeFloat property. /// AC stores these as doubles despite the "Float" name. + /// Fast path: stype 280 (ITEM_WORKMANSHIP) is read from PublicWeenieDesc._workmanship + /// (Single at PWD+152) because it lives in the weenie descriptor, not CBaseQualities, + /// and InqFloat fails for pack/inventory items that have no m_pQualities pointer. /// public static unsafe bool TryGetObjectDoubleProperty(uint objectId, uint stype, out double value) { value = 0; - if (_inqFloat == null || _getWeenieObject == null) + if (_getWeenieObject == null) { - if (!Probe() || _inqFloat == null || _getWeenieObject == null) + if (!Probe() || _getWeenieObject == null) + return false; + } + + // Fast path: ITEM_WORKMANSHIP (STypeFloat=280) → PublicWeenieDesc._workmanship (Single at PWD+152) + if (stype == 280u && _weeniePhysicsObjOffset >= 0) + { + try + { + IntPtr weeniePtr = _getWeenieObject(objectId); + if (weeniePtr == IntPtr.Zero) + return false; + int pwdBase = _weeniePhysicsObjOffset + 4; + IntPtr fieldAddr = weeniePtr + pwdBase + 152; + if (!IsReadablePointer(fieldAddr)) + return false; + int bits = Marshal.ReadInt32(fieldAddr); + float f = BitConverter.Int32BitsToSingle(bits); + if (f == 0f) + return false; + value = f; + return true; + } + catch { return false; } + } + + if (_inqFloat == null) + { + if (!Probe() || _inqFloat == null) return false; } try @@ -825,6 +934,12 @@ internal static class ClientObjectHooks public static unsafe bool TryGetObjectBoolProperty(uint objectId, uint stype, out bool value) { value = false; + + // Appraisal cache covers inventory items where m_pQualities is null + // (CBaseQualities::InqBool always returns 0 for such objects). + if (AppraisalHooks.TryGetCachedBoolProperty(objectId, stype, out value)) + return true; + if (_inqBool == null || _getWeenieObject == null) { if (!Probe() || _inqBool == null || _getWeenieObject == null) diff --git a/src/RynthCore.Engine/Compatibility/CombatModeHooks.cs b/src/RynthCore.Engine/Compatibility/CombatModeHooks.cs index 70c22d2..64df2c1 100644 --- a/src/RynthCore.Engine/Compatibility/CombatModeHooks.cs +++ b/src/RynthCore.Engine/Compatibility/CombatModeHooks.cs @@ -19,9 +19,36 @@ internal static class CombatModeHooks private static string _statusMessage = "Not probed yet."; private static int _lastObservedCombatMode; + // ClientCombatSystem::s_pCombatSystem — pointer to the singleton in .data + private const uint CombatSystemPtrVa = 0x0087166C; + // Offset of combatMode (COMBAT_MODE) within ClientCombatSystem: + // ClientSystem(8) + IInputActionCallback(4) + QualityChangeHandler(4) + // + Turbine_RefCount(8) + jump_pending(1) + m_bTrackingTarget(1) + pad(2) = 28 + private const int CombatModeOffset = 28; + public static bool IsInstalled { get; private set; } public static string StatusMessage => _statusMessage; + /// + /// Reads the current combat mode directly from ClientCombatSystem::combatMode. + /// Returns NonCombat if the pointer is null or unreadable. + /// + public static unsafe int ReadCurrentCombatMode() + { + try + { + IntPtr combatSystem = *(IntPtr*)CombatSystemPtrVa; + if (combatSystem == IntPtr.Zero) + return CombatActionHooks.CombatModeNonCombat; + int raw = *(int*)(combatSystem + CombatModeOffset); + return NormalizeCombatMode(raw); + } + catch + { + return CombatActionHooks.CombatModeNonCombat; + } + } + public static void Initialize() { if (IsInstalled) diff --git a/src/RynthCore.Engine/Compatibility/SalvageHooks.cs b/src/RynthCore.Engine/Compatibility/SalvageHooks.cs new file mode 100644 index 0000000..3c2f7c1 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/SalvageHooks.cs @@ -0,0 +1,100 @@ +// ============================================================================ +// 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. +// +// VA derivation (map_offset + 0x00401000 = live VA): +// 000CAF70 gmSalvageUI::OpenSalvagePanel → 0x004CBF70 +// ============================================================================ + +using System; +using System.Runtime.InteropServices; +using System.Threading; +using RynthCore.Engine.Hooking; + +namespace RynthCore.Engine.Compatibility; + +internal static class SalvageHooks +{ + // gmSalvageUI::OpenSalvagePanel(uint toolId) — thiscall + // Map: 000CAF70 → live VA: 0x004CBF70 + private const int GmSalvageUIOpenSalvagePanelVa = 0x004CBF70; + + [UnmanagedFunctionPointer(CallingConvention.ThisCall)] + private delegate void GmSalvageUIOpenSalvagePanelDelegate(IntPtr thisPtr, uint toolId); + + private static GmSalvageUIOpenSalvagePanelDelegate? _originalOpenSalvagePanel; + private static GmSalvageUIOpenSalvagePanelDelegate? _openSalvagePanelDetour; // held alive to prevent GC + private static IntPtr _gmSalvageUIInstance; + private static bool _hookInstalled; + private static string _statusMessage = "Not initialized."; + + public static bool IsInstalled => _hookInstalled; + public static string StatusMessage => _statusMessage; + + /// + /// The captured gmSalvageUI singleton. Zero until the salvage panel has been + /// opened at least once (either by the player or by SalvagePanelOpen). + /// + public static IntPtr GmSalvageUIInstance => _gmSalvageUIInstance; + + public static void Initialize() + { + if (_hookInstalled) + return; + + if (!AcClientModule.TryReadTextSection(out AcClientTextSection textSection)) + { + _statusMessage = "acclient.exe not available."; + return; + } + + int funcOff = GmSalvageUIOpenSalvagePanelVa - textSection.TextBaseVa; + if (funcOff < 0 || funcOff >= textSection.Bytes.Length) + { + _statusMessage = $"gmSalvageUI::OpenSalvagePanel VA out of range @ 0x{GmSalvageUIOpenSalvagePanelVa:X8}."; + RynthLog.Compat($"Compat: salvage hook failed - {_statusMessage}"); + return; + } + + byte firstByte = textSection.Bytes[funcOff]; + if (firstByte is 0x00 or 0xCC or 0xC3) + { + _statusMessage = $"gmSalvageUI::OpenSalvagePanel looks invalid @ 0x{GmSalvageUIOpenSalvagePanelVa:X8} (opcode 0x{firstByte:X2})."; + RynthLog.Compat($"Compat: salvage hook failed - {_statusMessage}"); + return; + } + + try + { + IntPtr targetAddress = new IntPtr(textSection.TextBaseVa + funcOff); + _openSalvagePanelDetour = OpenSalvagePanelDetour; + IntPtr detourPtr = Marshal.GetFunctionPointerForDelegate(_openSalvagePanelDetour); + _originalOpenSalvagePanel = Marshal.GetDelegateForFunctionPointer( + MinHook.HookCreate(targetAddress, detourPtr)); + Thread.MemoryBarrier(); + MinHook.Enable(targetAddress); + + _hookInstalled = true; + _statusMessage = $"Hooked gmSalvageUI::OpenSalvagePanel @ 0x{targetAddress.ToInt32():X8}."; + RynthLog.Compat($"Compat: salvage hook ready @ 0x{targetAddress.ToInt32():X8}, firstByte=0x{firstByte:X2}"); + } + catch (Exception ex) + { + _statusMessage = ex.Message; + RynthLog.Compat($"Compat: salvage hook failed - {ex.Message}"); + } + } + + private static void OpenSalvagePanelDetour(IntPtr thisPtr, uint toolId) + { + // Capture the gmSalvageUI singleton on every open so it stays fresh + // even across hot-reloads or UI recreation. + if (thisPtr != IntPtr.Zero) + _gmSalvageUIInstance = thisPtr; + + _originalOpenSalvagePanel!(thisPtr, toolId); + } +} diff --git a/src/RynthCore.Engine/Compatibility/TeleportStateHooks.cs b/src/RynthCore.Engine/Compatibility/TeleportStateHooks.cs new file mode 100644 index 0000000..2996810 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/TeleportStateHooks.cs @@ -0,0 +1,46 @@ +using System; +using System.Runtime.InteropServices; + +namespace RynthCore.Engine.Compatibility; + +/// +/// 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) +/// +internal static class TeleportStateHooks +{ + private const int PlayerSystemPtrVa = 0x0087119C; + private const int TeleportInProgressOffset = 0x238; + + public static bool IsInstalled => true; // no hook needed — direct memory read + + /// Returns true while the player is in the teleport/portal transit state. + public static unsafe bool IsPortaling + { + get + { + try + { + IntPtr playerSystem = *(IntPtr*)PlayerSystemPtrVa; + if (playerSystem == IntPtr.Zero) return false; + return *(byte*)(playerSystem + TeleportInProgressOffset) != 0; + } + catch + { + return false; + } + } + } + + // Called from EntryPoint.Initialize chain — nothing to install for a direct read. + public static void Initialize() + { + RynthLog.Compat($"Compat: teleport-state ready — direct read CPlayerSystem+0x238 @ PlayerSystemPtr=0x{PlayerSystemPtrVa:X8}"); + } +} diff --git a/src/RynthCore.Engine/EntryPoint.cs b/src/RynthCore.Engine/EntryPoint.cs index 22c2b66..281f028 100644 --- a/src/RynthCore.Engine/EntryPoint.cs +++ b/src/RynthCore.Engine/EntryPoint.cs @@ -270,6 +270,10 @@ public static class EntryPoint RunInitStep("logo bypass", LogoBypassHooks.Start); RunInitStep("busy-count hooks", BusyCountHooks.Initialize); RunInitStep("combat-mode hooks", CombatModeHooks.Initialize); + RunInitStep("teleport-state hooks", TeleportStateHooks.Initialize); + RunInitStep("salvage hooks", SalvageHooks.Initialize); + RunInitStep("appraisal hooks", AppraisalHooks.Initialize); + RunInitStep("account hooks", AccountHooks.Initialize); RunInitStep("client combat hooks", () => ClientCombatHooks.Probe()); RunInitStep("selected-target hooks", SelectedTargetHooks.Initialize); RunInitStep("smartbox hooks", SmartBoxHooks.Initialize); diff --git a/src/RynthCore.Engine/Plugins/PluginContract.cs b/src/RynthCore.Engine/Plugins/PluginContract.cs index d0ffa31..0697fca 100644 --- a/src/RynthCore.Engine/Plugins/PluginContract.cs +++ b/src/RynthCore.Engine/Plugins/PluginContract.cs @@ -125,6 +125,9 @@ internal struct RynthCoreAPI /// Function pointer: int GetPlayerPose(uint* objCellId, float* x, float* y, float* z, float* qw, float* qx, float* qy, float* qz) public IntPtr GetPlayerPoseFn; + /// Function pointer: int IsPortaling() — returns 1 if SmartBox::teleport_in_progress, 0 otherwise + public IntPtr IsPortalingFn; + /// Function pointer: int SetMotion(uint motion, int enabled) public IntPtr SetMotionFn; @@ -301,12 +304,71 @@ internal struct RynthCoreAPI /// creates new stacks instead of merging, so AutoStack must use this entry point. /// public IntPtr MergeStackInternalFn; + + /// + /// Function pointer: int GetCurrentCombatMode() + /// Reads the current combat mode directly from ClientCombatSystem in AC memory. + /// Returns 1=NonCombat, 2=Melee, 4=Missile, 8=Magic. + /// + public IntPtr GetCurrentCombatModeFn; + + /// + /// Function pointer: int SalvagePanelOpen(uint toolId) + /// Calls CM_Inventory::SendNotice_OpenSalvagePanel to open the salvage panel + /// for the given salvage tool. Returns 1 on success. The panel opens + /// asynchronously — wait ~400 ms before calling SalvagePanelAddItem. + /// + public IntPtr SalvagePanelOpenFn; + + /// + /// Function pointer: int SalvagePanelAddItem(uint itemId) + /// Calls gmSalvageUI::AddNewItem to add an item to the open salvage panel. + /// Requires the panel to have been opened at least once. + /// Returns 1 on success, 0 if the gmSalvageUI instance is not yet captured. + /// + public IntPtr SalvagePanelAddItemFn; + + /// + /// Function pointer: int SalvagePanelExecute() + /// Calls gmSalvageUI::Salvage to execute the salvage operation. + /// Requires the panel to have been opened at least once. + /// Returns 1 on success, 0 if the gmSalvageUI instance is not yet captured. + /// + public IntPtr SalvagePanelExecuteFn; + + /// + /// Function pointer: float GetVitae(uint playerId) + /// Returns the player's vitae multiplier via CACQualities::GetVitaeValue. + /// 1.0 = no vitae, 0.95 = 5% penalty. Returns 1.0 if unavailable. + /// + public IntPtr GetVitaeFn; + + /// + /// Function pointer: const char* GetAccountName() + /// Returns a pointer to the cached ANSI account name string, or IntPtr.Zero if not available. + /// The pointer is valid until the next call. + /// + public IntPtr GetAccountNameFn; + + /// + /// Function pointer: const char* GetWorldName() + /// Returns a pointer to the cached UTF-8 world/server name string, or IntPtr.Zero if not available. + /// The pointer is valid until the next call. + /// + public IntPtr GetWorldNameFn; + + /// + /// Function pointer: uint GetObjectWcid(uint objectId) + /// Returns the Weenie Class ID (WCID) from PublicWeenieDesc._wcid for the given object. + /// Returns 0 if the object is not found or the phys_obj offset is not yet probed. + /// + public IntPtr GetObjectWcidFn; } /// Current API version. Bump when adding fields to RynthCoreAPI. internal static class PluginContractVersion { - public const uint Current = 34; + public const uint Current = 40; } internal static class ClientActionHookFlags @@ -433,6 +495,9 @@ internal delegate int NativeAttackCallbackDelegate(int attackHeight, float power [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate int IsPlayerReadyCallbackDelegate(); +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal delegate int IsPortalingCallbackDelegate(); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void SetFpsLimitCallbackDelegate(int enabled, int focusedFps, int backgroundFps); @@ -615,3 +680,27 @@ internal unsafe delegate int GetContainerContentsCallbackDelegate(uint container [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal unsafe delegate int GetObjectOwnershipInfoCallbackDelegate(uint objectId, uint* containerID, uint* wielderID, uint* location); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal delegate int GetCurrentCombatModeCallbackDelegate(); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal delegate int SalvagePanelOpenCallbackDelegate(uint toolId); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal delegate int SalvagePanelAddItemCallbackDelegate(uint itemId); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal delegate int SalvagePanelExecuteCallbackDelegate(); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal delegate float GetVitaeCallbackDelegate(uint playerId); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal delegate IntPtr GetAccountNameCallbackDelegate(); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal delegate IntPtr GetWorldNameCallbackDelegate(); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal delegate uint GetObjectWcidCallbackDelegate(uint objectId); diff --git a/src/RynthCore.Engine/Plugins/PluginManager.cs b/src/RynthCore.Engine/Plugins/PluginManager.cs index b4265db..e2808f7 100644 --- a/src/RynthCore.Engine/Plugins/PluginManager.cs +++ b/src/RynthCore.Engine/Plugins/PluginManager.cs @@ -46,6 +46,9 @@ internal static class PluginManager private const int MaxPendingStopViewingObjectContents = 128; private const int MaxPendingUpdateHealth = 512; private const int MaxPendingEnchantmentEvents = 256; + private const int MaxPrePluginCreateObjects = 4096; + private static readonly Queue _prePluginCreateObjects = new(); + private static readonly object PrePluginCreateObjectsLock = new(); private static readonly List _plugins = new(); private static readonly Queue _pendingIncomingChats = new(); private static readonly Queue _pendingBusyCountIncremented = new(); @@ -123,6 +126,7 @@ internal static class PluginManager private static MergeStackInternalCallbackDelegate? _mergeStackInternalCallback; private static WriteToChatCallbackDelegate? _writeToChatCallback; private static GetPlayerPoseCallbackDelegate? _getPlayerPoseCallback; + private static IsPortalingCallbackDelegate? _isPortalingCallback; private static GetObjectNameCallbackDelegate? _getObjectNameCallback; private static GetPlayerVitalsCallbackDelegate? _getPlayerVitalsCallback; private static GetObjectPositionCallbackDelegate? _getObjectPositionCallback; @@ -152,6 +156,16 @@ internal static class PluginManager private static SetFpsLimitCallbackDelegate? _setFpsLimitCallback; private static GetContainerContentsCallbackDelegate? _getContainerContentsCallback; private static GetObjectOwnershipInfoCallbackDelegate? _getObjectOwnershipInfoCallback; + private static GetCurrentCombatModeCallbackDelegate? _getCurrentCombatModeCallback; + private static SalvagePanelOpenCallbackDelegate? _salvagePanelOpenCallback; + private static SalvagePanelAddItemCallbackDelegate? _salvagePanelAddItemCallback; + private static SalvagePanelExecuteCallbackDelegate? _salvagePanelExecuteCallback; + private static GetVitaeCallbackDelegate? _getVitaeCallback; + private static GetAccountNameCallbackDelegate? _getAccountNameCallback; + private static GetWorldNameCallbackDelegate? _getWorldNameCallback; + private static GetObjectWcidCallbackDelegate? _getObjectWcidCallback; + private static IntPtr _accountNameScratchPtr; + private static IntPtr _worldNameScratchPtr; [ThreadStatic] private static IntPtr _objectNameScratchPtr; private static string _pluginsDir = ""; private static string _shadowRootDir = ""; @@ -208,6 +222,29 @@ internal static class PluginManager InitializeLoadedPlugins(); DispatchUIInitializedToLoadedPlugins(); DispatchLoginCompleteToLoadedPlugins(); + ReplayPrePluginCreateObjects(); + } + + private static void ReplayPrePluginCreateObjects() + { + uint[] prePending; + lock (PrePluginCreateObjectsLock) + { + if (_prePluginCreateObjects.Count == 0) return; + prePending = _prePluginCreateObjects.ToArray(); + // Do NOT clear — keep accumulating so hot-reloads can replay the full snapshot. + } + + RynthLog.Plugin($"PluginManager: Replaying {prePending.Length} pre-plugin CreateObject event(s)."); + lock (PendingCreateObjectsLock) + { + foreach (uint objectId in prePending) + { + if (_pendingCreateObjects.Count >= MaxPendingCreateObjects) + _pendingCreateObjects.Dequeue(); + _pendingCreateObjects.Enqueue(new PendingCreateObject(objectId)); + } + } } public static void RequestRescan() @@ -416,6 +453,14 @@ internal static class PluginManager public static void QueueCreateObject(uint objectId) { + // Always buffer for replay — covers the race between hook install and plugin load + lock (PrePluginCreateObjectsLock) + { + if (_prePluginCreateObjects.Count >= MaxPrePluginCreateObjects) + _prePluginCreateObjects.Dequeue(); + _prePluginCreateObjects.Enqueue(objectId); + } + if (_plugins.Count == 0) return; @@ -704,6 +749,7 @@ internal static class PluginManager InitializeLoadedPlugins(); DispatchUIInitializedToLoadedPlugins(); DispatchLoginCompleteToLoadedPlugins(); + ReplayPrePluginCreateObjects(); } private static void DispatchQueuedChatWindowText() @@ -1455,6 +1501,12 @@ internal static class PluginManager CombatActionHooks.RequestId(playerId); RynthLog.Plugin($"PluginManager: sent self-identify for player 0x{playerId:X8} to seed max vitals."); } + + // Sync the actual current combat mode to newly initialized plugins. + // Reads directly from ClientCombatSystem so this is accurate even at first inject. + int actualCombatMode = CombatModeHooks.ReadCurrentCombatMode(); + QueueCombatModeChange(actualCombatMode, CombatActionHooks.CombatModeNonCombat); + RynthLog.Plugin($"PluginManager: synced combat mode {actualCombatMode} to plugins."); } private static unsafe void EnsureHostCallbacks() @@ -1494,6 +1546,7 @@ internal static class PluginManager _mergeStackInternalCallback ??= MergeStackInternal; _writeToChatCallback ??= WriteToChat; _getPlayerPoseCallback ??= GetPlayerPose; + _isPortalingCallback ??= IsPortalingCallback; _getObjectNameCallback ??= GetObjectName; _getPlayerVitalsCallback ??= GetPlayerVitals; _getObjectPositionCallback ??= GetObjectPosition; @@ -1523,6 +1576,14 @@ internal static class PluginManager _setFpsLimitCallback ??= SetFpsLimitAction; _getContainerContentsCallback ??= GetContainerContentsAction; _getObjectOwnershipInfoCallback ??= GetObjectOwnershipInfoAction; + _getCurrentCombatModeCallback ??= GetCurrentCombatModeAction; + _salvagePanelOpenCallback ??= SalvagePanelOpenAction; + _salvagePanelAddItemCallback ??= SalvagePanelAddItemAction; + _salvagePanelExecuteCallback ??= SalvagePanelExecuteAction; + _getVitaeCallback ??= GetVitaeAction; + _getAccountNameCallback ??= GetAccountNameAction; + _getWorldNameCallback ??= GetWorldNameAction; + _getObjectWcidCallback ??= GetObjectWcidAction; _api.Version = PluginContractVersion.Current; _api.LogFn = Marshal.GetFunctionPointerForDelegate(_logCallback); @@ -1558,6 +1619,7 @@ internal static class PluginManager _api.MoveItemInternalFn = Marshal.GetFunctionPointerForDelegate(_moveItemInternalCallback); _api.WriteToChatFn = Marshal.GetFunctionPointerForDelegate(_writeToChatCallback); _api.GetPlayerPoseFn = Marshal.GetFunctionPointerForDelegate(_getPlayerPoseCallback); + _api.IsPortalingFn = Marshal.GetFunctionPointerForDelegate(_isPortalingCallback); _api.GetObjectNameFn = Marshal.GetFunctionPointerForDelegate(_getObjectNameCallback); _api.GetPlayerVitalsFn = Marshal.GetFunctionPointerForDelegate(_getPlayerVitalsCallback); _api.GetObjectPositionFn = Marshal.GetFunctionPointerForDelegate(_getObjectPositionCallback); @@ -1589,6 +1651,14 @@ internal static class PluginManager _api.GetObjectOwnershipInfoFn = Marshal.GetFunctionPointerForDelegate(_getObjectOwnershipInfoCallback); _api.SplitStackInternalFn = Marshal.GetFunctionPointerForDelegate(_splitStackInternalCallback); _api.MergeStackInternalFn = Marshal.GetFunctionPointerForDelegate(_mergeStackInternalCallback); + _api.GetCurrentCombatModeFn = Marshal.GetFunctionPointerForDelegate(_getCurrentCombatModeCallback); + _api.SalvagePanelOpenFn = Marshal.GetFunctionPointerForDelegate(_salvagePanelOpenCallback); + _api.SalvagePanelAddItemFn = Marshal.GetFunctionPointerForDelegate(_salvagePanelAddItemCallback); + _api.SalvagePanelExecuteFn = Marshal.GetFunctionPointerForDelegate(_salvagePanelExecuteCallback); + _api.GetVitaeFn = Marshal.GetFunctionPointerForDelegate(_getVitaeCallback); + _api.GetAccountNameFn = Marshal.GetFunctionPointerForDelegate(_getAccountNameCallback); + _api.GetWorldNameFn = Marshal.GetFunctionPointerForDelegate(_getWorldNameCallback); + _api.GetObjectWcidFn = Marshal.GetFunctionPointerForDelegate(_getObjectWcidCallback); } private static void ProbeClientHooks() @@ -1763,6 +1833,17 @@ internal static class PluginManager return 1; } + private static int GetCurrentCombatModeAction() => CombatModeHooks.ReadCurrentCombatMode(); + + private static int SalvagePanelOpenAction(uint toolId) + => ToAbiBool(ClientHelperHooks.SalvagePanelOpen(toolId)); + + private static int SalvagePanelAddItemAction(uint itemId) + => ToAbiBool(ClientHelperHooks.SalvagePanelAddItem(itemId)); + + private static int SalvagePanelExecuteAction() + => ToAbiBool(ClientHelperHooks.SalvagePanelExecute()); + private static unsafe int GetContainerContentsAction(uint containerId, uint* itemIds, int maxCount) { RynthLog.Compat($"Compat: GetContainerContentsAction ENTRY id=0x{containerId:X8} itemIds=0x{(int)itemIds:X8} maxCount={maxCount}"); @@ -1983,6 +2064,51 @@ internal static class PluginManager return ToAbiBool(ClientHelperHooks.InvokeParser(text)); } + private static int IsPortalingCallback() + { + return TeleportStateHooks.IsPortaling ? 1 : 0; + } + + private static float GetVitaeAction(uint playerId) + { + return ClientObjectHooks.TryGetVitae(playerId, out float v) ? v : 1.0f; + } + + private static IntPtr GetAccountNameAction() + { + if (!AccountHooks.TryGetAccountName(out string name) || string.IsNullOrEmpty(name)) + return IntPtr.Zero; + + if (_accountNameScratchPtr != IntPtr.Zero) + { + Marshal.FreeHGlobal(_accountNameScratchPtr); + _accountNameScratchPtr = IntPtr.Zero; + } + + _accountNameScratchPtr = Marshal.StringToHGlobalAnsi(name); + return _accountNameScratchPtr; + } + + private static IntPtr GetWorldNameAction() + { + if (!AccountHooks.TryGetWorldName(out string name) || string.IsNullOrEmpty(name)) + return IntPtr.Zero; + + if (_worldNameScratchPtr != IntPtr.Zero) + { + Marshal.FreeHGlobal(_worldNameScratchPtr); + _worldNameScratchPtr = IntPtr.Zero; + } + + _worldNameScratchPtr = Marshal.StringToHGlobalAnsi(name); + return _worldNameScratchPtr; + } + + private static uint GetObjectWcidAction(uint objectId) + { + return ClientObjectHooks.TryGetObjectWcid(objectId, out uint wcid) ? wcid : 0u; + } + private static unsafe int GetPlayerPose( uint* objCellId, float* x, diff --git a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs index 1e5c5a5..a81cb11 100644 --- a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs +++ b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs @@ -39,6 +39,7 @@ public struct RynthCoreApiNative public IntPtr MoveItemInternalFn; public IntPtr WriteToChatFn; public IntPtr GetPlayerPoseFn; + public IntPtr IsPortalingFn; public IntPtr SetMotionFn; public IntPtr StopCompletelyFn; public IntPtr TurnToHeadingFn; @@ -74,4 +75,12 @@ public struct RynthCoreApiNative public IntPtr GetObjectOwnershipInfoFn; public IntPtr SplitStackInternalFn; public IntPtr MergeStackInternalFn; + public IntPtr GetCurrentCombatModeFn; + public IntPtr SalvagePanelOpenFn; + public IntPtr SalvagePanelAddItemFn; + public IntPtr SalvagePanelExecuteFn; + public IntPtr GetVitaeFn; + public IntPtr GetAccountNameFn; + public IntPtr GetWorldNameFn; + public IntPtr GetObjectWcidFn; } diff --git a/src/RynthCore.PluginSdk/RynthCoreHost.cs b/src/RynthCore.PluginSdk/RynthCoreHost.cs index 495c2c5..9761954 100644 --- a/src/RynthCore.PluginSdk/RynthCoreHost.cs +++ b/src/RynthCore.PluginSdk/RynthCoreHost.cs @@ -5,7 +5,7 @@ namespace RynthCore.PluginSdk; public readonly unsafe struct RynthCoreHost { - public const uint CurrentApiVersion = 32; + public const uint CurrentApiVersion = 40; private readonly RynthCoreApiNative _api; @@ -50,6 +50,11 @@ public readonly unsafe struct RynthCoreHost public bool HasMergeStackInternal => _api.MergeStackInternalFn != IntPtr.Zero; public bool HasWriteToChat => _api.WriteToChatFn != IntPtr.Zero; public bool HasGetPlayerPose => _api.GetPlayerPoseFn != IntPtr.Zero; + public bool HasIsPortaling => _api.IsPortalingFn != IntPtr.Zero; + public bool HasGetVitae => _api.GetVitaeFn != IntPtr.Zero; + public bool HasGetAccountName => _api.GetAccountNameFn != IntPtr.Zero; + public bool HasGetWorldName => _api.GetWorldNameFn != IntPtr.Zero; + public bool HasGetObjectWcid => _api.GetObjectWcidFn != IntPtr.Zero; public bool HasSetMotion => _api.SetMotionFn != IntPtr.Zero; public bool HasStopCompletely => _api.StopCompletelyFn != IntPtr.Zero; public bool HasTurnToHeading => _api.TurnToHeadingFn != IntPtr.Zero; @@ -81,6 +86,8 @@ public readonly unsafe struct RynthCoreHost public bool HasSetFpsLimit => _api.SetFpsLimitFn != IntPtr.Zero; public bool HasGetContainerContents => _api.GetContainerContentsFn != IntPtr.Zero; public bool HasGetObjectOwnershipInfo => _api.GetObjectOwnershipInfoFn != IntPtr.Zero; + public bool HasGetCurrentCombatMode => _api.GetCurrentCombatModeFn != IntPtr.Zero; + public bool HasSalvagePanel => _api.SalvagePanelOpenFn != IntPtr.Zero && _api.SalvagePanelAddItemFn != IntPtr.Zero && _api.SalvagePanelExecuteFn != IntPtr.Zero; // ─── Methods ──────────────────────────────────────────────────────────── @@ -121,6 +128,29 @@ public readonly unsafe struct RynthCoreHost ((delegate* unmanaged[Cdecl])_api.ChangeCombatModeFn)(combatMode) != 0; } + /// Reads the current combat mode directly from AC client memory (1=NonCombat 2=Melee 4=Missile 8=Magic). + public int GetCurrentCombatMode() + { + return _api.GetCurrentCombatModeFn != IntPtr.Zero + ? ((delegate* unmanaged[Cdecl])_api.GetCurrentCombatModeFn)() + : 1; // NonCombat fallback + } + + /// Open the salvage panel for the given salvage tool (async — wait ~400 ms before adding items). + public bool SalvagePanelOpen(uint toolId) + => _api.SalvagePanelOpenFn != IntPtr.Zero && + ((delegate* unmanaged[Cdecl])_api.SalvagePanelOpenFn)(toolId) != 0; + + /// Add an item to the open salvage panel. Requires the panel to have been opened at least once. + public bool SalvagePanelAddItem(uint itemId) + => _api.SalvagePanelAddItemFn != IntPtr.Zero && + ((delegate* unmanaged[Cdecl])_api.SalvagePanelAddItemFn)(itemId) != 0; + + /// Execute the salvage operation (equivalent to clicking the Salvage button). + public bool SalvagePanelExecute() + => _api.SalvagePanelExecuteFn != IntPtr.Zero && + ((delegate* unmanaged[Cdecl])_api.SalvagePanelExecuteFn)() != 0; + public bool CancelAttack() { return _api.CancelAttackFn != IntPtr.Zero && @@ -385,6 +415,46 @@ public readonly unsafe struct RynthCoreHost } } + public bool IsPortaling() + { + if (_api.IsPortalingFn == IntPtr.Zero) return false; + return ((delegate* unmanaged[Cdecl])_api.IsPortalingFn)() != 0; + } + + public float GetVitae(uint playerId) + { + if (_api.GetVitaeFn == IntPtr.Zero) return 1.0f; + return ((delegate* unmanaged[Cdecl])_api.GetVitaeFn)(playerId); + } + + public bool TryGetAccountName(out string name) + { + name = string.Empty; + if (_api.GetAccountNameFn == IntPtr.Zero) return false; + IntPtr ptr = ((delegate* unmanaged[Cdecl])_api.GetAccountNameFn)(); + if (ptr == IntPtr.Zero) return false; + name = Marshal.PtrToStringAnsi(ptr) ?? string.Empty; + return !string.IsNullOrEmpty(name); + } + + public bool TryGetWorldName(out string name) + { + name = string.Empty; + if (_api.GetWorldNameFn == IntPtr.Zero) return false; + IntPtr ptr = ((delegate* unmanaged[Cdecl])_api.GetWorldNameFn)(); + if (ptr == IntPtr.Zero) return false; + name = Marshal.PtrToStringAnsi(ptr) ?? string.Empty; + return !string.IsNullOrEmpty(name); + } + + public bool TryGetObjectWcid(uint objectId, out uint wcid) + { + wcid = 0; + if (_api.GetObjectWcidFn == IntPtr.Zero) return false; + wcid = ((delegate* unmanaged[Cdecl])_api.GetObjectWcidFn)(objectId); + return wcid != 0; + } + public bool TryGetObjectName(uint objectId, out string name) { name = string.Empty;