diff --git a/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs b/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs index 8151693..6a9ebb1 100644 --- a/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs @@ -4083,6 +4083,24 @@ internal static class ClientObjectHooks internal static bool IsContainerInSnapshot(uint objectId) => TryGetPwdSnapshotInt(objectId, 6, out int capacity) && capacity > 0; + /// + /// EquipmentTracker's start: the ids the PWD snapshot shows as wielded by + /// in no container, with their location. Both fields must agree: the wielder alone stays on an + /// item after it went into a pack (2026-10-17). Off-thread safe (snapshot only). + /// + internal static void CollectWieldedFromSnapshot(uint playerId, List<(uint Id, uint Loc)> dest) + { + lock (_weeniePtrSwapLock) + { + foreach (KeyValuePair kv in _pwdFront) + { + if (kv.Key == playerId) continue; + if (kv.Value.Wielder == playerId && kv.Value.Container == 0 && kv.Value.Location != 0) + dest.Add((kv.Key, kv.Value.Location)); + } + } + } + /// /// Off-thread helper for UpdateObjectInventoryHooks: writes the ids whose PWD /// container or wielder is from the main-thread diff --git a/src/RynthCore.Engine/Compatibility/EquipmentTracker.cs b/src/RynthCore.Engine/Compatibility/EquipmentTracker.cs new file mode 100644 index 0000000..743865e --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/EquipmentTracker.cs @@ -0,0 +1,228 @@ +using System; +using System.Collections.Generic; +using System.IO; + +namespace RynthCore.Engine.Compatibility; + +/// +/// What the player wields, and where, from the server's own messages (the way Decal's object +/// database knows it, and why VTank never guesses): +/// * GameEvent 0x0023 WieldObject [item][EquipMask]: the item is wielded in that slot; +/// * GameEvent 0x0022 InventoryPutObjInContainer [item][container]..: it is in a container; +/// * GameEvent 0x019A InventoryPutObjectIn3D [item]: it was dropped. +/// (ACE: GameEventWieldItem, GameEventItemServerSaysContainId, GameEventItemServerSaysMoveItem.) +/// +/// The client's own copy of these fields goes stale on this client: CurrentWieldedLocation reads 0 +/// and the PWD wielder keeps naming the player after the item went into a pack (Drakkon fought +/// bare-handed and died over it, 2026-10-17/18). The tracker starts from the client's PWD snapshot +/// where its fields agree (wielder = the player and no container), then follows the messages. +/// Messages that arrive before that start are kept and applied on top of it. +/// +/// The record survives an engine reload (/rc rl, a publish): every change is written to +/// %LOCALAPPDATA%\RynthCore\equip\p{pid}.txt and a new engine in the same client starts from it. +/// The client's fields are only right at login: restarted from them mid-session, the tracker had +/// the Sceptre "in hand" that the server had put into the pack minutes before (2026-10-18 12:29). +/// At logout the file is deleted, so the next login starts from the login's own records. +/// +/// Thread safety: the game-event hook runs on AC's main thread, plugins ask from the pump thread; +/// everything goes through . +/// +internal static class EquipmentTracker +{ + private static readonly object Gate = new(); + private static readonly Dictionary _wielded = new(); // item -> EquipMask + private static readonly Dictionary _pending = new(); // before the start: item -> EquipMask (0 = not wielded) + private static uint _playerId; + private static bool _seeded; + private static int _changes; + private static string _source = ""; + + private static string FilePath => Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "equip", + $"p{Environment.ProcessId}.txt"); + + /// Where the current record started from ("saved", "login records", "client records mid-session"). + public static string Source { get { lock (Gate) return _source; } } + + // Writes the record (under Gate). A failed write only loses the carry-over across a reload. + private static void SaveLocked() + { + try + { + string path = FilePath; + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + var lines = new List(_wielded.Count + 1) { $"player {_playerId:X8}" }; + foreach (var kv in _wielded) lines.Add($"{kv.Key:X8} {kv.Value:X8}"); + File.WriteAllLines(path, lines); + } + catch { } + } + + // The saved record for this client and character, or null. + private static Dictionary? LoadSaved(uint player) + { + try + { + string path = FilePath; + if (!File.Exists(path)) return null; + string[] lines = File.ReadAllLines(path); + if (lines.Length == 0 || lines[0] != $"player {player:X8}") return null; + var map = new Dictionary(); + for (int i = 1; i < lines.Length; i++) + { + string[] parts = lines[i].Split(' '); + if (parts.Length == 2 + && uint.TryParse(parts[0], System.Globalization.NumberStyles.HexNumber, null, out uint id) + && uint.TryParse(parts[1], System.Globalization.NumberStyles.HexNumber, null, out uint loc)) + map[id] = loc; + } + return map; + } + catch { return null; } + } + + private static void DeleteSaved() + { + try { File.Delete(FilePath); } catch { } + } + + /// A WieldObject for at (main thread). + public static void OnWield(uint item, uint location) + { + if (item == 0) return; + lock (Gate) + { + if (!_seeded) { _pending[item] = location; return; } + if (location == 0) _wielded.Remove(item); else _wielded[item] = location; + _changes++; + SaveLocked(); + } + RynthLog.Compat($"Equipment: 0x{item:X8} wielded at 0x{location:X8} (server)"); + } + + /// An InventoryPutObjInContainer for (main thread): not wielded. + public static void OnContained(uint item, uint container) + { + if (item == 0) return; + bool was; + lock (Gate) + { + if (!_seeded) { _pending[item] = 0; return; } + was = _wielded.Remove(item); + if (was) { _changes++; SaveLocked(); } + } + if (was) RynthLog.Compat($"Equipment: 0x{item:X8} into container 0x{container:X8} (server)"); + } + + /// An InventoryPutObjectIn3D for (main thread): dropped, not wielded. + public static void OnDropped(uint item) + { + if (item == 0) return; + bool was; + lock (Gate) + { + if (!_seeded) { _pending[item] = 0; return; } + was = _wielded.Remove(item); + if (was) { _changes++; SaveLocked(); } + } + if (was) RynthLog.Compat($"Equipment: 0x{item:X8} dropped (server)"); + } + + /// + /// The player's wielded items into / . Returns the + /// count, or -1 while there is no player or no PWD snapshot to start from. Any thread. + /// + public static int Copy(Span ids, Span locations) + { + if (!EnsureStarted()) return -1; + lock (Gate) + { + int n = 0; + foreach (var kv in _wielded) + { + if (n >= ids.Length || n >= locations.Length) break; + ids[n] = kv.Key; + locations[n] = kv.Value; + n++; + } + return n; + } + } + + /// Starts (or restarts, for another character) from the PWD snapshot. False until it can. + private static bool EnsureStarted() + { + if (LogoutLifecycleHooks.HasObservedLogout) + { + bool had; + lock (Gate) had = _seeded; + if (had) { Reset(); DeleteSaved(); RynthLog.Compat("Equipment: logged out - the record is dropped"); } + return false; + } + uint player = ClientHelperHooks.GetPlayerId(); + if (player == 0) return false; + lock (Gate) + { + if (_seeded && player == _playerId) return true; + } + Dictionary? saved = LoadSaved(player); + if (saved == null && !ClientObjectHooks.HasPwdSnapshot) return false; + + var seed = new List<(uint Id, uint Loc)>(); + string from; + if (saved != null) + { + foreach (var kv in saved) seed.Add((kv.Key, kv.Value)); + from = "the record saved before the engine reload"; + } + else + { + ClientObjectHooks.CollectWieldedFromSnapshot(player, seed); + from = LoginLifecycleHooks.HasObservedLoginComplete ? "the client's records (at login)" : "the client's records (mid-session: may be stale until items move)"; + } + string list; + lock (Gate) + { + if (_seeded && player == _playerId) return true; + bool other = _seeded && player != _playerId; + _wielded.Clear(); + foreach (var (id, loc) in seed) _wielded[id] = loc; + // Messages seen before the start are newer than the snapshot read, except after a + // character change (they were the last character's). + if (!other) + foreach (var kv in _pending) + { + if (kv.Value == 0) _wielded.Remove(kv.Key); + else _wielded[kv.Key] = kv.Value; + } + _pending.Clear(); + _playerId = player; + _seeded = true; + _source = from; + SaveLocked(); + list = _wielded.Count == 0 ? "nothing" : string.Join(", ", FormatAll()); + } + RynthLog.Compat($"Equipment: started for 0x{player:X8} from {from}: {list}"); + return true; + } + + private static IEnumerable FormatAll() + { + foreach (var kv in _wielded) yield return $"0x{kv.Key:X8}@0x{kv.Value:X}"; + } + + /// Forget everything (logout, teardown): the next query starts again. + public static void Reset() + { + lock (Gate) + { + _wielded.Clear(); + _pending.Clear(); + _seeded = false; + _playerId = 0; + } + } + + /// Changes followed since the start (diagnostics). + public static int Changes { get { lock (Gate) return _changes; } } +} diff --git a/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs b/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs index a154142..f494b6a 100644 --- a/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs +++ b/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs @@ -408,10 +408,23 @@ internal static class SmartBoxHooks // nothing cached is a candidate. Here, not on the server message stream, // so it works with that stream off (engine.json / /rc netmsg off). if (size >= 12) - AutoIdService.OnPutInContainer( + { + uint putItem = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 4))); + uint putContainer = unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 8))); + AutoIdService.OnPutInContainer(putItem, putContainer); + EquipmentTracker.OnContained(putItem, putContainer); + } + break; + case 0x0023: // WieldObject: [item u32][EquipMask u32] (ACE GameEventWieldItem). + if (size >= 12) + EquipmentTracker.OnWield( unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 4))), unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 8)))); break; + case 0x019A: // InventoryPutObjectIn3D: [item u32] (ACE GameEventItemServerSaysMoveItem): dropped. + if (size >= 8) + EquipmentTracker.OnDropped(unchecked((uint)Marshal.ReadInt32(IntPtr.Add(data, 4)))); + break; case 0x00A0: // InventoryServerSaveFailed: [objectId u32][errorType u32] — // the server refused an inventory change (wield, move, ...). // Layout from UIQueueManager::ProcessNetBlobData's inline case diff --git a/src/RynthCore.Engine/Plugins/PluginContract.cs b/src/RynthCore.Engine/Plugins/PluginContract.cs index 90ee5a3..e26e15e 100644 --- a/src/RynthCore.Engine/Plugins/PluginContract.cs +++ b/src/RynthCore.Engine/Plugins/PluginContract.cs @@ -944,6 +944,12 @@ internal struct RynthCoreAPI /// schema). Returns the UTF-8 byte length; when it is >= capacity nothing was written (call /// again with a bigger buffer). -1 on failure. Any thread. Requires API v86+. public IntPtr GetServerStateJsonFn; + /// v87: int GetWieldedItems(uint* ids, uint* locations, int max): what the player + /// wields and where (EquipMask), from the server's WieldObject / InventoryPutObjInContainer / + /// InventoryPutObjectIn3D messages, started from the client's records where they agree + /// (Compatibility/EquipmentTracker.cs). Returns the count written (at most max), or -1 while + /// there is no player or nothing to start from. Any thread. Requires API v87+. + public IntPtr GetWieldedItemsFn; } /// v79 bits. @@ -1756,6 +1762,8 @@ internal unsafe delegate int GetServerInfoCallbackDelegate(byte* worldName, int [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal unsafe delegate int GetServerStateJsonCallbackDelegate(byte* buffer, int capacity); +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate int GetWieldedItemsCallbackDelegate(uint* ids, uint* locations, int max); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate int CloseContainerCallbackDelegate(uint containerId); diff --git a/src/RynthCore.Engine/Plugins/PluginContractVersion.cs b/src/RynthCore.Engine/Plugins/PluginContractVersion.cs index dd68d9c..849783a 100644 --- a/src/RynthCore.Engine/Plugins/PluginContractVersion.cs +++ b/src/RynthCore.Engine/Plugins/PluginContractVersion.cs @@ -23,5 +23,7 @@ internal static class PluginContractVersion // craft chance, for a plugin; from SilentKelpie's build, 2026-10-15). // v86: GetServerStateJson (the server list, active server and owning plugins for every plugin; // server plugins declare their server in their manifest; from SilentKelpie's build). - public const uint Current = 86; + // v87: GetWieldedItems (what the player wields and where, from the server's wield / contain / + // drop messages: EquipmentTracker; the client's own fields go stale, 2026-10-18). + public const uint Current = 87; } diff --git a/src/RynthCore.Engine/Plugins/PluginManager.cs b/src/RynthCore.Engine/Plugins/PluginManager.cs index 59c3e08..17ae8e6 100644 --- a/src/RynthCore.Engine/Plugins/PluginManager.cs +++ b/src/RynthCore.Engine/Plugins/PluginManager.cs @@ -279,6 +279,7 @@ internal static partial class PluginManager private static ArmConfirmationCallbackDelegate? _armConfirmationCallback; // v85 private static GetLastConfirmationCallbackDelegate? _getLastConfirmationCallback; // v85 private static GetServerStateJsonCallbackDelegate? _getServerStateJsonCallback; // v86 + private static GetWieldedItemsCallbackDelegate? _getWieldedItemsCallback; // v87 private static ForceResetBusyCountCallbackDelegate? _forceResetBusyCountCallback; private static GetObjectSpellIdsCallbackDelegate? _getObjectSpellIdsCallback; private static GetObjectSkillLevelCallbackDelegate? _getObjectSkillBuffedCallback; @@ -3135,6 +3136,7 @@ internal static partial class PluginManager _armConfirmationCallback ??= ArmConfirmationAction; unsafe { _getLastConfirmationCallback ??= GetLastConfirmationAction; } unsafe { _getServerStateJsonCallback ??= GetServerStateJsonAction; } + unsafe { _getWieldedItemsCallback ??= GetWieldedItemsAction; } _api.Version = PluginContractVersion.Current; _api.LogFn = Marshal.GetFunctionPointerForDelegate(_logCallback); @@ -3288,6 +3290,7 @@ internal static partial class PluginManager _api.ArmConfirmationFn = Marshal.GetFunctionPointerForDelegate(_armConfirmationCallback); _api.GetLastConfirmationFn = Marshal.GetFunctionPointerForDelegate(_getLastConfirmationCallback); _api.GetServerStateJsonFn = Marshal.GetFunctionPointerForDelegate(_getServerStateJsonCallback); + _api.GetWieldedItemsFn = Marshal.GetFunctionPointerForDelegate(_getWieldedItemsCallback); RouteApiThroughLoader(); } @@ -3485,6 +3488,20 @@ internal static partial class PluginManager /// v86: the server list as JSON (UI/Sections/ServerStateJson.cs) from the published snapshot. /// Any thread: the snapshot is immutable and the strings are volatile reads. -1 on failure. /// + /// v87: what the player wields (EquipmentTracker). -1 while it can't start. + private static unsafe int GetWieldedItemsAction(uint* ids, uint* locations, int max) + { + try + { + if (ids == null || locations == null || max <= 0) return -1; + return Compatibility.EquipmentTracker.Copy(new Span(ids, max), new Span(locations, max)); + } + catch + { + return -1; + } + } + private static unsafe int GetServerStateJsonAction(byte* buffer, int capacity) { try diff --git a/src/RynthCore.Engine/UI/Data/SettingsData.cs b/src/RynthCore.Engine/UI/Data/SettingsData.cs index ac44d33..980061f 100644 --- a/src/RynthCore.Engine/UI/Data/SettingsData.cs +++ b/src/RynthCore.Engine/UI/Data/SettingsData.cs @@ -40,6 +40,9 @@ internal sealed class RynthAiSettings public int TargetFPSBackground { get; set; } = 30; public bool EnableAutocram { get; set; } public bool PeaceModeWhenIdle { get; set; } + // RynthAi's Weapons Back After Heals. Nullable: an older RynthAi doesn't send it, and the + // engine then sends none back (a false would turn it off). + public bool? RearmAfterVitals { get; set; } public bool StartMacroOnLogin { get; set; } public bool PatrolOnLogin { get; set; } // RynthAi's Escape Acid and Lava. Default on; an older RynthAi doesn't send it, and a missing @@ -720,6 +723,8 @@ internal static class SettingsSchema Bool("Auto Cram", s => s.EnableAutocram, (s, v) => s.EnableAutocram = v, "Automatically moves items from your main pack into side packs.\nNote: recently used weapons stay in the main pack."), Bool("Peace Mode When Idle", s => s.PeaceModeWhenIdle, (s, v) => s.PeaceModeWhenIdle = v), + Bool("Weapons Back After Heals", s => s.RearmAfterVitals == true, (s, v) => s.RearmAfterVitals = v, + "After a heal, restam or remana spell with nothing to fight, put the last fight's weapons\n(main hand and off hand) back on instead of waiting for the next monster."), Bool("Start Macro On Login", s => s.StartMacroOnLogin, (s, v) => s.StartMacroOnLogin = v, "Automatically starts the macro when RynthAi loads."), Bool("Patrol On Login", s => s.PatrolOnLogin, (s, v) => s.PatrolOnLogin = v, diff --git a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs index eb4b39c..f01f9b2 100644 --- a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs +++ b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs @@ -179,6 +179,8 @@ public struct RynthCoreApiNative public IntPtr GetLastConfirmationFn; // int GetLastConfirmation(uint* type, uint* ctx, int* percent, int* outcome, int* ageMs) -> seq // v86: which server this is, for every plugin (servers, verdicts, overrides, owning plugins) public IntPtr GetServerStateJsonFn; // int GetServerStateJson(byte* buffer, int capacity) -> UTF-8 byte length (>= capacity: too small) + // v87: what the player wields, from the server's messages (the client's own fields go stale) + public IntPtr GetWieldedItemsFn; // int GetWieldedItems(uint* ids, uint* locations, int max) -> count, -1 not ready } /// diff --git a/src/RynthCore.PluginSdk/RynthCoreHost.cs b/src/RynthCore.PluginSdk/RynthCoreHost.cs index 9daf715..7dff495 100644 --- a/src/RynthCore.PluginSdk/RynthCoreHost.cs +++ b/src/RynthCore.PluginSdk/RynthCoreHost.cs @@ -144,6 +144,8 @@ public readonly unsafe struct RynthCoreHost public bool HasGetServerInfo => _api.Version >= 75 && _api.GetServerInfoFn != IntPtr.Zero; /// v86: (the server list for every plugin). public bool HasGetServerStateJson => _api.Version >= 86 && _api.GetServerStateJsonFn != IntPtr.Zero; + /// v87: (what the player wields, from the server's messages). + public bool HasGetWieldedItems => _api.Version >= 87 && _api.GetWieldedItemsFn != IntPtr.Zero; /// v76: (close a corpse or chest like the client's window close). public bool HasCloseContainer => _api.Version >= 76 && _api.CloseContainerFn != IntPtr.Zero; /// v77: , and the UI callbacks @@ -1125,6 +1127,27 @@ public readonly unsafe struct RynthCoreHost /// v86 or the call failed. Any thread; a few hundred bytes, so poll it (every second or two) /// rather than caching it for a session: an override changes it live. /// + /// + /// v87: what the player wields and where (EquipMask: 0x00100000 MeleeWeapon, 0x00200000 Shield, + /// 0x00400000 MissileWeapon, 0x00800000 MissileAmmo, 0x01000000 Held, 0x02000000 TwoHanded, ...), + /// from the server's wield / contain / drop messages. False when the engine doesn't have it or + /// can't start yet (no player). Any thread. + /// + public bool TryGetWieldedItems(out (uint Id, uint Location)[] items) + { + items = Array.Empty<(uint, uint)>(); + if (!HasGetWieldedItems) return false; + const int Max = 64; + uint* ids = stackalloc uint[Max]; + uint* locs = stackalloc uint[Max]; + int n = ((delegate* unmanaged[Cdecl])_api.GetWieldedItemsFn)(ids, locs, Max); + if (n < 0) return false; + var list = new (uint, uint)[n]; + for (int i = 0; i < n; i++) list[i] = (ids[i], locs[i]); + items = list; + return true; + } + public bool TryGetServerStateJson(out string json) { json = string.Empty;