From 9b5e2765b79b69a9f4549b61f46f9e9c8262e75f Mon Sep 17 00:00:00 2001 From: Tom Bohar Date: Sun, 27 Sep 2026 20:25:45 -0400 Subject: [PATCH] RynthCore as of 2026-09-27 (internal d359eee): items past the old object-id range, no idle logoff, overlay popups without the panel flash, UI hidden at character select, vendor trading (API 67), Settings rows and Vendoring tab, release 2026.9.27.2 --- docs/STATUS_AGENT.md | 4 +- installer/Publish-Update.ps1 | 25 +- src/RynthCore.App/CharacterCacheStore.cs | 7 +- .../Compatibility/AcMainThreadQueue.cs | 4 + .../Compatibility/CharacterCaptureHooks.cs | 106 +- .../Compatibility/CharacterManagementHooks.cs | 38 + .../Compatibility/ChatCallbackHooks.cs | 2 + .../Compatibility/ChatCommandDispatcher.cs | 2 + .../Compatibility/ChatHooks.cs | 10 +- .../Compatibility/ClientHelperHooks.cs | 1 + .../Compatibility/ClientObjectHooks.cs | 52 + .../Compatibility/GameTickHooks.cs | 3 + .../Compatibility/HeartbeatLogger.cs | 7 +- .../Compatibility/LogoffOriginProbe.cs | 802 +++++++++ .../Compatibility/LogoutLifecycleHooks.cs | 51 + .../Compatibility/ProcessExitHooks.cs | 2 +- .../Compatibility/RynthCoreChatCommands.cs | 13 + .../UpdateObjectInventoryHooks.cs | 23 +- .../Compatibility/VendorHooks.cs | 44 + .../Compatibility/VendorTrade.cs | 1488 +++++++++++++++++ src/RynthCore.Engine/D3D9/EndSceneHook.cs | 6 +- src/RynthCore.Engine/EntryPoint.cs | 4 + .../ImGui/EngineFrameController.cs | 10 +- src/RynthCore.Engine/ImGui/Win32Backend.cs | 54 +- .../Plugins/EngineSettings.cs | 22 + .../Plugins/PluginContract.cs | 149 +- src/RynthCore.Engine/Plugins/PluginManager.cs | 65 + src/RynthCore.Engine/UI/AvaloniaOverlay.cs | 371 +++- src/RynthCore.Engine/UI/LayeredWindow.cs | 65 +- .../UI/OverlaySkiaPlatformGraphics.cs | 127 +- src/RynthCore.Engine/UI/Panels/MetaPanel.cs | 66 +- src/RynthCore.Engine/UI/Panels/RadarPanel.cs | 9 +- .../UI/Panels/RynthAiPanel.cs | 73 +- .../UI/Panels/SettingsPanel.cs | 72 +- src/RynthCore.PluginCore/RynthPluginBase.cs | 2 +- src/RynthCore.PluginSdk/RynthCoreApiNative.cs | 6 + src/RynthCore.PluginSdk/RynthCoreHost.cs | 216 ++- src/RynthCore.PluginSdk/VendorTypes.cs | 238 +++ src/RynthCore.StatusAgent/AgentConfig.cs | 6 +- .../LocalStatusServer.cs | 17 +- src/RynthCore.StatusAgent/Program.cs | 10 +- .../RynthCore.StatusAgent.csproj | 5 +- tools/check_offthread_mutators.py | 1 + 43 files changed, 4216 insertions(+), 62 deletions(-) create mode 100644 src/RynthCore.Engine/Compatibility/LogoffOriginProbe.cs create mode 100644 src/RynthCore.Engine/Compatibility/VendorTrade.cs create mode 100644 src/RynthCore.PluginSdk/VendorTypes.cs diff --git a/docs/STATUS_AGENT.md b/docs/STATUS_AGENT.md index 708abc8..8e6adfe 100644 --- a/docs/STATUS_AGENT.md +++ b/docs/STATUS_AGENT.md @@ -126,7 +126,9 @@ they're all opt-in, so use whichever fits the app you end up building: a private mesh like **Tailscale** (phone hits `http://:8740/status`). A `+` bind needs a one-time `netsh http add urlacl url=http://+:8740/ user=Everyone` (or run the agent elevated). - - Set `ServeToken` to require `Authorization: Bearer ` (or `?token=`). + - `ServeToken` is required: with it empty the server stays off, on any bind. + Every route but `/healthz` then needs `Authorization: Bearer ` (or `?token=`). + Use the same token as your DrakBot remote and one DrakRemote entry shows both. - `GET /healthz` returns `ok` for uptime checks. 3. **File sync.** Leave `WriteAggregateFile: true` and point iCloud/Dropbox/etc. at `Logs\status\aggregate.json`; the app reads the synced copy. diff --git a/installer/Publish-Update.ps1 b/installer/Publish-Update.ps1 index c284781..d2cb1db 100644 --- a/installer/Publish-Update.ps1 +++ b/installer/Publish-Update.ps1 @@ -21,10 +21,14 @@ RynthCore client is closed. .EXAMPLE - .\Publish-Update.ps1 -Version 2026.9.27.1 -Notes "Arrow crafting covers every head type." + .\Publish-Update.ps1 -Version 2026.9.28.1 -Changes "Arrow crafting covers every head type.", "The Tell button works on players too." #> param( [Parameter(Mandatory)][string]$Version, + # Release notes for players, one line per change: they become this release's entry in + # downloads/rynth/releases.json, which the "What's new" list on aelrynth.com/rynth.html shows. + [string[]]$Changes = @(), + # Short text the launcher shows next to an available update; defaults to the changes. [string]$Notes = "", [switch]$DryRun, # build + sign + verify, upload nothing [switch]$AllowDirty, # publish with uncommitted changes (don't) @@ -69,6 +73,9 @@ Step "Checking preconditions" $p = $Version.Split('.') if ($p.Count -ne 4 -or ($p | Where-Object { $_ -notmatch '^\d+$' })) { throw "-Version must be yyyy.m.d.n, got '$Version'" } $release = [int]$p[0] * 1000000 + [int]$p[1] * 10000 + [int]$p[2] * 100 + [int]$p[3] +if ($Changes.Count -eq 0 -and $Notes) { $Changes = @($Notes -split ';\s*' | Where-Object { $_ }) } +if ($Changes.Count -eq 0) { throw "Give -Changes: the release notes players see on aelrynth.com/rynth.html (one string per change)." } +if (-not $Notes) { $Notes = $Changes -join " " } $trusted = [regex]::Matches((Get-Content $TrustFile -Raw), '"([A-Za-z0-9+/=]{80,})"') | ForEach-Object { $_.Groups[1].Value } if ($trusted.Count -lt 2) { @@ -183,6 +190,15 @@ Set-Content "$rel\update.payload.json" ($manifest | ConvertTo-Json -Depth 5) -En if (-not (Test-Envelope "$rel\update.json" $trusted)) { throw "Signed feed does not verify against UpdateTrust.cs" } Write-Host " verified against the launcher's trusted keys" +# Release notes: this release on top of the live list (a re-run replaces its own entry). +$history = @() +try { $history = @((Invoke-RestMethod "$BaseUrl/releases.json" -TimeoutSec 20).releases) } +catch [Microsoft.PowerShell.Commands.HttpResponseException] { Write-Host " no releases.json yet — starting one" } +$entry = [ordered]@{ version = $Version; date = (Get-Date -Format "yyyy-MM-dd"); changes = @($Changes) } +$releaseNotes = [ordered]@{ releases = @($entry) + @($history | Where-Object { $_ -and $_.version -ne $Version }) } +Set-Content "$rel\releases.json" ($releaseNotes | ConvertTo-Json -Depth 5) -Encoding utf8NoBOM +Write-Host " releases.json: $($releaseNotes.releases.Count) release(s), $($Changes.Count) change(s) in this one" + if ($DryRun) { Write-Host ""; Write-Host "Dry run: release built and signed in $rel; nothing uploaded." -ForegroundColor Yellow return @@ -220,6 +236,11 @@ scp -q "$rel\update.json" "${SshHost}:$RemoteDir/.update.json.new" if ($LASTEXITCODE -ne 0) { throw "scp of update.json failed" } ssh $SshHost "mv -f '$RemoteDir/.update.json.new' '$RemoteDir/update.json'" if ($LASTEXITCODE -ne 0) { throw "Publishing update.json failed" } +# The release notes follow the feed, so the page never lists a release launchers can't get yet. +scp -q "$rel\releases.json" "${SshHost}:$RemoteDir/.releases.json.new" +if ($LASTEXITCODE -ne 0) { throw "scp of releases.json failed" } +ssh $SshHost "mv -f '$RemoteDir/.releases.json.new' '$RemoteDir/releases.json'" +if ($LASTEXITCODE -ne 0) { throw "Publishing releases.json failed" } # ── 5. Verify ──────────────────────────────────────────────────────────────── Step "Verifying the live feed" @@ -232,4 +253,4 @@ try { Write-Host "" Write-Host "Published RynthCore $Version (release $release)." -ForegroundColor Green -Write-Host "Launchers pick it up at their next check. Still by hand: the site text (projects.html) and the public source snapshots." +Write-Host "Launchers pick it up at their next check, and aelrynth.com/rynth.html lists it. Still by hand: the public source snapshots." diff --git a/src/RynthCore.App/CharacterCacheStore.cs b/src/RynthCore.App/CharacterCacheStore.cs index a743eae..0e27deb 100644 --- a/src/RynthCore.App/CharacterCacheStore.cs +++ b/src/RynthCore.App/CharacterCacheStore.cs @@ -85,12 +85,17 @@ internal static class CharacterCacheStore return; List characters = Read(accountName, serverName); - if (!characters.Contains(characterName, StringComparer.OrdinalIgnoreCase)) + if (!characters.Any(existing => IsSameCharacter(existing, characterName))) characters.Add(characterName); Write(accountName, serverName, characters); } + // The client shows admin names with a leading '+' ('+Buffi'); a launch-context + // name may lack it. Treat both as one character so the list holds no duplicate. + private static bool IsSameCharacter(string a, string b) => + string.Equals(a.Trim().TrimStart('+'), b.Trim().TrimStart('+'), StringComparison.OrdinalIgnoreCase); + public static void DeleteForAccount(string accountName) { if (string.IsNullOrWhiteSpace(accountName)) diff --git a/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs b/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs index 3ca85ea..17cca0c 100644 --- a/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs +++ b/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs @@ -268,6 +268,10 @@ internal static class AcMainThreadQueue DrainChat(); DrainChatCommands(); DrainRequestIds(); + // Vendor buy/sell: a packet send through the client's own SendShopEvent, not a + // motion, so it sits with the non-gesture queues above. Also polls whether the + // vendor window is still open. Idle fast path when no vendor is open. + try { VendorTrade.MainThreadTick(); } catch { } int head = _head; // only the main thread writes _head int tail = Volatile.Read(ref _tail); diff --git a/src/RynthCore.Engine/Compatibility/CharacterCaptureHooks.cs b/src/RynthCore.Engine/Compatibility/CharacterCaptureHooks.cs index c78f80f..90fc472 100644 --- a/src/RynthCore.Engine/Compatibility/CharacterCaptureHooks.cs +++ b/src/RynthCore.Engine/Compatibility/CharacterCaptureHooks.cs @@ -53,6 +53,22 @@ internal static class CharacterCaptureHooks private const int AutoLoginDirectFailsBeforeClick = 4; private static int _autoLoginPollStarted; + // Native character-list capture. The 0xF658 packet path is dead (see above), + // so ParseAndSaveCharacterList never runs and the launcher's cache + // (characters__.json) was only written by SessionStateRegistry's + // login upsert, which records just the launch context's TargetCharacter. An + // account launched with no character picked therefore never got a cache file + // and its launcher dropdown stayed empty. This poll reads the list straight + // from AC's native CharacterSet while char-select is up, whether or not + // auto-login is armed. In the world it only checks a managed flag; the native + // set is read only in CharacterManagementUI. Logout back to char-select + // (LoginLifecycleHooks.ResetObservation) re-arms it, so a new or deleted + // character is picked up too. The file is rewritten only when the list changes. + private const int CharacterListCapturePollIntervalMs = 500; + private static int _characterListCapturePollStarted; + private static readonly object CharacterListCaptureLock = new(); + private static string _lastCharacterListCaptureKey = string.Empty; + private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam); [DllImport("user32.dll")] @@ -86,13 +102,16 @@ internal static class CharacterCaptureHooks private static int _autoLoginEverFired; /// - /// Starts the poll-driven auto-login worker. Call once from InitWorker. - /// No-ops if no TargetCharacter is configured in the launch context, or if - /// the worker is already running. Safe to call before the client window or - /// char-select UI exists — the worker waits for them. + /// Starts the character-list capture poll (always) and the poll-driven + /// auto-login worker. Call once from InitWorker. Auto-login no-ops if no + /// TargetCharacter is configured in the launch context, or if the worker is + /// already running. Safe to call before the client window or char-select UI + /// exists — both workers wait for them. /// public static void Initialize() { + StartCharacterListCapturePoll(); + (_, _, string targetCharacter) = ReadLaunchContext(); if (string.IsNullOrWhiteSpace(targetCharacter)) { @@ -175,6 +194,10 @@ internal static class CharacterCaptureHooks RynthLog.Info($"CharacterCapture: Char-select up — driving direct auto-login for '{targetCharacter}'."); } + // Save the account's character list before logging on, so the + // launcher cache is written even when auto-login is quick. + TryCaptureNativeCharacterList(); + // Direct path: read AC's native CharacterSet and call LogOnCharacter. // No packet required. Retries every tick if it didn't take. if (CharacterManagementHooks.TryLogOnCharacter( @@ -226,6 +249,79 @@ internal static class CharacterCaptureHooks } } + private static void StartCharacterListCapturePoll() + { + if (Interlocked.Exchange(ref _characterListCapturePollStarted, 1) != 0) + return; + + var thread = new Thread(CharacterListCapturePollLoop) + { + Name = "RynthCore.CharacterListCapture", + IsBackground = true + }; + thread.Start(); + } + + private static void CharacterListCapturePollLoop() + { + try + { + while (!EngineLifecycle.IsShuttingDown) + { + Thread.Sleep(CharacterListCapturePollIntervalMs); + + // In the world: no native reads at all. + if (LoginLifecycleHooks.HasObservedLoginComplete) + continue; + + if (!CharacterManagementHooks.TryGetCurrentMode(out int mode) || mode != CharacterManagementUIMode) + continue; + + TryCaptureNativeCharacterList(); + } + } + catch (Exception ex) + { + RynthLog.Compat($"CharacterCapture: Character-list capture poll crashed - {ex.Message}"); + } + finally + { + Interlocked.Exchange(ref _characterListCapturePollStarted, 0); + } + } + + /// + /// Reads the character list from AC's native CharacterSet (char-select only) + /// and saves it to the launcher's character cache for this client's + /// account/server. Writes only when the list differs from the last one seen + /// in this process. Safe to call from any poll thread. + /// + private static void TryCaptureNativeCharacterList() + { + try + { + if (!CharacterManagementHooks.TryReadCharacterNames(out List characters)) + return; + + lock (CharacterListCaptureLock) + { + string key = string.Join("\n", characters); + if (string.Equals(key, _lastCharacterListCaptureKey, StringComparison.Ordinal)) + return; + + _lastCharacterListCaptureKey = key; + RynthLog.Info($"CharacterCapture: Native character set has {characters.Count} chars: {string.Join(", ", characters)}"); + + (string accountName, string serverName, _) = ReadLaunchContext(); + SaveCharacterList(characters, accountName, serverName); + } + } + catch (Exception ex) + { + RynthLog.Compat($"CharacterCapture: Native character-list capture failed - {ex.Message}"); + } + } + /// /// Single char-list double-click at the slot for . /// Fallback for when the direct native LogOnCharacter path isn't taking. @@ -461,7 +557,7 @@ internal static class CharacterCaptureHooks if (!string.IsNullOrWhiteSpace(accountName)) { CharacterCacheStore.Write(accountName, serverName, characters); - RynthLog.Verbose( + RynthLog.Info( !string.IsNullOrWhiteSpace(serverName) ? $"CharacterCapture: Saved {characters.Count} chars for '{accountName}' on '{serverName}'." : $"CharacterCapture: Saved {characters.Count} chars for '{accountName}' (no server name in context)."); diff --git a/src/RynthCore.Engine/Compatibility/CharacterManagementHooks.cs b/src/RynthCore.Engine/Compatibility/CharacterManagementHooks.cs index 74a2d67..7e3f451 100644 --- a/src/RynthCore.Engine/Compatibility/CharacterManagementHooks.cs +++ b/src/RynthCore.Engine/Compatibility/CharacterManagementHooks.cs @@ -184,6 +184,44 @@ internal static class CharacterManagementHooks return false; } + /// + /// Reads the character names in AC's native CharacterSet, in slot order + /// (the order char-select lists them). Read-only: never calls + /// LogOnCharacter. Only reads while CharacterManagementUI is the current + /// mode, so the native set is never touched in the world. Returns false + /// (empty list) when unbound, not at char-select, or the set isn't filled yet. + /// + public static bool TryReadCharacterNames(out List names) + { + names = new List(); + + if (!EnsureBound()) + return false; + + if (!TryGetCurrentMode(out int mode) || mode != CharacterManagementUI) + return false; + + IntPtr charSetPtr = GetCharacterSetPointer(); + if (charSetPtr == IntPtr.Zero) + return false; + + for (int index = 0; index < MaxCharacterSlots; index++) + { + IntPtr identityPtr = _characterSetGetIdentity!(charSetPtr, index); + if (identityPtr == IntPtr.Zero) + continue; + + string? name = ReadAnsiString(_characterSetGetName!(charSetPtr, index)); + uint avatarId = _characterSetGetGid!(charSetPtr, index); + if (string.IsNullOrWhiteSpace(name) || avatarId == 0) + continue; + + names.Add(name.Trim()); + } + + return names.Count > 0; + } + /// /// Returns the count of populated character slots in AC's native /// CharacterSet (slots where GetIdentity returns non-null). Used by the diff --git a/src/RynthCore.Engine/Compatibility/ChatCallbackHooks.cs b/src/RynthCore.Engine/Compatibility/ChatCallbackHooks.cs index 8a7f617..d59efc8 100644 --- a/src/RynthCore.Engine/Compatibility/ChatCallbackHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ChatCallbackHooks.cs @@ -338,6 +338,7 @@ internal static class ChatCallbackHooks try { string? line = ReadWidePString(text); + LogoffOriginProbe.RecordChat($"AC OutgoingChat src={commandSource}", line); // Capture the chat-manager 'this' + command source from the live submit // so ChatCommandDispatcher can re-invoke this function directly later. @@ -568,6 +569,7 @@ internal static class ChatCallbackHooks foreach (char c in line) if (c < 0x20 && c != '\t') return false; // never feed AC control chars + LogoffOriginProbe.RecordChat("OutgoingChat direct", line); try { diff --git a/src/RynthCore.Engine/Compatibility/ChatCommandDispatcher.cs b/src/RynthCore.Engine/Compatibility/ChatCommandDispatcher.cs index 7385a19..924662e 100644 --- a/src/RynthCore.Engine/Compatibility/ChatCommandDispatcher.cs +++ b/src/RynthCore.Engine/Compatibility/ChatCommandDispatcher.cs @@ -132,6 +132,7 @@ internal static unsafe class ChatCommandDispatcher { string trimmed = text.Trim(); if (trimmed.Length == 0) return false; + LogoffOriginProbe.RecordChat("ChatCommandDispatcher", trimmed); // RynthCore engine commands (/rc ...) are handled before plugin // pre-dispatch and before any AC chat routing so they work even @@ -320,6 +321,7 @@ internal static unsafe class ChatCommandDispatcher /// private static bool SimulateChatInput(string command) { + LogoffOriginProbe.RecordChat("SimulateChatInput", command); // Deep-audit finding #18 (2026-06-18): SendToGameWndProc drives // CallWindowProcA directly into AC's WndProc — calling that off the // window-owning thread is a cross-thread WndProc re-entry. Dispatch() diff --git a/src/RynthCore.Engine/Compatibility/ChatHooks.cs b/src/RynthCore.Engine/Compatibility/ChatHooks.cs index ef552f3..aff1674 100644 --- a/src/RynthCore.Engine/Compatibility/ChatHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ChatHooks.cs @@ -65,11 +65,13 @@ internal static class ChatHooks public static volatile bool ChatPanelShown; /// - /// RynthChat is standing in for the retail chat: its panel is open AND "Hide retail chat" - /// is on. Only then is the retail chatbox hidden and Enter routed to RynthChat — whichever - /// chat is visible gets Enter. + /// RynthChat is standing in for the retail chat: in the world, its panel is open AND + /// "Hide retail chat" is on. Only then is the retail chatbox hidden and Enter routed to + /// RynthChat — whichever chat is visible gets Enter. Outside the world Enter is AC's: + /// at character select it enters the game. /// - public static bool RynthChatOwnsChat => SuppressOriginalChat && ChatPanelShown; + public static bool RynthChatOwnsChat => + SuppressOriginalChat && ChatPanelShown && LoginLifecycleHooks.HasObservedLoginComplete; public static IntPtr GmMainChatInstance => _gmMainChatInstance; diff --git a/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs b/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs index c62df03..8769c59 100644 --- a/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs @@ -936,6 +936,7 @@ internal static class ClientHelperHooks return false; RynthLog.Verbose($"Compat: InvokeParser text='{line}'"); + LogoffOriginProbe.RecordChat("InvokeChatParser", line); return ChatCommandDispatcher.Dispatch(line); } catch (Exception ex) diff --git a/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs b/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs index eea8fed..4ef0fb2 100644 --- a/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs @@ -216,6 +216,14 @@ internal static class ClientObjectHooks private static DateTime _lastObjectIdentityPrefetchUtc = DateTime.MinValue; private static bool _loggedObjectIdentityServe; private const int ObjectIdentityPrefetchThrottleMs = 500; + // Every id the same walk visited, swapped whole (readers never see a half-built array). + private static volatile uint[] _liveObjectIds = Array.Empty(); + + /// + /// Ids of every weenie object the client knew at the last identity snapshot (main-thread + /// walk, at most ~0.5 s old). Empty until the first snapshot. + /// + public static uint[] LiveObjectIds => _liveObjectIds; // Position snapshot — mirrors the attackable/identity snapshots, but sampled // EVERY EndScene (no throttle) because positions change per-frame. The @@ -1457,6 +1465,47 @@ internal static class ClientObjectHooks } } + /// + /// Reads one 4-byte field of an object's PublicWeenieDesc by its offset from the + /// start of the PWD (e.g. +56 _type, +60 _value, +96 _stackSize, +116 _burden; layout + /// in Chorizite Weenie.cs:1734, same base as ). + /// MAIN THREAD ONLY: off the main thread it returns false without touching AC memory + /// (a snapshot-cached weenie pointer can be freed and reused under us). Both ends of + /// the read are page-probed, so a bad pointer fails closed instead of faulting. + /// Used by vendor trading to read item value/burden for pack items, whose qualities + /// pointer is null (so InqInt can't serve them). + /// + internal static bool TryReadPwdInt32(uint objectId, int pwdFieldOffset, out int value) + { + value = 0; + if (pwdFieldOffset < 0 || pwdFieldOffset > 172 || (pwdFieldOffset & 3) != 0) + return false; + if (!MainThreadGuard.IsOnMainThread()) + return false; + 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; + IntPtr fieldAddr = weeniePtr + _weeniePhysicsObjOffset + 4 + pwdFieldOffset; + if (!IsReadablePointer(fieldAddr) || !IsReadablePointer(fieldAddr + 3)) + return false; + value = Marshal.ReadInt32(fieldAddr); + return true; + } + catch + { + return false; + } + } + /// /// Reads PublicWeenieDesc._wcid directly from the weenie struct. /// Returns the Weenie Class ID (WCID) for the given object. @@ -2456,9 +2505,11 @@ internal static class ClientObjectHooks { var nameSnap = new Dictionary(); var typeSnap = new Dictionary(); + var idSnap = new List(); int n = CObjectMaintHooks.EnumerateLiveWeenieObjectIds(id => { + idSnap.Add(id); if (TryGetObjectName(id, out string nm) && nm.Length > 0) nameSnap[id] = nm; if (TryGetItemType(id, out uint typeFlags)) @@ -2477,6 +2528,7 @@ internal static class ClientObjectHooks foreach (var kv in typeSnap) _objectTypeCache[kv.Key] = kv.Value; } + _liveObjectIds = idSnap.ToArray(); if (!_loggedObjectIdentityServe) { diff --git a/src/RynthCore.Engine/Compatibility/GameTickHooks.cs b/src/RynthCore.Engine/Compatibility/GameTickHooks.cs index 502770d..7b4d7c1 100644 --- a/src/RynthCore.Engine/Compatibility/GameTickHooks.cs +++ b/src/RynthCore.Engine/Compatibility/GameTickHooks.cs @@ -100,6 +100,9 @@ internal static class GameTickHooks // wedges before the new generation's EndScene hook installs. try { MainThreadHangWatchdog.MainThreadBeatNoFrame(); } catch { } + // Diag (diag/logoff-origin): 1 Hz sample of the client's own input-idle clock. + try { LogoffOriginProbe.SampleIdleOnGameThread(); } + catch { } // Drain any queued cast BEFORE AC's game-logic tick: SelectItem sets AC's // selection and the cast initiates, then THIS SAME UseTime call processes it to // completion — mimicking AC's natural input -> UseTime flow. (Draining AFTER the diff --git a/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs b/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs index 7fff3ec..7d5f9b1 100644 --- a/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs +++ b/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs @@ -98,7 +98,12 @@ internal static class HeartbeatLogger // Soak health: rec climbs during combat/loot; fcl stays flat. long rec = 0, fcl = 0; try { rec = BusyCountHooks.ReconcileCount; fcl = BusyCountHooks.ForceClearCount; } catch { } - RynthLog.Info($"hb #{tick} up={(nowMs - startMs) / 1000}s fps={fps} plug={pps}/s ws={wsMb}MB login={login} qd={dropped} rec={rec} fcl={fcl}"); + // idle = the client's own input-idle clock (diag/logoff-origin); the retail + // client logs itself off past InactiveTimeBeforeLogout. Omitted when unknown. + int idle = -1; + try { idle = LogoffOriginProbe.IdleSecondsForHeartbeat; } catch { } + string idleField = idle >= 0 ? $" idle={idle}s" : ""; + RynthLog.Info($"hb #{tick} up={(nowMs - startMs) / 1000}s fps={fps} plug={pps}/s ws={wsMb}MB login={login} qd={dropped} rec={rec} fcl={fcl}{idleField}"); // Cache this client's live metrics so the GetEngineStatusJson host bridge can serve // them to a plugin (the RynthRemote status export). No file write, no networking. diff --git a/src/RynthCore.Engine/Compatibility/LogoffOriginProbe.cs b/src/RynthCore.Engine/Compatibility/LogoffOriginProbe.cs new file mode 100644 index 0000000..610f10b --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/LogoffOriginProbe.cs @@ -0,0 +1,802 @@ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using RynthCore.Engine.Hooking; + +namespace RynthCore.Engine.Compatibility; + +/// +/// DIAGNOSTIC (branch diag/logoff-origin, 2026-09-27): pins down which client code path +/// asks the server to log the character off. Lucy logged off by herself mid-fight at +/// 14:28:20, 15:36:52 and 16:43:30; the ExecuteLogOff caller was the server's +/// CharacterLogOff (0xF653) handler, and ACE only sends that in reply to a logoff the +/// client requested. This probe watches the request side. It changes no behaviour. +/// +/// Hooks (all log caller frames via ): +/// - CPlayerSystem::LogOffCharacter(bool immediate) every client logoff entry point +/// - CPlayerSystem::RequestLogOff() prints "Logging off...", sends +/// - Proto_UI::LogOffCharacter(uint gid) builds + sends the 0xF653 request +/// - CPlayerSystem::SetLogOffStarted() ~3 s after the request (timeline) +/// - ClientNet::LogOffServer() transport-level disconnect +/// +/// Context, dumped once when a logoff is requested (or when one completes with no request): +/// - client input idle time vs InactiveTimeBeforeLogout (the retail client logs itself +/// off from ClientUISystem::UseTime when Timer::cur_time minus CInputManager's +/// last-input time exceeds it; 1200 s on the reference client) +/// - game-window foreground/focus state and when it last changed +/// - ring buffers: the last window messages the WndProc subclass saw (keys, clicks, +/// focus, close, syscommand) and the last chat lines through the engine's chat paths +/// - an acclient-only stack sweep (return addresses above the detour; may be stale) +/// +/// Idle milestones are also logged as the idle time climbs toward the threshold, and the +/// heartbeat line carries idle=Ns. +/// +/// CommandInterpreter::HandleLogOff (0x006B4270) is NOT hooked: it is a two-instruction +/// thunk to CommandInterpreter::Disable (vtable +0x84) that runs as a consequence of a +/// logoff, not a requester. +/// +internal static unsafe class LogoffOriginProbe +{ + // Fallback VAs on the reference retail client (4,841,472 bytes, SizeOfImage 0x56D000). + // The patterns below are the source of truth (cut + verified with tools/pe_pattern.py). + private const int ProbeLogOffCharacterVa = 0x005642C0; // CPlayerSystem::LogOffCharacter(bool) + private const int ProbeRequestLogOffVa = 0x00563B70; // CPlayerSystem::RequestLogOff() + private const int ProbeProtoLogOffVa = 0x005475E0; // Proto_UI::LogOffCharacter(uint gid), cdecl + private const int ProbeSetLogOffStartedVa = 0x0055E4F0; // CPlayerSystem::SetLogOffStarted() + private const int ProbeLogOffServerVa = 0x00544AB0; // ClientNet::LogOffServer() + private const int ProbeTimerCurTimeVa = 0x008379A8; // Timer::cur_time (double, seconds) + private const int ProbeInputManagerVa = 0x00837FF4; // ICIDM::s_cidm (CInputManager*) + private const int ProbeIdleLimitVa = 0x007CEB70; // InactiveTimeBeforeLogout (double, 1200.0) + + private const int ReferenceImageSize = 0x0056D000; + + // push esi; mov esi,ecx; push 0; lea ecx,[esi+0x30]; call; mov al,[esp+8]; test al,al + private static readonly byte?[] LogOffCharacterPattern = [ 0x56, 0x8B, 0xF1, 0x6A, 0x00, 0x8D, 0x4E, 0x30, 0xE8, null, null, null, null, 0x8A, 0x44, 0x24, 0x08, 0x84, 0xC0 ]; + // push ecx; push esi; push edi; push "Logging off...\n"; mov esi,ecx; push 0; lea ecx,[esp+0x10]; call + private static readonly byte?[] RequestLogOffPattern = [ 0x51, 0x56, 0x57, 0x68, null, null, null, null, 0x8B, 0xF1, 0x6A, 0x00, 0x8D, 0x4C, 0x24, 0x10, 0xE8 ]; + // push 8; call alloc; mov ecx,[esp+8]; push 8; mov dword ptr [eax],0xF653 + private static readonly byte?[] ProtoLogOffPattern = [ 0x6A, 0x08, 0xE8, null, null, null, null, 0x8B, 0x4C, 0x24, 0x08, 0x6A, 0x08, 0xC7, 0x00, 0x53, 0xF6, 0x00, 0x00 ]; + // mov byte ptr [ecx+0x221],0; ret + private static readonly byte?[] SetLogOffStartedPattern = [ 0xC6, 0x81, 0x21, 0x02, 0x00, 0x00, 0x00, 0xC3 ]; + // push ebp; push esi; push edi; mov ebp,ecx; mov esi,[ebp+0x8820]; push 0x1C; call + private static readonly byte?[] LogOffServerPattern = [ 0x55, 0x56, 0x57, 0x8B, 0xE9, 0x8B, 0xB5, 0x20, 0x88, 0x00, 0x00, 0x6A, 0x1C, 0xE8 ]; + + // Data globals by code-xref (operand at offset 2). + private static readonly byte?[] CurTimeXrefPattern = [ 0xDD, 0x05, null, null, null, null, 0x56, 0xDD ]; + // ClientUISystem::UseTime: mov ebp,[ICIDM::s_cidm]; push esi; push edi; lea eax,[esp+0x10] + private static readonly byte?[] InputManagerXrefPattern = [ 0x8B, 0x2D, null, null, null, null, 0x56, 0x57, 0x8D, 0x44, 0x24, 0x10 ]; + // ClientUISystem::UseTime: fcomp qword ptr [InactiveTimeBeforeLogout]; fnstsw ax; test ah,0x41; jne; cmp + private static readonly byte?[] IdleLimitXrefPattern = [ 0xDC, 0x1D, null, null, null, null, 0xDF, 0xE0, 0xF6, 0xC4, 0x41, 0x75, 0x22, 0x3B ]; + + private static IntPtr _origLogOffCharacter; + private static IntPtr _origRequestLogOff; + private static IntPtr _origProtoLogOff; + private static IntPtr _origSetLogOffStarted; + private static IntPtr _origLogOffServer; + + private static IntPtr _curTimeVa; + private static IntPtr _inputMgrSlotVa; + private static IntPtr _idleLimitVa; + private static int _lastInputOffset = -1; + private static bool _inputOffsetProbed; + + private static long _acBase; + private static long _acImageSize; + private static long _acTextLo; + private static long _acTextHi; + private static bool _labelsValid; + private static bool _initialized; + + public static void Initialize() + { + if (_initialized) + return; + _initialized = true; + + if (!AcClientModule.TryReadTextSection(out AcClientTextSection text)) + { + RynthLog.Compat("LogoffProbe: acclient.exe not available - probe not installed."); + return; + } + + _acBase = text.ModuleBase.ToInt64(); + _acImageSize = text.ImageSize; + _acTextLo = text.TextBaseVa; + _acTextHi = text.TextBaseVa + (long)text.Bytes.Length; + _labelsValid = text.ImageSize == ReferenceImageSize; + + _curTimeVa = HookResolver.ResolveData(text, "LogoffProbe.Timer_cur_time", CurTimeXrefPattern, 2, ProbeTimerCurTimeVa).Address; + _inputMgrSlotVa = HookResolver.ResolveData(text, "LogoffProbe.ICIDM_s_cidm", InputManagerXrefPattern, 2, ProbeInputManagerVa).Address; + _idleLimitVa = HookResolver.ResolveData(text, "LogoffProbe.InactiveTimeBeforeLogout", IdleLimitXrefPattern, 2, ProbeIdleLimitVa).Address; + + try + { + double limit = _idleLimitVa != IntPtr.Zero ? *(double*)_idleLimitVa : double.NaN; + RynthLog.Compat($"LogoffProbe: client idle auto-logoff threshold (InactiveTimeBeforeLogout @ 0x{_idleLimitVa.ToInt32():X8}) = {limit:0.#} s. ClientUISystem::UseTime calls LogOffCharacter(0) once Timer::cur_time - last input exceeds it."); + } + catch { } + + int hooked = 0; + HookResolver.ResolveResult r; + + r = HookResolver.Resolve(text, "LogoffProbe.LogOffCharacter", LogOffCharacterPattern, ProbeLogOffCharacterVa); + delegate* unmanaged[Thiscall] dLogOffCharacter = &LogOffCharacterDetour; + if (TryHook(r, "CPlayerSystem::LogOffCharacter", (IntPtr)dLogOffCharacter, out _origLogOffCharacter)) hooked++; + + r = HookResolver.Resolve(text, "LogoffProbe.RequestLogOff", RequestLogOffPattern, ProbeRequestLogOffVa); + delegate* unmanaged[Thiscall] dRequestLogOff = &RequestLogOffDetour; + if (TryHook(r, "CPlayerSystem::RequestLogOff", (IntPtr)dRequestLogOff, out _origRequestLogOff)) hooked++; + + r = HookResolver.Resolve(text, "LogoffProbe.Proto_UI_LogOffCharacter", ProtoLogOffPattern, ProbeProtoLogOffVa); + delegate* unmanaged[Cdecl] dProtoLogOff = &ProtoLogOffDetour; + if (TryHook(r, "Proto_UI::LogOffCharacter", (IntPtr)dProtoLogOff, out _origProtoLogOff)) hooked++; + + r = HookResolver.Resolve(text, "LogoffProbe.SetLogOffStarted", SetLogOffStartedPattern, ProbeSetLogOffStartedVa); + delegate* unmanaged[Thiscall] dSetLogOffStarted = &SetLogOffStartedDetour; + if (TryHook(r, "CPlayerSystem::SetLogOffStarted", (IntPtr)dSetLogOffStarted, out _origSetLogOffStarted)) hooked++; + + r = HookResolver.Resolve(text, "LogoffProbe.ClientNet_LogOffServer", LogOffServerPattern, ProbeLogOffServerVa); + delegate* unmanaged[Thiscall] dLogOffServer = &LogOffServerDetour; + if (TryHook(r, "ClientNet::LogOffServer", (IntPtr)dLogOffServer, out _origLogOffServer)) hooked++; + + RynthLog.Compat($"LogoffProbe: {hooked}/5 logoff-origin hooks installed (labels {(_labelsValid ? "on" : "off - not the reference client")})."); + } + + private static bool TryHook(HookResolver.ResolveResult r, string name, IntPtr detour, out IntPtr original) + { + original = IntPtr.Zero; + if (!r.Success) + { + RynthLog.Compat($"LogoffProbe: {name} unresolved - not hooked."); + return false; + } + try + { + MinHook.Hook(r.Address, detour, out original); + RynthLog.Compat($"LogoffProbe: {name} hooked @ 0x{r.Address.ToInt32():X8} ({r.Detail})."); + return true; + } + catch (Exception ex) + { + original = IntPtr.Zero; + RynthLog.Compat($"LogoffProbe: {name} hook failed: {ex.GetType().Name}: {ex.Message}"); + return false; + } + } + + // ── Detours (game thread; must never throw into AC) ────────────────────── + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })] + private static void LogOffCharacterDetour(IntPtr thisPtr, byte immediate) + { + try { OnRequest("CPlayerSystem::LogOffCharacter", $"immediate={immediate}"); } + catch { } + ((delegate* unmanaged[Thiscall])_origLogOffCharacter)(thisPtr, immediate); + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })] + private static void RequestLogOffDetour(IntPtr thisPtr) + { + try { OnRequest("CPlayerSystem::RequestLogOff", ""); } + catch { } + ((delegate* unmanaged[Thiscall])_origRequestLogOff)(thisPtr); + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })] + private static int ProtoLogOffDetour(uint gid) + { + try + { + Volatile.Write(ref _lastProtoSendMs, Environment.TickCount64); + OnRequest("Proto_UI::LogOffCharacter", $"gid=0x{gid:X8} (sends 0xF653 to the server)"); + } + catch { } + return ((delegate* unmanaged[Cdecl])_origProtoLogOff)(gid); + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })] + private static void SetLogOffStartedDetour(IntPtr thisPtr) + { + try + { + string since = _lastRequestMs != 0 ? $" {(Environment.TickCount64 - _lastRequestMs) / 1000.0:0.00}s after the request" : " (no request seen)"; + RynthLog.Info($"LogoffProbe: CPlayerSystem::SetLogOffStarted{since}."); + LogoutLifecycleHooks.LogCaller("SetLogOffStarted", "LogoffProbe"); + } + catch { } + ((delegate* unmanaged[Thiscall])_origSetLogOffStarted)(thisPtr); + } + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvThiscall) })] + private static void LogOffServerDetour(IntPtr thisPtr) + { + try + { + RynthLog.Info("LogoffProbe: ClientNet::LogOffServer (transport disconnect) entered."); + LogoutLifecycleHooks.LogCaller("ClientNet::LogOffServer", "LogoffProbe"); + } + catch { } + ((delegate* unmanaged[Thiscall])_origLogOffServer)(thisPtr); + } + + // ── Request / completion tracking ──────────────────────────────────────── + + private static long _lastRequestMs; + private static string? _lastRequestDesc; + private static long _lastProtoSendMs; + private static long _lastDumpMs; + + private static void OnRequest(string fn, string args) + { + long now = Environment.TickCount64; + IntPtr caller = LogoutLifecycleHooks.LogCaller(fn, "LogoffProbe"); + string callerText = DescribeAcclientAddress(caller); + + string idleText = "idle=?"; + bool idleOver = false; + if (TryReadIdle(out double idle, out double limit, out _, out _)) + { + idleOver = idle > limit; + idleText = $"idle={idle:0.0}s/{limit:0.#}s{(idleOver ? " (OVER threshold: matches the client idle auto-logoff)" : "")}"; + } + + string argText = args.Length > 0 ? $"({args})" : "()"; + RynthLog.Warn($"LogoffProbe: logoff requested - {fn}{argText} caller={callerText} {idleText} {DescribeFocus()}"); + + // The first request of a cycle names the path; later ones (RequestLogOff, the send) + // are the same logoff continuing, so keep the original description. + if (_lastRequestMs == 0 || now - _lastRequestMs > 30_000) + { + _lastRequestMs = now; + _lastRequestDesc = $"{fn}{argText} from {callerText}"; + } + + if (now - _lastDumpMs > 30_000) + { + _lastDumpMs = now; + DumpContext($"request via {fn}"); + } + } + + /// + /// Called once per logout cycle from the ExecuteLogOff / RecvNotice_Logoff detours. + /// Says whether the client asked for this logoff, and if not, dumps the context. + /// + internal static void OnLogoffCompleted(string via) + { + try + { + long now = Environment.TickCount64; + long req = _lastRequestMs; + if (req != 0 && now - req < 120_000) + { + long send = Volatile.Read(ref _lastProtoSendMs); + string sendText = send != 0 && now - send < 120_000 ? $"{(now - send) / 1000.0:0.00}s after the 0xF653 send" : "no 0xF653 send seen"; + RynthLog.Info($"LogoffProbe: logoff completed via {via} {(now - req) / 1000.0:0.00}s after the client request ({sendText}). Request: {_lastRequestDesc}."); + } + else + { + RynthLog.Warn($"LogoffProbe: logoff completed via {via} with NO client logoff request in the last 120 s - server-initiated, or a path this probe does not hook."); + if (now - _lastDumpMs > 30_000) + { + _lastDumpMs = now; + DumpContext($"completion via {via} without a request"); + } + } + _lastRequestMs = 0; + _lastRequestDesc = null; + } + catch { } + } + + // ── Idle time (client's own idle-logoff clock) ─────────────────────────── + + private static long _lastIdleSampleMs; + private static int _idleSecondsForHb = -1; + private static double _prevIdle; + private static int _idleMilestoneIdx; + private static bool _idleOverLogged; + private static bool _idleDisabledLogged; + // Seconds before the threshold at which a milestone line is logged. + private static readonly int[] IdleMilestonesBefore = [900, 600, 300, 120, 60, 30, 10]; + + /// Client input idle seconds for the heartbeat line, or -1 when unknown. + internal static int IdleSecondsForHeartbeat => Volatile.Read(ref _idleSecondsForHb); + + /// + /// Called from the Client::UseTime detour (AC's game thread). Samples once a second. + /// + internal static void SampleIdleOnGameThread() + { + long now = Environment.TickCount64; + if (now - _lastIdleSampleMs < 1000) + return; + _lastIdleSampleMs = now; + + try + { + if (!TryReadIdle(out double idle, out double limit, out _, out _)) + { + Volatile.Write(ref _idleSecondsForHb, -1); + return; + } + Volatile.Write(ref _idleSecondsForHb, idle < 0 ? 0 : (int)Math.Min(idle, int.MaxValue)); + + // Input arrived since the last sample: the client reset its idle clock. + if (idle + 1.5 < _prevIdle) + { + if (_idleMilestoneIdx > 0 || _idleOverLogged) + RynthLog.Info($"LogoffProbe: client input idle clock reset after {_prevIdle:0}s (input received). {DescribeFocus()}"); + _idleMilestoneIdx = 0; + _idleOverLogged = false; + } + _prevIdle = idle; + + // ClientUISystem::UseTime only logs off an in-world player; skip the + // milestone lines at character select. + bool inWorld = false; + try { inWorld = LoginLifecycleHooks.HasObservedLoginComplete; } catch { } + if (!inWorld) + return; + + if (double.IsNaN(limit) || double.IsInfinity(limit) || limit <= 60) + { + if (!_idleDisabledLogged) + { + _idleDisabledLogged = true; + RynthLog.Info($"LogoffProbe: idle auto-logoff threshold is {limit} - milestones off."); + } + return; + } + + // The client counts only real keyboard/mouse input, so a character a bot is + // playing idles out after InactiveTimeBeforeLogout (1200 s) and logs itself off + // mid-fight - Lucy, three times on 2026-09-27, each 1206 s after the window lost + // focus. Keep the idle clock fresh while in the world (PreventIdleLogoff). + if (Plugins.EngineSettings.PreventIdleLogoff && idle > IdleRefreshAfterSec && TryRefreshLastInput()) + { + long nowMs = Environment.TickCount64; + if (nowMs - _lastIdleRefreshLogMs > 600_000) + { + _lastIdleRefreshLogMs = nowMs; + RynthLog.Info($"LogoffProbe: reset the client's idle clock at {idle:0}s idle so the {limit:0.#}s idle auto-logoff can't fire (PreventIdleLogoff; logged at most every 10 min). {DescribeFocus()}"); + } + _prevIdle = 0; + return; + } + + while (_idleMilestoneIdx < IdleMilestonesBefore.Length && idle >= limit - IdleMilestonesBefore[_idleMilestoneIdx]) + { + RynthLog.Info($"LogoffProbe: client input idle {idle:0}s - the client auto-logs-off at {limit:0.#}s ({limit - idle:0}s left). {DescribeFocus()}"); + _idleMilestoneIdx++; + } + + if (!_idleOverLogged && idle > limit) + { + _idleOverLogged = true; + RynthLog.Warn($"LogoffProbe: client input idle {idle:0.0}s is over the {limit:0.#}s threshold - ClientUISystem::UseTime should call LogOffCharacter(0) now. {DescribeFocus()}"); + } + } + catch { } + } + + private const double IdleRefreshAfterSec = 120; + private static long _lastIdleRefreshLogMs = -600_000; + + /// Sets the input manager's last-input time to Timer::cur_time, as real input + /// would. Game thread only (called from SampleIdleOnGameThread). + private static bool TryRefreshLastInput() + { + if (_curTimeVa == IntPtr.Zero || _inputMgrSlotVa == IntPtr.Zero) + return false; + IntPtr mgr = *(IntPtr*)_inputMgrSlotVa; + if (mgr == IntPtr.Zero) + return false; + int off = ResolveLastInputOffset(mgr); + if (off < 0) + return false; + *(double*)((byte*)mgr + off) = *(double*)_curTimeVa; + return true; + } + + /// Reads the same values ClientUISystem::UseTime compares. Game thread only. + private static bool TryReadIdle(out double idle, out double limit, out double curTime, out double lastInput) + { + idle = 0; limit = double.NaN; curTime = 0; lastInput = 0; + if (_curTimeVa == IntPtr.Zero || _inputMgrSlotVa == IntPtr.Zero) + return false; + + IntPtr mgr = *(IntPtr*)_inputMgrSlotVa; + if (mgr == IntPtr.Zero) + return false; + + int off = ResolveLastInputOffset(mgr); + if (off < 0) + return false; + + curTime = *(double*)_curTimeVa; + lastInput = *(double*)((byte*)mgr + off); + if (_idleLimitVa != IntPtr.Zero) + limit = *(double*)_idleLimitVa; + idle = curTime - lastInput; + return true; + } + + /// + /// ClientUISystem::UseTime gets the last-input time from vtable slot 5 of the input + /// manager, CInputManager::GetLastInputTimestamp, which is "fld qword [ecx+off]; ret". + /// Read the field offset out of that body so the probe never guesses a layout. + /// + private static int ResolveLastInputOffset(IntPtr mgr) + { + if (_inputOffsetProbed) + return _lastInputOffset; + _inputOffsetProbed = true; + + long vtbl = (*(IntPtr*)mgr).ToInt64(); + if (vtbl < _acBase || vtbl + 0x18 > _acBase + _acImageSize) + { + RynthLog.Compat($"LogoffProbe: input manager vtable 0x{vtbl:X8} is outside acclient - idle probe off."); + return -1; + } + long fn = (*(IntPtr*)(vtbl + 0x14)).ToInt64(); + if (fn < _acTextLo || fn + 4 > _acTextHi) + { + RynthLog.Compat($"LogoffProbe: GetLastInputTimestamp 0x{fn:X8} is outside acclient .text - idle probe off."); + return -1; + } + byte* p = (byte*)fn; + if (p[0] == 0xDD && p[1] == 0x41 && p[3] == 0xC3) + { + _lastInputOffset = p[2]; + RynthLog.Compat($"LogoffProbe: CInputManager last-input time at +0x{_lastInputOffset:X2} (GetLastInputTimestamp @ 0x{fn:X8})."); + } + else + { + RynthLog.Compat($"LogoffProbe: GetLastInputTimestamp @ 0x{fn:X8} has unexpected bytes {p[0]:X2} {p[1]:X2} {p[2]:X2} {p[3]:X2} - idle probe off."); + } + return _lastInputOffset; + } + + // ── Ring buffers ───────────────────────────────────────────────────────── + + private const uint WM_DESTROY = 0x0002; + private const uint WM_ACTIVATE = 0x0006; + private const uint WM_SETFOCUS = 0x0007; + private const uint WM_KILLFOCUS = 0x0008; + private const uint WM_CLOSE = 0x0010; + private const uint WM_QUERYENDSESSION = 0x0011; + private const uint WM_ENDSESSION = 0x0016; + private const uint WM_ACTIVATEAPP = 0x001C; + private const uint WM_KEYDOWN = 0x0100; + private const uint WM_KEYUP = 0x0101; + private const uint WM_SYSKEYDOWN = 0x0104; + private const uint WM_SYSKEYUP = 0x0105; + private const uint WM_SYSCOMMAND = 0x0112; + private const uint WM_MOUSEMOVE = 0x0200; + private const uint WM_LBUTTONDOWN = 0x0201; + private const uint WM_RBUTTONDOWN = 0x0204; + private const uint WM_MBUTTONDOWN = 0x0207; + private const uint WM_XBUTTONDOWN = 0x020B; + + private struct MsgEntry + { + public long Ms; + public uint Msg; + public int WParam; + public int LParam; + public bool Synthetic; + } + + private struct ChatEntry + { + public long Ms; + public string Source; + public string Text; + } + + private const int MsgRingSize = 24; + private const int ChatRingSize = 16; + private static readonly MsgEntry[] _msgRing = new MsgEntry[MsgRingSize]; + private static readonly ChatEntry[] _chatRing = new ChatEntry[ChatRingSize]; + private static int _msgCount; + private static int _chatCount; + private static readonly object _ringLock = new(); + + private static long _lastMouseMoveMs; + private static long _lastRealKeyMs; + private static long _lastRealClickMs; + private static long _lastKillFocusMs; + private static long _lastSetFocusMs; + + /// + /// Records an input/focus/close message seen by the game WndProc subclass + /// ( = false) or sent by the engine through + /// Win32Backend.SendToGameWndProc (true). Cheap filter first; never throws. + /// + internal static void RecordWndMsg(uint msg, IntPtr wParam, IntPtr lParam, bool synthetic) + { + try + { + long now; + switch (msg) + { + case WM_MOUSEMOVE: + if (!synthetic) Volatile.Write(ref _lastMouseMoveMs, Environment.TickCount64); + return; + case WM_KEYDOWN: + case WM_SYSKEYDOWN: + // Skip auto-repeat (bit 30 = key was already down) so a held key can't flood the ring. + if (((long)lParam & 0x40000000) != 0) return; + now = Environment.TickCount64; + if (!synthetic) Volatile.Write(ref _lastRealKeyMs, now); + break; + case WM_KEYUP: + case WM_SYSKEYUP: + now = Environment.TickCount64; + if (!synthetic) Volatile.Write(ref _lastRealKeyMs, now); + break; + case WM_LBUTTONDOWN: + case WM_RBUTTONDOWN: + case WM_MBUTTONDOWN: + case WM_XBUTTONDOWN: + now = Environment.TickCount64; + if (!synthetic) Volatile.Write(ref _lastRealClickMs, now); + break; + case WM_SETFOCUS: + now = Environment.TickCount64; + Volatile.Write(ref _lastSetFocusMs, now); + break; + case WM_KILLFOCUS: + now = Environment.TickCount64; + Volatile.Write(ref _lastKillFocusMs, now); + break; + case WM_DESTROY: + case WM_ACTIVATE: + case WM_CLOSE: + case WM_QUERYENDSESSION: + case WM_ENDSESSION: + case WM_ACTIVATEAPP: + case WM_SYSCOMMAND: + now = Environment.TickCount64; + break; + default: + return; + } + + lock (_ringLock) + { + ref MsgEntry e = ref _msgRing[_msgCount % MsgRingSize]; + e.Ms = now; + e.Msg = msg; + e.WParam = (int)(long)wParam; + e.LParam = (int)(long)lParam; + e.Synthetic = synthetic; + _msgCount++; + } + } + catch { } + } + + /// Records a chat line passing through one of the engine's chat paths. + internal static void RecordChat(string source, string? text) + { + try + { + if (text == null) return; + string t = text.Length > 120 ? text.Substring(0, 120) + "..." : text; + lock (_ringLock) + { + ref ChatEntry e = ref _chatRing[_chatCount % ChatRingSize]; + e.Ms = Environment.TickCount64; + e.Source = source; + e.Text = t; + _chatCount++; + } + } + catch { } + } + + // ── Context dump ───────────────────────────────────────────────────────── + + [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); + [DllImport("user32.dll")] private static extern IntPtr GetFocus(); + [DllImport("user32.dll")] private static extern IntPtr GetActiveWindow(); + [DllImport("user32.dll")] private static extern bool IsIconic(IntPtr hWnd); + [DllImport("kernel32.dll")] private static extern void GetCurrentThreadStackLimits(out IntPtr lowLimit, out IntPtr highLimit); + + private static string Ago(long ms, long now) + => ms == 0 ? "never" : $"{(now - ms) / 1000.0:0.0}s ago"; + + private static string DescribeFocus() + { + try + { + IntPtr game = ImGuiBackend.Win32Backend.GameHwnd; + long now = Environment.TickCount64; + IntPtr fg = GetForegroundWindow(); + int fgGame = game != IntPtr.Zero && fg == game ? 1 : 0; + int focusGame = game != IntPtr.Zero && GetFocus() == game ? 1 : 0; + int iconic = game != IntPtr.Zero && IsIconic(game) ? 1 : 0; + return $"fg={fgGame} focus={focusGame} min={iconic} killfocus={Ago(Volatile.Read(ref _lastKillFocusMs), now)} setfocus={Ago(Volatile.Read(ref _lastSetFocusMs), now)}"; + } + catch { return "fg=?"; } + } + + private static void DumpContext(string trigger) + { + try + { + long now = Environment.TickCount64; + DateTime wallNow = DateTime.Now; + var sb = new StringBuilder(); + sb.Append($"LogoffProbe: ---- context dump ({trigger}) ----"); + + if (TryReadIdle(out double idle, out double limit, out double cur, out double last)) + sb.Append($"\n idle: Timer::cur_time={cur:0.000} lastInput={last:0.000} idle={idle:0.0}s threshold={limit:0.#}s"); + else + sb.Append("\n idle: unavailable"); + + IntPtr game = ImGuiBackend.Win32Backend.GameHwnd; + IntPtr fg = GetForegroundWindow(); + sb.Append($"\n window: game=0x{game.ToInt64():X} foreground=0x{fg.ToInt64():X} active=0x{GetActiveWindow().ToInt64():X} focus=0x{GetFocus().ToInt64():X} minimized={(game != IntPtr.Zero && IsIconic(game) ? 1 : 0)}"); + sb.Append($"\n engine-seen input: key={Ago(Volatile.Read(ref _lastRealKeyMs), now)} click={Ago(Volatile.Read(ref _lastRealClickMs), now)} mousemove={Ago(Volatile.Read(ref _lastMouseMoveMs), now)} killfocus={Ago(Volatile.Read(ref _lastKillFocusMs), now)} setfocus={Ago(Volatile.Read(ref _lastSetFocusMs), now)}"); + + sb.Append("\n acclient stack sweep (may include stale frames):"); + AppendStackSweep(sb); + + MsgEntry[] msgs; + ChatEntry[] chats; + int msgCount, chatCount; + lock (_ringLock) + { + msgs = (MsgEntry[])_msgRing.Clone(); + chats = (ChatEntry[])_chatRing.Clone(); + msgCount = _msgCount; + chatCount = _chatCount; + } + + int mn = Math.Min(msgCount, MsgRingSize); + sb.Append($"\n last {mn} window messages (of {msgCount}):"); + for (int i = msgCount - mn; i < msgCount; i++) + { + MsgEntry e = msgs[i % MsgRingSize]; + sb.Append($"\n {Clock(wallNow, now, e.Ms)} {(e.Synthetic ? "synth " : "")}{DescribeMsg(e)}"); + } + + int cn = Math.Min(chatCount, ChatRingSize); + sb.Append($"\n last {cn} engine chat lines (of {chatCount}):"); + for (int i = chatCount - cn; i < chatCount; i++) + { + ChatEntry e = chats[i % ChatRingSize]; + sb.Append($"\n {Clock(wallNow, now, e.Ms)} [{e.Source}] '{e.Text}'"); + } + + sb.Append("\nLogoffProbe: ---- end context dump ----"); + RynthLog.Info(sb.ToString()); + } + catch (Exception ex) + { + try { RynthLog.Info($"LogoffProbe: context dump failed: {ex.GetType().Name}: {ex.Message}"); } catch { } + } + } + + private static string Clock(DateTime wallNow, long now, long ms) + => $"{wallNow.AddMilliseconds(-(now - ms)):HH:mm:ss.fff} ({(ms - now) / 1000.0:0.0}s)"; + + private static string DescribeMsg(MsgEntry e) + { + switch (e.Msg) + { + case WM_KEYDOWN: return $"WM_KEYDOWN vk=0x{e.WParam & 0xFF:X2}{(IsExtended(e.LParam) ? " ext" : "")}"; + case WM_KEYUP: return $"WM_KEYUP vk=0x{e.WParam & 0xFF:X2}{(IsExtended(e.LParam) ? " ext" : "")}"; + case WM_SYSKEYDOWN: return $"WM_SYSKEYDOWN vk=0x{e.WParam & 0xFF:X2} alt={((e.LParam >> 29) & 1)}"; + case WM_SYSKEYUP: return $"WM_SYSKEYUP vk=0x{e.WParam & 0xFF:X2} alt={((e.LParam >> 29) & 1)}"; + case WM_LBUTTONDOWN: return $"WM_LBUTTONDOWN ({(short)(e.LParam & 0xFFFF)},{(short)((e.LParam >> 16) & 0xFFFF)})"; + case WM_RBUTTONDOWN: return $"WM_RBUTTONDOWN ({(short)(e.LParam & 0xFFFF)},{(short)((e.LParam >> 16) & 0xFFFF)})"; + case WM_MBUTTONDOWN: return "WM_MBUTTONDOWN"; + case WM_XBUTTONDOWN: return "WM_XBUTTONDOWN"; + case WM_SETFOCUS: return $"WM_SETFOCUS from=0x{e.WParam:X}"; + case WM_KILLFOCUS: return $"WM_KILLFOCUS to=0x{e.WParam:X}"; + case WM_ACTIVATE: return $"WM_ACTIVATE state={e.WParam & 0xFFFF} other=0x{e.LParam:X}"; + case WM_ACTIVATEAPP: return $"WM_ACTIVATEAPP active={e.WParam} tid={e.LParam}"; + case WM_CLOSE: return "WM_CLOSE"; + case WM_DESTROY: return "WM_DESTROY"; + case WM_QUERYENDSESSION: return "WM_QUERYENDSESSION"; + case WM_ENDSESSION: return $"WM_ENDSESSION ending={e.WParam}"; + case WM_SYSCOMMAND: return $"WM_SYSCOMMAND cmd=0x{e.WParam & 0xFFF0:X4}{((e.WParam & 0xFFF0) == 0xF060 ? " (SC_CLOSE)" : "")}"; + default: return $"msg=0x{e.Msg:X4} w=0x{e.WParam:X} l=0x{e.LParam:X}"; + } + } + + private static bool IsExtended(int lParam) => ((lParam >> 24) & 1) != 0; + + /// + /// Scans this thread's stack above the current frame for values that are return + /// addresses into acclient .text (preceded by a call instruction). AC is built with + /// frame-pointer omission, so the EBP walk in LogCaller stops at the first AC frame; + /// this recovers the AC callers above it. Stale values from earlier calls can appear. + /// + private static void AppendStackSweep(StringBuilder sb) + { + int local = 0; + long start = (long)(nint)(&local); + GetCurrentThreadStackLimits(out IntPtr lowLimit, out IntPtr highLimit); + long high = highLimit.ToInt64(); + if (start < lowLimit.ToInt64() || start >= high) + { + sb.Append(" "); + return; + } + long end = Math.Min(high, start + 0x3000); + int hits = 0; + for (long a = (start + 3) & ~3L; a + 4 <= end && hits < 16; a += 4) + { + long v = *(uint*)a; + if (v < _acTextLo + 8 || v >= _acTextHi) + continue; + if (!LooksLikeReturnAddress((byte*)v)) + continue; + hits++; + sb.Append($" {DescribeAcclientAddress((IntPtr)v)}"); + } + if (hits == 0) + sb.Append(" "); + } + + private static bool LooksLikeReturnAddress(byte* ret) + { + if (ret[-5] == 0xE8) return true; // call rel32 + if (ret[-2] == 0xFF && ((ret[-1] >> 3) & 7) == 2 && (ret[-1] >> 6) == 3) return true; // call reg + if (ret[-3] == 0xFF && ((ret[-2] >> 3) & 7) == 2 && (ret[-2] >> 6) == 1) return true; // call [reg+disp8] + if (ret[-2] == 0xFF && ((ret[-1] >> 3) & 7) == 2 && (ret[-1] >> 6) == 0) return true; // call [reg] + if (ret[-6] == 0xFF && ((ret[-5] >> 3) & 7) == 2 && ((ret[-5] >> 6) == 2 || (ret[-5] & 0xC7) == 0x05)) return true; // call [reg+disp32] / [abs] + return false; + } + + private static string DescribeAcclientAddress(IntPtr addr) + { + if (addr == IntPtr.Zero) + return ""; + int rva = (int)(addr.ToInt64() - _acBase); + string label = LabelForAcclientRva(rva); + return label.Length > 0 ? $"acclient.exe+0x{rva:X}{{{label}}}" : $"acclient.exe+0x{rva:X}"; + } + + /// + /// Names the known logoff-related call sites by return-address RVA. Reference client + /// only (labels are off on any other build); the raw module+RVA is always logged. + /// + internal static string LabelForAcclientRva(int rva) + { + if (!_labelsValid) + return ""; + return rva switch + { + // callers of CPlayerSystem::LogOffCharacter + 0x166056 => "ClientUISystem::UseTime: idle auto-logoff", + 0x0EB0E9 => "gmGamePlayUI::UseTime: logout confirmed in the UI", + 0x0EAEC8 => "gmGamePlayUI::EndSession", + 0x0EA80F => "gmEpilogueUI ctor", + 0x15AD39 => "APIManager::EndCharacterSession: plugin API", + // callers of CPlayerSystem::RequestLogOff + 0x1642EE => "CPlayerSystem::LogOffCharacter", + 0x163FC6 => "CPlayerSystem::UseTime: deferred request", + // caller of Proto_UI::LogOffCharacter + 0x163BC4 => "CPlayerSystem::RequestLogOff", + // callers of CPlayerSystem::ExecuteLogOff + 0x15D676 => "server CharacterLogOff 0xF653 handler", + 0x1642DC => "CPlayerSystem::LogOffCharacter(immediate)", + // caller of CPlayerSystem::SetLogOffStarted + 0x0D7AF8 => "gmSmartBoxUI::UseTime", + // callers of ClientNet::LogOffServer + 0x01160C => "Client::Disconnect", + 0x012077 => "Client::CleanupNet", + 0x145E79 => "ClientNet::ProcessOptionalHeader: server disconnect", + 0x145FEC => "ClientNet::RemoveConnection", + _ => "", + }; + } +} diff --git a/src/RynthCore.Engine/Compatibility/LogoutLifecycleHooks.cs b/src/RynthCore.Engine/Compatibility/LogoutLifecycleHooks.cs index 92e882c..f6ed561 100644 --- a/src/RynthCore.Engine/Compatibility/LogoutLifecycleHooks.cs +++ b/src/RynthCore.Engine/Compatibility/LogoutLifecycleHooks.cs @@ -133,7 +133,11 @@ internal static class LogoutLifecycleHooks { RecursionGuard.Tick("LogoutLifecycleHooks.ExecuteLogOff"); if (!HasObservedLogout) + { RynthLog.Compat("LogoutLifecycleHooks: ExecuteLogOff detour entered."); + LogCaller("ExecuteLogOff"); + LogoffOriginProbe.OnLogoffCompleted("CPlayerSystem::ExecuteLogOff"); + } try { _originalExecuteLogOff!(thisPtr); } catch (Exception ex) { try { RynthLog.Compat($"LogoutLifecycleHooks: ExecuteLogOff original threw {ex.GetType().Name}: {ex.Message}"); } catch { } } @@ -145,7 +149,11 @@ internal static class LogoutLifecycleHooks { RecursionGuard.Tick("LogoutLifecycleHooks.RecvNoticeLogoff"); if (!HasObservedLogout) + { RynthLog.Compat("LogoutLifecycleHooks: RecvNotice_Logoff detour entered."); + LogCaller("RecvNotice_Logoff"); + LogoffOriginProbe.OnLogoffCompleted("gmGamePlayUI::RecvNotice_Logoff"); + } try { _originalRecvNoticeLogoff!(thisPtr); } catch (Exception ex) { try { RynthLog.Compat($"LogoutLifecycleHooks: RecvNotice_Logoff original threw {ex.GetType().Name}: {ex.Message}"); } catch { } } @@ -153,6 +161,49 @@ internal static class LogoutLifecycleHooks RaiseLogoutCompleteOnce("gmGamePlayUI::RecvNotice_Logoff"); } + [DllImport("kernel32.dll")] + private static extern ushort RtlCaptureStackBackTrace( + uint FramesToSkip, uint FramesToCapture, IntPtr[] BackTrace, out uint BackTraceHash); + + /// + /// Logs who in the client called the logoff, as module+RVA frames. Characters were + /// logging off by themselves (2026-09-27, Lucy, twice mid-route) with no meta, no + /// command and nothing from the server, so the next one needs to say which client + /// code path confirmed it (UI button, chat /logout, something else). x86 EBP walk: + /// deep frames can be unreliable, the first acclient frames are the useful ones. + /// Known logoff call sites get a {label} (LogoffOriginProbe). Returns the first + /// acclient.exe frame (the immediate AC caller), or Zero if none was captured. + /// + internal static IntPtr LogCaller(string hook, string prefix = "LogoutLifecycleHooks") + { + IntPtr firstAcclient = IntPtr.Zero; + try + { + var frames = new IntPtr[24]; + ushort captured = RtlCaptureStackBackTrace(1, (uint)frames.Length, frames, out _); + var sb = new System.Text.StringBuilder($"{prefix}: {hook} caller frames:"); + for (int i = 0; i < captured && frames[i] != IntPtr.Zero; i++) + { + string module = ProcessExitHooks.ResolveModule(frames[i], out int rva); + sb.Append($" [{i}] {module}+0x{rva:X}"); + if (string.Equals(module, "acclient.exe", StringComparison.OrdinalIgnoreCase)) + { + if (firstAcclient == IntPtr.Zero) + firstAcclient = frames[i]; + string label = LogoffOriginProbe.LabelForAcclientRva(rva); + if (label.Length > 0) + sb.Append($"{{{label}}}"); + } + } + RynthLog.Compat(sb.ToString()); + } + catch (Exception ex) + { + try { RynthLog.Compat($"{prefix}: {hook} caller capture failed: {ex.GetType().Name}"); } catch { } + } + return firstAcclient; + } + private static void RaiseLogoutCompleteOnce(string source) { if (HasObservedLogout) diff --git a/src/RynthCore.Engine/Compatibility/ProcessExitHooks.cs b/src/RynthCore.Engine/Compatibility/ProcessExitHooks.cs index cc39deb..cd8647f 100644 --- a/src/RynthCore.Engine/Compatibility/ProcessExitHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ProcessExitHooks.cs @@ -424,7 +424,7 @@ internal static class ProcessExitHooks } } - private static string ResolveModule(IntPtr address, out int rva) + internal static string ResolveModule(IntPtr address, out int rva) { rva = 0; try diff --git a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs index 08549f0..3706a56 100644 --- a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs +++ b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs @@ -19,6 +19,10 @@ namespace RynthCore.Engine.Compatibility; /// recovery. /// /rc vitals (alias /rc hud) — toggle the custom D3D9 /// Health/Stamina/Mana HUD on/off (persisted to engine.json). +/// /rc vendor [list|info|status|buy <id|sel> [n]|sell <id|sel> [id ...]] +/// — read / trade with the open vendor through the engine's vendor +/// primitives (); a manual test hook for the +/// plugin API. Replies go to chat from the main-thread drain and to the log. /// /// internal static class RynthCoreChatCommands @@ -41,6 +45,15 @@ internal static class RynthCoreChatCommands string sub = trimmed.Substring(Prefix.Length).Trim(); + // /rc vendor [list|info|status|buy [n]|sell [id ...]] + if (sub.Equals("vendor", StringComparison.OrdinalIgnoreCase) + || sub.StartsWith("vendor ", StringComparison.OrdinalIgnoreCase)) + { + try { VendorTrade.HandleChatCommand(sub.Length > 6 ? sub.Substring(7) : string.Empty); } + catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc vendor failed - {ex.GetType().Name}: {ex.Message}"); } + return true; + } + switch (sub.ToLowerInvariant()) { case "resetbar": diff --git a/src/RynthCore.Engine/Compatibility/UpdateObjectInventoryHooks.cs b/src/RynthCore.Engine/Compatibility/UpdateObjectInventoryHooks.cs index 1500808..f03e5d0 100644 --- a/src/RynthCore.Engine/Compatibility/UpdateObjectInventoryHooks.cs +++ b/src/RynthCore.Engine/Compatibility/UpdateObjectInventoryHooks.cs @@ -188,9 +188,30 @@ internal static class UpdateObjectInventoryHooks /// private static int ScanByContainerId(uint containerId, Span itemIds) { + // Check every object the client knows, from the identity snapshot. The old fixed + // range stopped at 0x8000FFFF, but a server hands out ids well past that once it + // has run a while, so newer items (and packs, with everything in them) were + // invisible to the bot: no bundles to craft from, inventory lookups finding nothing. + uint[] live = ClientObjectHooks.LiveObjectIds; + if (live.Length > 0) + { + int found = 0; + foreach (uint id in live) + { + if (found >= itemIds.Length) break; + if (id == containerId) continue; + if (!ClientObjectHooks.TryGetObjectOwnershipInfo(id, out uint c, out uint w, out _)) + continue; + if (c == containerId || w == containerId) + itemIds[found++] = id; + } + itemIds[..found].Sort(); // same ascending order the range scan gave + return found; + } + int written = 0; - // Scan dynamic object range (0x80000001 – 0x8000FFFF) + // No snapshot yet: scan the first dynamic object range (0x80000001 – 0x8000FFFF) for (uint id = 0x80000001; id <= 0x8000FFFF && written < itemIds.Length; id++) { if (id == containerId) continue; diff --git a/src/RynthCore.Engine/Compatibility/VendorHooks.cs b/src/RynthCore.Engine/Compatibility/VendorHooks.cs index 3773ec2..a57bc79 100644 --- a/src/RynthCore.Engine/Compatibility/VendorHooks.cs +++ b/src/RynthCore.Engine/Compatibility/VendorHooks.cs @@ -14,6 +14,10 @@ namespace RynthCore.Engine.Compatibility; /// RecvNotice_CloseVendor = 0x000BFF40 + 0x00401000 = 0x004C0F40 /// /// We hook the real impl (0x004C5790, called by the thunk) and the close entry directly. +/// +/// The open detour also feeds (the vendor snapshot plugins +/// read and trade against); the close path goes through , +/// which VendorTrade's main-thread poll also calls when the vendor window goes away. /// internal static class VendorHooks { @@ -104,22 +108,62 @@ internal static class VendorHooks { _statusMessage = ex.Message; RynthLog.Compat($"Compat: vendor hooks failed - {ex.Message}"); + return; } + + // Vendor trading rides on these detours (snapshot + close tracking). + try { VendorTrade.Initialize(textSection); } + catch (Exception ex) { RynthLog.Warn($"VendorTrade: init failed - {ex.GetType().Name}: {ex.Message}"); } } private static void OpenVendorDetour(IntPtr thisPtr, uint vendorId, IntPtr vpRef, IntPtr itemsRef, int shopMode) { + // Copy the vendor out of the arguments BEFORE the original runs: OpenVendor frees + // the item PWDs on its own copy as it turns them into weenie objects. + VendorSnapshot? snap = null; + if (vendorId != 0) + { + try { snap = VendorTrade.CaptureFromNotice(vendorId, vpRef, itemsRef, shopMode); } + catch { snap = null; } + } + _originalOpen!(thisPtr, vendorId, vpRef, itemsRef, shopMode); if (vendorId == 0) return; + + try { VendorTrade.OnVendorOpened(thisPtr, vendorId, snap); } + catch { } + + // Switching straight to another vendor never sends a close notice; tell plugins. + uint prev = _currentVendorId; _currentVendorId = vendorId; + if (prev != 0 && prev != vendorId) + PluginManager.QueueVendorClose(prev); PluginManager.QueueVendorOpen(vendorId); } private static void CloseVendorDetour(IntPtr thisPtr, int updating) { _originalClose!(thisPtr, updating); + // The flag is a bool in the low byte (MOV AL,[ESP+4]; TEST AL,AL); the rest of the + // stack slot is garbage. With it set, the retail function returns without closing + // anything, so neither do we. + if ((updating & 0xFF) != 0) + return; + MarkVendorClosed("close notice"); + } + + /// + /// The vendor is gone: clear the trade snapshot and raise OnVendorClose once. Called + /// from the close detour and from VendorTrade's main-thread poll of gmVendorUI's + /// shopVendorID, which backs the notice up for any close path that skips it. + /// AC's main thread only. + /// + internal static void MarkVendorClosed(string reason) + { uint vid = _currentVendorId; _currentVendorId = 0; + try { VendorTrade.OnVendorClosed(reason); } + catch { } if (vid != 0) PluginManager.QueueVendorClose(vid); } diff --git a/src/RynthCore.Engine/Compatibility/VendorTrade.cs b/src/RynthCore.Engine/Compatibility/VendorTrade.cs new file mode 100644 index 0000000..8b089d6 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/VendorTrade.cs @@ -0,0 +1,1488 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/VendorTrade.cs +// +// Engine side of vendor trading: read the open vendor, buy from it, sell to it. +// Plugins reach this through the v67 host calls (GetVendorInfo / GetVendorItems / +// VendorBuy / VendorSell / GetVendorTradeStatus); Tom can drive it by hand with +// /rc vendor ... (RynthCoreChatCommands). +// +// How it works (all offsets checked against the live acclient.exe): +// +// READ The server's vendor list (GameEvent ApproachVendor 0x0062) reaches +// gmVendorUI::OpenVendor(this, vendorId, VendorProfile const&, +// PackableList const&, ShopMode), which VendorHooks already +// detours. Inside that detour (AC's main thread, arguments alive) we copy +// the VendorProfile and every ItemProfile + its PublicWeenieDesc into a +// managed, immutable VendorSnapshot. Every read is page-probed first, so a +// layout surprise fails closed (no snapshot) instead of faulting. Plugin +// reads are served from that snapshot on any thread. +// +// BUY / The retail "Buy all"/"Sell all" buttons (gmVendorUI::HandleButtonClicks) +// SELL fill gmVendorUI.m_buyList / m_sellList (PackableList, amount +// + object id, pwd null) and call gmVendorUI::SendShopEvent(vendorId, list, +// altCurrencyId, 0=buy/1=sell), which calls CM_Vendor::Event_Buy (0x005F) / +// Event_Sell (0x0060), then ACCWeenieObject::RecordRequest(vendor, 10) and +// ClientUISystem::IncrementBusyCount (the server's UseDone takes it back +// off). We do exactly that, with our own short-lived list: a real +// PackableList header + ItemProfile nodes in unmanaged memory +// whose vtables are the client's own (found by code xref, then confirmed +// against the live vendor list before we ever send). Event_Buy only walks +// the list to pack it into the outgoing blob, so the memory is freed as soon +// as the call returns. altCurrencyId is VendorProfile.trade_id, as retail. +// +// THREAD Requests are checked against the snapshot on the caller's thread, then +// queued. MainThreadTick (called from AcMainThreadQueue.Drain, the EndScene +// drain on AC's main thread) re-checks against live client state (vendor +// still open, pyreals / alt currency, pack slots, burden, ownership) and only +// then calls SendShopEvent. One transaction is in flight at a time; it +// completes when the server's UseDone (0x01C7) arrives, the vendor list is +// re-sent, the vendor closes, or 10 s pass. +// +// FAIL No vendor, unknown item, bad amount, insufficient funds, an item the player +// CLOSED doesn't own or is wearing, unresolved client function or unverified layout: +// refuse, log, and report through GetVendorTradeStatus. Pack slots and burden +// are refused only when the numbers are known and say "won't fit"; when they +// can't be read the server (which checks the same limits) has the final say. +// +// Server rules mirrored from ACE (Player_Commerce.cs / Vendor.cs / ItemsToReceive.cs): +// player pays max(1, ceil(value * SellRate - 0.1)) per created stack (promissory +// notes at 1.15), vendor pays max(1, floor(value * BuyRate + 0.1)) per item (notes +// at 1.0), burden limit = 3 x capacity, stackables take ceil(amount / maxStack) slots. +// ============================================================================ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using RynthCore.Engine.Plugins; + +namespace RynthCore.Engine.Compatibility; + +/// One item on the vendor's list, copied out of its ItemProfile + PublicWeenieDesc. +internal sealed class VendorItemInfo +{ + public uint ObjectId; + public uint Wcid; + public uint ItemType; + public uint IconId; + /// ItemProfile.amount: how many the vendor has, negative = unlimited. + public int Amount; + public int StackSize; + public int MaxStackSize; + public int Value; + public int Burden; + public uint Bitfield; + public int ItemsCapacity; + public int ContainersCapacity; + public string Name = string.Empty; + + public bool Unlimited => Amount < 0; + /// ACE treats MaxStackSize > 0 as stackable (ItemProfileToWorldObjects). + public bool Stackable => MaxStackSize > 0; + /// Packs and foci take a container slot (BF_REQUIRES_PACKSLOT 0x800000). + public bool NeedsContainerSlot => (Bitfield & 0x800000u) != 0 || ItemsCapacity > 0 || ContainersCapacity > 0; + public int UnitValue => StackSize > 1 ? Value / StackSize : Value; + public int UnitBurden => StackSize > 1 ? Burden / StackSize : Burden; +} + +/// Immutable copy of the open vendor, published on AC's main thread. +internal sealed class VendorSnapshot +{ + public uint VendorId; + public uint Generation; + public int ShopMode; + public uint ItemTypes; + public int MinValue; + public int MaxValue; + public int DealsMagic; + public float BuyRate; + public float SellRate; + public uint AltCurrencyWcid; + public int AltCurrencyServerCount = -1; + public string AltCurrencyName = string.Empty; + public string Name = string.Empty; + public bool ProfileRead; + public bool ItemsComplete; + /// gmVendorUI field offsets and the list/ItemProfile vtables matched the live objects. + public bool LayoutVerified; + public IntPtr Ui; + public IntPtr ListVtableSeen; + public IntPtr ItemVtableSeen; + public VendorItemInfo[] Items = Array.Empty(); + + public VendorItemInfo? Find(uint objectId) + { + foreach (VendorItemInfo it in Items) + if (it.ObjectId == objectId) + return it; + return null; + } +} + +internal static class VendorTrade +{ + // ── Client addresses (pattern-resolved; the VAs are fallbacks the gate checks) ── + // gmVendorUI::SendShopEvent(vendorId, PackableList const&, altCurrencyId, + // ShopEvent) — thiscall, `this` unused, ret 0x10. Literal prologue: + // mov eax,[esp+10]; sub eax,0; push esi; jz buy; dec eax; jnz out + private const int VendorSendShopEventVa = 0x004C0EA0; + private static readonly byte?[] PatVendorSendShopEvent = + [ 0x8B, 0x44, 0x24, 0x10, 0x83, 0xE8, 0x00, 0x56, 0x74, 0x17, 0x48, 0x75, 0x42 ]; + + // PackableList vtable — code xref in gmVendorUI::OpenVendor where it + // news the shop list: jz +11; mov [eax],; mov [eax+4],ebp; mov [eax+8],ebp; + // mov [eax+C],ebp; jmp +2 (operand at +4). + private const int VendorItemProfileListVtableVa = 0x007B6110; + private static readonly byte?[] PatXrefItemProfileListVtable = + [ 0x74, 0x11, 0xC7, 0x00, null, null, null, null, 0x89, 0x68, 0x04, 0x89, 0x68, 0x08, 0x89, 0x68, 0x0C, 0xEB, 0x02 ]; + + // ItemProfile vtable — code xref in ItemProfile::~ItemProfile: + // mov [esi],; jz; mov eax,[ecx]; push 1; call [eax]; mov [esi+C],0; mov [esi], + private const int VendorItemProfileVtableVa = 0x007E9A34; + private static readonly byte?[] PatXrefItemProfileVtable = + [ 0xC7, 0x06, null, null, null, null, 0x74, 0x0D, 0x8B, 0x01, 0x6A, 0x01, 0xFF, 0x10, 0xC7, 0x46, 0x0C, 0x00, 0x00, 0x00, 0x00, 0xC7, 0x06 ]; + + [UnmanagedFunctionPointer(CallingConvention.ThisCall)] + private delegate void SendShopEventDelegate(IntPtr gmVendorUi, uint vendorId, IntPtr itemList, uint altCurrencyId, int shopEvent); + + private const int ShopEventBuy = 0; + private const int ShopEventSell = 1; + + // ── Layouts (from the live binary: gmVendorUI ctor 0x004C3060, OpenVendor 0x004C5790, + // ResetShopState 0x004C32C0, ItemProfile::Pack 0x005D2890, PackableList::Pack + // 0x0055F420, VendorProfile::GetTradeID 0x005D2BD0) ───────────────────────── + private const int UiShopVendorIdOffset = 0x608; // 0 once ResetShopState runs (every close path) + private const int UiShopItemListOffset = 0x610; // PackableList* (UI's own copy) + + private const int ProfileSize = 0x28; + private const int ProfileItemTypes = 0x04, ProfileMinValue = 0x08, ProfileMaxValue = 0x0C, ProfileMagic = 0x10; + private const int ProfileBuyRate = 0x14, ProfileSellRate = 0x18, ProfileTradeId = 0x1C, ProfileTradeNum = 0x20, ProfileTradeName = 0x24; + + private const int ListSize = 0x10; // vfptr, head, tail, curNum + private const int ListHead = 0x04, ListTail = 0x08, ListCount = 0x0C; + private const int NodeSize = 0x18; // ItemProfile(16) + next + prev + private const int NodeAmount = 0x04, NodeIid = 0x08, NodePwd = 0x0C, NodeNext = 0x10, NodePrev = 0x14; + + private const int PwdSize = 0xB0; + private const int PwdName = 4, PwdWcid = 12, PwdIcon = 16, PwdContainer = 28, PwdWielder = 32; + private const int PwdItemsCapacity = 48, PwdContainersCapacity = 52, PwdType = 56, PwdValue = 60; + private const int PwdStackSize = 96, PwdMaxStackSize = 100, PwdBitfield = 104, PwdBurden = 116; + + private const uint ItemTypePromissoryNote = 0x00040000; + private const int PyrealMaxStack = 25000; // coinstack MaxStackSize (payout slots) + private const int MaxVendorItems = 1024; + private const int MaxTradeEntries = 100; + private const int MaxTradeAmount = 0x7FFFFF; // ItemProfile::Pack keeps 24 bits; stay positive + private const int MaxPendingTxns = 4; + private const long InFlightTimeoutMs = 10_000; + + // ── Resolved state ────────────────────────────────────────────────────────── + private static SendShopEventDelegate? _sendShopEvent; + private static IntPtr _listVtable; + private static IntPtr _itemProfileVtable; + private static IntPtr _moduleBase; + private static int _moduleSize; + private static bool _resolved; + private static volatile bool _vtablesVerified; + private static string _statusMessage = "Not initialized."; + + // ── Snapshot + live polling (snapshot written on AC's main thread only) ───── + private static volatile VendorSnapshot? _snapshot; + private static uint _generation; + private static long _lastPollTick; + private static long _lastCoinsTick; + private static volatile int _playerCoins = -1; + private static volatile int _altHave = -1; + private static volatile bool _needAltScan; + + // ── Transactions ──────────────────────────────────────────────────────────── + private sealed class Txn + { + public uint Seq; + public bool IsBuy; + public uint VendorId; + public uint[] Ids = Array.Empty(); + public int[] Amounts = Array.Empty(); + public bool Echo; + } + + private static readonly object _txnLock = new(); + private static readonly Queue _pending = new(); + private static volatile int _pendingCount; + private static int _seq; + + // In-flight transaction (main thread only). + private static Txn? _inFlight; + private static long _inFlightSinceTick; + private static int _inFlightUseDoneBaseline; + private static long _inFlightUseDoneSeenTick; + private static bool _inFlightRefreshed; + + // Last-request status (any thread, under _statusLock). + private static readonly object _statusLock = new(); + private static uint _stSeq; + private static int _stState; // 1 queued, 2 sent, 3 done, 4 refused + private static int _stResult; // with 3: 1 accepted, 2 answered w/o refresh, 3 timeout + private static bool _stIsBuy; + private static uint _stVendor; + private static int _stCount; + private static long _stEstimate; + private static string _stMessage = string.Empty; + + // Chat echo for /rc vendor (drained on the main thread; written from the drain, + // never from inside the outgoing-chat detour). + private static readonly object _echoLock = new(); + private static readonly Queue _echo = new(); + private static volatile int _echoCount; + private const int MaxEcho = 48; + + public static string StatusMessage => _statusMessage; + /// Client functions + vtables resolved by pattern (not fallback). + public static bool IsResolved => _resolved; + public static VendorSnapshot? Snapshot => _snapshot; + + // ════════════════════════════════════════════════════════════════════════════ + // Init + // ════════════════════════════════════════════════════════════════════════════ + + /// + /// Resolve SendShopEvent and the two vtables. Strict: a fallback-VA resolve is NOT + /// accepted for anything we call or build objects from — trading just stays off. + /// Called from VendorHooks.Initialize once the open/close detours are in. + /// + public static void Initialize(AcClientTextSection text) + { + _moduleBase = text.ModuleBase; + _moduleSize = text.ImageSize; + + HookResolver.ResolveResult send = HookResolver.Resolve(text, "Vendor.SendShopEvent", PatVendorSendShopEvent, VendorSendShopEventVa); + HookResolver.ResolveResult listVt = HookResolver.ResolveData(text, "Vendor.ItemProfileListVtable", PatXrefItemProfileListVtable, 4, VendorItemProfileListVtableVa); + HookResolver.ResolveResult itemVt = HookResolver.ResolveData(text, "Vendor.ItemProfileVtable", PatXrefItemProfileVtable, 2, VendorItemProfileVtableVa); + + if (send.Source != HookResolver.ResolveSource.PatternScan + || listVt.Source != HookResolver.ResolveSource.PatternScan + || itemVt.Source != HookResolver.ResolveSource.PatternScan) + { + _statusMessage = $"trading OFF - SendShopEvent={send.Detail}, listVtbl={listVt.Detail}, itemVtbl={itemVt.Detail}"; + RynthLog.Warn($"VendorTrade: {_statusMessage}"); + return; + } + + if (!InModule(listVt.Address) || !InModule(itemVt.Address)) + { + _statusMessage = $"trading OFF - vtables outside acclient (list=0x{listVt.Address.ToInt32():X8} item=0x{itemVt.Address.ToInt32():X8})"; + RynthLog.Warn($"VendorTrade: {_statusMessage}"); + return; + } + + _sendShopEvent = Marshal.GetDelegateForFunctionPointer(send.Address); + _listVtable = listVt.Address; + _itemProfileVtable = itemVt.Address; + _resolved = true; + _statusMessage = $"ready (SendShopEvent=0x{send.Address.ToInt32():X8}, listVtbl=0x{_listVtable.ToInt32():X8}, itemVtbl=0x{_itemProfileVtable.ToInt32():X8}); waiting for a vendor to confirm the layout"; + RynthLog.Compat($"VendorTrade: {_statusMessage}"); + } + + // ════════════════════════════════════════════════════════════════════════════ + // Snapshot (called from the VendorHooks detours — AC's main thread) + // ════════════════════════════════════════════════════════════════════════════ + + /// + /// Copy the vendor out of the OpenVendor arguments. Called BEFORE the original runs, + /// while the caller's VendorProfile / ItemProfile list (and each item's PWD) are + /// intact — OpenVendor clears the PWDs on its own copy as it builds weenie objects. + /// Returns null if the arguments don't look like what we expect. + /// + public static VendorSnapshot? CaptureFromNotice(uint vendorId, IntPtr profile, IntPtr list, int shopMode) + { + if (vendorId == 0) + return null; + + try + { + var snap = new VendorSnapshot { VendorId = vendorId, ShopMode = shopMode }; + + if (profile != IntPtr.Zero && Readable(profile, ProfileSize) && InModule(Marshal.ReadIntPtr(profile))) + { + snap.ItemTypes = ReadU32(profile + ProfileItemTypes); + snap.MinValue = Marshal.ReadInt32(profile + ProfileMinValue); + snap.MaxValue = Marshal.ReadInt32(profile + ProfileMaxValue); + snap.DealsMagic = Marshal.ReadInt32(profile + ProfileMagic); + snap.BuyRate = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(profile + ProfileBuyRate)); + snap.SellRate = BitConverter.Int32BitsToSingle(Marshal.ReadInt32(profile + ProfileSellRate)); + snap.AltCurrencyWcid = ReadU32(profile + ProfileTradeId); + snap.AltCurrencyServerCount = snap.AltCurrencyWcid != 0 ? Marshal.ReadInt32(profile + ProfileTradeNum) : -1; + TryReadLegacyString(profile + ProfileTradeName, 128, out snap.AltCurrencyName); + snap.ProfileRead = RateLooksSane(snap.BuyRate) && RateLooksSane(snap.SellRate); + if (!snap.ProfileRead) + RynthLog.Warn($"VendorTrade: vendor 0x{vendorId:X8} profile rates look wrong (buy={snap.BuyRate} sell={snap.SellRate}); trading with it is off."); + } + + if (list != IntPtr.Zero && Readable(list, ListSize)) + { + snap.ListVtableSeen = Marshal.ReadIntPtr(list); + if (InModule(snap.ListVtableSeen)) + snap.Items = ReadItemList(list, snap); + } + + return snap; + } + catch (Exception ex) + { + RynthLog.Warn($"VendorTrade: capture failed for vendor 0x{vendorId:X8} - {ex.GetType().Name}: {ex.Message}"); + return null; + } + } + + private static VendorItemInfo[] ReadItemList(IntPtr list, VendorSnapshot snap) + { + int declared = Marshal.ReadInt32(list + ListCount); + int capacity = declared > 0 && declared <= MaxVendorItems ? declared : 16; + var items = new List(capacity); + IntPtr node = Marshal.ReadIntPtr(list + ListHead); + int walked = 0; + bool complete = true; + + while (node != IntPtr.Zero) + { + if (walked >= MaxVendorItems || !Readable(node, NodeSize)) + { + complete = false; + break; + } + walked++; + + IntPtr itemVt = Marshal.ReadIntPtr(node); + if (snap.ItemVtableSeen == IntPtr.Zero) + snap.ItemVtableSeen = itemVt; + else if (itemVt != snap.ItemVtableSeen) + { + complete = false; // mixed vtables = not the list we think it is + break; + } + + var it = new VendorItemInfo + { + Amount = Marshal.ReadInt32(node + NodeAmount), + ObjectId = ReadU32(node + NodeIid), + }; + + IntPtr pwd = Marshal.ReadIntPtr(node + NodePwd); + if (pwd != IntPtr.Zero && Readable(pwd, PwdSize) && InModule(Marshal.ReadIntPtr(pwd))) + { + it.Wcid = ReadU32(pwd + PwdWcid); + it.IconId = ReadU32(pwd + PwdIcon); + it.ItemsCapacity = Marshal.ReadInt32(pwd + PwdItemsCapacity); + it.ContainersCapacity = Marshal.ReadInt32(pwd + PwdContainersCapacity); + it.ItemType = ReadU32(pwd + PwdType); + it.Value = Marshal.ReadInt32(pwd + PwdValue); + it.StackSize = Marshal.ReadInt32(pwd + PwdStackSize); + it.MaxStackSize = Marshal.ReadInt32(pwd + PwdMaxStackSize); + it.Bitfield = ReadU32(pwd + PwdBitfield); + it.Burden = Marshal.ReadInt32(pwd + PwdBurden); + TryReadLegacyString(pwd + PwdName, 256, out it.Name); + } + + if (it.ObjectId != 0) + items.Add(it); + + node = Marshal.ReadIntPtr(node + NodeNext); + } + + snap.ItemsComplete = complete && (declared < 0 || walked == declared); + if (!snap.ItemsComplete) + RynthLog.Warn($"VendorTrade: vendor 0x{snap.VendorId:X8} item list read stopped early ({walked} walked, {declared} declared)."); + return items.ToArray(); + } + + /// + /// After the original OpenVendor ran: confirm the gmVendorUI layout against the live + /// object, fill names from the client, publish the snapshot. Main thread. + /// + public static void OnVendorOpened(IntPtr gmVendorUi, uint vendorId, VendorSnapshot? snap) + { + try + { + if (snap == null) + { + _snapshot = null; + RynthLog.Warn($"VendorTrade: vendor 0x{vendorId:X8} opened but could not be read; vendor calls will refuse."); + return; + } + + snap.Ui = gmVendorUi; + + // gmVendorUI.shopVendorID (+0x608) must now hold this vendor, and +0x610 must be + // the UI's own PackableList copy (vtable = the one we resolved). + bool uiIdOk = gmVendorUi != IntPtr.Zero + && Readable(gmVendorUi + UiShopVendorIdOffset, 12) + && ReadU32(gmVendorUi + UiShopVendorIdOffset) == vendorId; + IntPtr uiList = uiIdOk ? Marshal.ReadIntPtr(gmVendorUi + UiShopItemListOffset) : IntPtr.Zero; + bool uiListOk = _resolved && uiList != IntPtr.Zero && Readable(uiList, ListSize) && Marshal.ReadIntPtr(uiList) == _listVtable; + IntPtr uiFirstItemVt = IntPtr.Zero; + if (uiListOk) + { + IntPtr head = Marshal.ReadIntPtr(uiList + ListHead); + if (head != IntPtr.Zero && Readable(head, NodeSize)) + uiFirstItemVt = Marshal.ReadIntPtr(head); + } + + bool listVtOk = uiListOk || (_resolved && snap.ListVtableSeen == _listVtable); + bool itemVtOk = _resolved && (snap.ItemVtableSeen == _itemProfileVtable || uiFirstItemVt == _itemProfileVtable); + if (listVtOk && itemVtOk && !_vtablesVerified) + { + _vtablesVerified = true; + RynthLog.Compat("VendorTrade: live vendor list matches the resolved PackableList/ItemProfile vtables - trading enabled."); + } + snap.LayoutVerified = uiIdOk && uiListOk + && (snap.Items.Length == 0 || snap.ItemVtableSeen == _itemProfileVtable || uiFirstItemVt == _itemProfileVtable); + if (!snap.LayoutVerified) + RynthLog.Warn($"VendorTrade: vendor 0x{vendorId:X8} layout check failed (uiId={uiIdOk}, uiList={uiListOk}, resolved={_resolved}, " + + $"argListVt=0x{snap.ListVtableSeen.ToInt32():X8} argItemVt=0x{snap.ItemVtableSeen.ToInt32():X8} uiItemVt=0x{uiFirstItemVt.ToInt32():X8} " + + $"expected list=0x{_listVtable.ToInt32():X8} item=0x{_itemProfileVtable.ToInt32():X8}); trading with it is off."); + + if (ClientObjectHooks.TryGetObjectName(vendorId, out string vendorName)) + snap.Name = vendorName; + foreach (VendorItemInfo it in snap.Items) + { + if (it.Name.Length == 0 && ClientObjectHooks.TryGetObjectName(it.ObjectId, out string n)) + it.Name = n; + if (it.Wcid == 0 && ClientObjectHooks.TryGetObjectWcid(it.ObjectId, out uint w)) + it.Wcid = w; + } + + snap.Generation = unchecked(++_generation); + if (_inFlight != null && _inFlight.VendorId == vendorId) + _inFlightRefreshed = true; + + _altHave = -1; + _needAltScan = snap.AltCurrencyWcid != 0; + _snapshot = snap; + RefreshCoins(); + _lastPollTick = Environment.TickCount64; + + RynthLog.Compat($"VendorTrade: vendor 0x{vendorId:X8} '{snap.Name}' open gen={snap.Generation} items={snap.Items.Length} " + + $"buy={snap.BuyRate:0.###} sell={snap.SellRate:0.###} types=0x{snap.ItemTypes:X8} " + + $"currency={(snap.AltCurrencyWcid == 0 ? "pyreals" : $"{snap.AltCurrencyName} (wcid {snap.AltCurrencyWcid})")} layout={(snap.LayoutVerified ? "ok" : "BAD")}"); + } + catch (Exception ex) + { + _snapshot = null; + RynthLog.Warn($"VendorTrade: OnVendorOpened failed - {ex.GetType().Name}: {ex.Message}"); + } + } + + /// The vendor is gone (close notice, window closed, walked away). Main thread. + public static void OnVendorClosed(string reason) + { + VendorSnapshot? snap = _snapshot; + _snapshot = null; + _needAltScan = false; + _altHave = -1; + + List? dropped = null; + lock (_txnLock) + { + if (_pending.Count > 0) + { + dropped = new List(_pending); + _pending.Clear(); + _pendingCount = 0; + } + } + if (dropped != null) + foreach (Txn t in dropped) + Refuse(t, "vendor closed before it was sent"); + + // A transaction already sent stays in flight: the server still answers it (UseDone, + // and a fresh vendor list if it went through). The client can also close and + // re-open the vendor inside one ApproachVendor dispatch (when a ground container + // was open - ClientUISystem 0x005652B0), so a close here is not a refusal. + + if (snap != null) + RynthLog.Compat($"VendorTrade: vendor 0x{snap.VendorId:X8} closed ({reason})."); + } + + // ════════════════════════════════════════════════════════════════════════════ + // Main-thread tick (AcMainThreadQueue.Drain) + // ════════════════════════════════════════════════════════════════════════════ + + public static void MainThreadTick() + { + if (_echoCount > 0) + DrainEcho(); + + VendorSnapshot? snap = _snapshot; + if (snap == null && _inFlight == null && _pendingCount == 0) + return; // idle fast path + + if (!MainThreadGuard.IsOnMainThread()) + return; + + long now = Environment.TickCount64; + if (snap != null) + { + if (now - _lastPollTick >= 200) + { + _lastPollTick = now; + if (!VendorStillOpen(snap)) + { + VendorHooks.MarkVendorClosed("vendor window closed"); + snap = null; + } + } + if (snap != null && now - _lastCoinsTick >= 250) + RefreshCoins(); + if (snap != null && _needAltScan) + { + _needAltScan = false; + _altHave = CountOwnedWcid(snap.AltCurrencyWcid); + } + } + + if (_inFlight != null) + CheckInFlight(now); + + if (_inFlight == null && _pendingCount > 0) + { + Txn? next = null; + lock (_txnLock) + { + if (_pending.Count > 0) + { + next = _pending.Dequeue(); + _pendingCount = _pending.Count; + } + } + if (next != null) + Execute(next); + } + } + + private static bool VendorStillOpen(VendorSnapshot snap) + { + if (!snap.LayoutVerified || snap.Ui == IntPtr.Zero) + return true; // can't poll this one; rely on the close notice + IntPtr field = snap.Ui + UiShopVendorIdOffset; + return Readable(field, 4) && ReadU32(field) == snap.VendorId; + } + + private static void RefreshCoins() + { + _lastCoinsTick = Environment.TickCount64; + uint player = ClientHelperHooks.GetPlayerId(); + _playerCoins = player != 0 && ClientObjectHooks.TryGetObjectIntProperty(player, 20u /* COIN_VALUE */, out int coins) ? coins : -1; + } + + private static void CheckInFlight(long now) + { + int useDone = SmartBoxHooks.GetUseDoneSeq(); + if (useDone != _inFlightUseDoneBaseline) + { + if (_inFlightRefreshed) + { + CompleteInFlight(1, "server accepted (vendor list re-sent)"); + return; + } + // ACE sends the fresh vendor list before UseDone, but give a late list (or a + // UseDone that belonged to some other action) a moment before calling it a refusal. + if (_inFlightUseDoneSeenTick == 0) + _inFlightUseDoneSeenTick = now; + else if (now - _inFlightUseDoneSeenTick >= 500) + { + CompleteInFlight(2, "server answered without re-sending the list (refused - see chat)"); + return; + } + } + if (now - _inFlightSinceTick >= InFlightTimeoutMs) + CompleteInFlight(_inFlightRefreshed ? 1 : 3, _inFlightRefreshed ? "server accepted (no UseDone seen)" : "no answer from the server within 10 s"); + } + + private static void CompleteInFlight(int result, string message) + { + Txn? t = _inFlight; + _inFlight = null; + _inFlightRefreshed = false; + if (t == null) + return; + SetStatus(t, 3, result, message); + RynthLog.Compat($"VendorTrade: #{t.Seq} {(t.IsBuy ? "buy" : "sell")} done - {message}"); + if (t.Echo) + Echo($"[RC] vendor #{t.Seq}: {message}"); + } + + // ════════════════════════════════════════════════════════════════════════════ + // Requests (any thread) + // ════════════════════════════════════════════════════════════════════════════ + + /// Queue a buy. Returns the request id, or 0 if refused (status says why). + public static uint RequestBuy(uint vendorId, ReadOnlySpan ids, ReadOnlySpan amounts, bool echo = false) + { + var t = new Txn { Seq = NextSeq(), IsBuy = true, Echo = echo }; + if (ids.Length != amounts.Length) + return RefuseNew(t, vendorId, ids.Length, "ids/amounts length mismatch"); + + VendorSnapshot? snap = _snapshot; + string? err = PreCheck(snap, vendorId, ids.Length, out uint vid); + if (err != null) + return RefuseNew(t, vendorId, ids.Length, err); + + long estimate = 0; + for (int i = 0; i < ids.Length; i++) + { + uint id = ids[i]; + int amount = amounts[i]; + for (int j = 0; j < i; j++) + if (ids[j] == id) + return RefuseNew(t, vid, ids.Length, $"0x{id:X8} listed twice"); + VendorItemInfo? item = snap!.Find(id); + if (item == null) + return RefuseNew(t, vid, ids.Length, $"0x{id:X8} is not on this vendor's list"); + if (amount < 1 || amount > MaxTradeAmount) + return RefuseNew(t, vid, ids.Length, $"bad amount {amount} for 0x{id:X8}"); + if (!item.Unlimited && amount > item.Amount) + return RefuseNew(t, vid, ids.Length, $"vendor only has {item.Amount} of 0x{id:X8}, asked for {amount}"); + EstimateBuy(item, amount, snap.SellRate, out long cost, out _, out _, out _); + estimate += cost; + } + + t.VendorId = vid; + t.Ids = ids.ToArray(); + t.Amounts = amounts.ToArray(); + return Enqueue(t, estimate); + } + + /// Queue a sell of whole stacks. Returns the request id, or 0 if refused. + public static uint RequestSell(uint vendorId, ReadOnlySpan ids, bool echo = false) + { + var t = new Txn { Seq = NextSeq(), IsBuy = false, Echo = echo }; + VendorSnapshot? snap = _snapshot; + string? err = PreCheck(snap, vendorId, ids.Length, out uint vid); + if (err != null) + return RefuseNew(t, vendorId, ids.Length, err); + + for (int i = 0; i < ids.Length; i++) + { + uint id = ids[i]; + if (id == 0) + return RefuseNew(t, vid, ids.Length, "item id 0"); + if (id == vid || snap!.Find(id) != null) + return RefuseNew(t, vid, ids.Length, $"0x{id:X8} belongs to the vendor"); + for (int j = 0; j < i; j++) + if (ids[j] == id) + return RefuseNew(t, vid, ids.Length, $"0x{id:X8} listed twice"); + } + + t.VendorId = vid; + t.Ids = ids.ToArray(); + t.Amounts = new int[ids.Length]; // filled with stack sizes on the main thread + return Enqueue(t, 0); + } + + /// Record a refusal for a request that never got as far as RequestBuy/RequestSell (bad host-call arguments). Returns 0. + public static uint RefuseRequest(bool isBuy, uint vendorId, int count, string reason) + { + var t = new Txn { Seq = NextSeq(), IsBuy = isBuy }; + return RefuseNew(t, vendorId, Math.Clamp(count, 0, MaxTradeEntries), reason); + } + + private static string? PreCheck(VendorSnapshot? snap, uint vendorId, int count, out uint vid) + { + vid = vendorId; + if (!_resolved) + return $"vendor trading unavailable ({_statusMessage})"; + if (snap == null) + return "no vendor open"; + vid = snap.VendorId; + if (vendorId != 0 && vendorId != snap.VendorId) + return $"vendor 0x{vendorId:X8} is not the open vendor (0x{snap.VendorId:X8})"; + if (!snap.LayoutVerified || !_vtablesVerified) + return "vendor layout not verified; trading is off for this vendor"; + if (!snap.ProfileRead) + return "vendor profile unreadable"; + if (count < 1) + return "nothing to trade"; + if (count > MaxTradeEntries) + return $"too many lines ({count} > {MaxTradeEntries}); split into batches"; + return null; + } + + private static uint Enqueue(Txn t, long estimate) + { + lock (_txnLock) + { + if (_pending.Count >= MaxPendingTxns) + return RefuseNew(t, t.VendorId, t.Ids.Length, $"{MaxPendingTxns} requests already waiting"); + _pending.Enqueue(t); + _pendingCount = _pending.Count; + } + SetStatus(t, 1, 0, "queued", estimate); + RynthLog.Compat($"VendorTrade: #{t.Seq} {(t.IsBuy ? "buy" : "sell")} queued - {t.Ids.Length} line(s) for vendor 0x{t.VendorId:X8}" + + (t.IsBuy ? $", est. cost {estimate}" : string.Empty)); + return t.Seq; + } + + private static uint NextSeq() + { + uint s = unchecked((uint)Interlocked.Increment(ref _seq)); + return s == 0 ? unchecked((uint)Interlocked.Increment(ref _seq)) : s; + } + + private static uint RefuseNew(Txn t, uint vendorId, int count, string reason) + { + t.VendorId = vendorId; + t.Ids = new uint[Math.Max(0, count)]; + Refuse(t, reason); + return 0; + } + + private static void Refuse(Txn t, string reason) + { + SetStatus(t, 4, 0, reason); + RynthLog.Compat($"VendorTrade: #{t.Seq} {(t.IsBuy ? "buy" : "sell")} refused - {reason}"); + if (t.Echo) + Echo($"[RC] vendor #{t.Seq} refused: {reason}"); + } + + // ════════════════════════════════════════════════════════════════════════════ + // Execute (main thread) + // ════════════════════════════════════════════════════════════════════════════ + + private static void Execute(Txn t) + { + try + { + VendorSnapshot? snap = _snapshot; + string? err = PreCheck(snap, t.VendorId, t.Ids.Length, out _); + if (err != null) { Refuse(t, err); return; } + if (!VendorStillOpen(snap!)) { Refuse(t, "vendor window is closed"); return; } + + uint player = ClientHelperHooks.GetPlayerId(); + if (player == 0) { Refuse(t, "player id unavailable"); return; } + + long estimate; + uint altCurrency = 0; + if (t.IsBuy) + { + err = ValidateBuy(t, snap!, player, out estimate); + altCurrency = snap!.AltCurrencyWcid; + } + else + { + err = ValidateSell(t, snap!, player, out estimate); + } + if (err != null) { Refuse(t, err); return; } + + if (!SendShopEvent(snap!, t, altCurrency, out err)) + { + Refuse(t, err ?? "send failed"); + return; + } + + _inFlight = t; + _inFlightSinceTick = Environment.TickCount64; + _inFlightUseDoneSeenTick = 0; + _inFlightRefreshed = false; + SetStatus(t, 2, 0, "sent, waiting for the server", estimate); + RynthLog.Compat($"VendorTrade: #{t.Seq} {(t.IsBuy ? "buy" : "sell")} SENT to 0x{t.VendorId:X8}: {DescribeLines(t, snap!)}" + + (t.IsBuy ? $" cost~{estimate}{(altCurrency != 0 ? " " + snap!.AltCurrencyName : "p")}" : $" payout~{estimate}p")); + if (t.Echo) + Echo($"[RC] vendor #{t.Seq} sent: {(t.IsBuy ? "cost" : "payout")} ~{estimate}"); + } + catch (Exception ex) + { + Refuse(t, $"internal error {ex.GetType().Name}: {ex.Message}"); + } + } + + private static string? ValidateBuy(Txn t, VendorSnapshot snap, uint player, out long totalCost) + { + totalCost = 0; + long needItemSlots = 0, needContainerSlots = 0, needBurden = 0; + for (int i = 0; i < t.Ids.Length; i++) + { + VendorItemInfo? item = snap.Find(t.Ids[i]); + if (item == null) + return $"0x{t.Ids[i]:X8} is no longer on the vendor's list"; + int amount = t.Amounts[i]; + if (amount < 1 || amount > MaxTradeAmount || (!item.Unlimited && amount > item.Amount)) + return $"bad amount {amount} for 0x{t.Ids[i]:X8} (vendor has {(item.Unlimited ? "unlimited" : item.Amount.ToString())})"; + EstimateBuy(item, amount, snap.SellRate, out long cost, out long slots, out bool containerSlot, out long burden); + totalCost += cost; + if (containerSlot) needContainerSlots += slots; else needItemSlots += slots; + needBurden += burden; + } + if (totalCost > int.MaxValue) + return "total cost overflows"; + + // Funds — fail closed if we can't read them. + if (snap.AltCurrencyWcid == 0) + { + if (!ClientObjectHooks.TryGetObjectIntProperty(player, 20u /* COIN_VALUE */, out int coins)) + return "could not read your pyreals"; + _playerCoins = coins; + if (totalCost > coins) + return $"costs {totalCost} pyreals, you have {coins}"; + } + else + { + int have = CountOwnedWcid(snap.AltCurrencyWcid); + _altHave = have; + if (have < 0) + return $"could not count your {Currency(snap)}"; + if (totalCost > have) + return $"costs {totalCost} {Currency(snap)}, you have {have}"; + } + + // Pack space + burden — refuse only when known not to fit. + if (TryGetFreeSlots(player, out int freeItems, out int freeContainers)) + { + if (needItemSlots > freeItems) + return $"needs {needItemSlots} free pack slots, you have {freeItems}"; + if (needContainerSlots > freeContainers) + return $"needs {needContainerSlots} free container slots, you have {freeContainers}"; + } + else + { + RynthLog.Compat($"VendorTrade: #{t.Seq} pack slots unreadable - leaving the space check to the server."); + } + + if (needBurden > 0 && TryGetAvailableBurden(player, out long availableBurden) && needBurden > availableBurden) + return $"adds {needBurden} burden, you can carry {availableBurden} more"; + + return null; + } + + private static string? ValidateSell(Txn t, VendorSnapshot snap, uint player, out long payout) + { + payout = 0; + for (int i = 0; i < t.Ids.Length; i++) + { + uint id = t.Ids[i]; + if (!ClientObjectHooks.TryGetObjectOwnershipInfo(id, out uint container, out uint wielder, out _)) + return $"0x{id:X8} not found"; + if (wielder != 0) + return $"0x{id:X8} is equipped - unequip it first"; + bool owned = container == player; + if (!owned && container != 0 + && ClientObjectHooks.TryGetObjectOwnershipInfo(container, out uint outer, out uint outerWielder, out _)) + owned = outer == player && outerWielder == 0; + if (!owned) + return $"0x{id:X8} is not in your packs"; + + if (!ClientObjectHooks.TryGetItemType(id, out uint type) || type == 0) + return $"could not read the type of 0x{id:X8}"; + if ((snap.ItemTypes & type) == 0) + return $"this vendor does not buy {DescribeObject(id)} (type 0x{type:X8})"; + + if (!ClientObjectHooks.TryReadPwdInt32(id, PwdValue, out int value)) + return $"could not read the value of 0x{id:X8}"; + if (value < 1) + return $"{DescribeObject(id)} has no value"; + + if (ClientObjectHooks.TryGetObjectIntProperty(id, 6u /* ITEMS_CAPACITY */, out int cap) && cap > 0) + { + int inside = ClientObjectHooks.GetNumContainedItems(id); + if (inside != 0) + return $"{DescribeObject(id)} is not empty"; + } + + int stack = ClientObjectHooks.TryGetObjectIntProperty(id, 12u /* STACK_SIZE */, out int s) && s > 0 ? s : 1; + if (stack > MaxTradeAmount) + return $"stack of 0x{id:X8} too large ({stack})"; + t.Amounts[i] = stack; + payout += VendorPaysForStack(snap.BuyRate, type, value); + } + if (payout > int.MaxValue) + return "payout overflows"; + + // The server puts the pyreals in your packs before it takes the sold items out. + long coinStacks = (payout + PyrealMaxStack - 1) / PyrealMaxStack; + if (coinStacks > 0 && TryGetFreeSlots(player, out int freeItems, out _) && coinStacks > freeItems) + return $"the {payout} pyreal payout needs {coinStacks} free pack slot(s), you have {freeItems}"; + + return null; + } + + /// + /// Build a PackableList<ItemProfile> in unmanaged memory and hand it to the + /// client's gmVendorUI::SendShopEvent. Main thread only. + /// + private static bool SendShopEvent(VendorSnapshot snap, Txn t, uint altCurrency, out string? error) + { + error = null; + if (!MainThreadGuard.IsOnMainThread()) { error = "not on AC's main thread"; return false; } + if (_sendShopEvent == null || !_resolved || !_vtablesVerified) { error = "SendShopEvent unavailable"; return false; } + int n = t.Ids.Length; + if (n < 1 || n > MaxTradeEntries) { error = "bad line count"; return false; } + + int bytes = ListSize + n * NodeSize; + IntPtr mem = Marshal.AllocHGlobal(bytes); + try + { + for (int off = 0; off < bytes; off += 4) + Marshal.WriteInt32(mem + off, 0); + + IntPtr first = mem + ListSize; + Marshal.WriteIntPtr(mem, _listVtable); + Marshal.WriteIntPtr(mem + ListHead, first); + Marshal.WriteIntPtr(mem + ListTail, first + (n - 1) * NodeSize); + Marshal.WriteInt32(mem + ListCount, n); + + for (int i = 0; i < n; i++) + { + int amount = t.Amounts[i]; + if (amount < 1 || amount > MaxTradeAmount) { error = $"bad amount {amount}"; return false; } + IntPtr node = first + i * NodeSize; + Marshal.WriteIntPtr(node, _itemProfileVtable); + Marshal.WriteInt32(node + NodeAmount, amount); + Marshal.WriteInt32(node + NodeIid, unchecked((int)t.Ids[i])); + Marshal.WriteIntPtr(node + NodePwd, IntPtr.Zero); // pwd null -> 8 bytes on the wire + Marshal.WriteIntPtr(node + NodeNext, i < n - 1 ? node + NodeSize : IntPtr.Zero); + Marshal.WriteIntPtr(node + NodePrev, i > 0 ? node - NodeSize : IntPtr.Zero); + } + + _inFlightUseDoneBaseline = SmartBoxHooks.GetUseDoneSeq(); + _sendShopEvent(snap.Ui, t.VendorId, mem, altCurrency, t.IsBuy ? ShopEventBuy : ShopEventSell); + return true; + } + catch (Exception ex) + { + error = $"SendShopEvent threw {ex.GetType().Name}: {ex.Message}"; + return false; + } + finally + { + Marshal.FreeHGlobal(mem); + } + } + + // ════════════════════════════════════════════════════════════════════════════ + // Prices, slots, burden (ACE rules) + // ════════════════════════════════════════════════════════════════════════════ + + /// What the player pays for one created stack worth (ACE Vendor.GetSellCost). + internal static long PlayerPaysForStack(float sellRate, uint itemType, long stackValue) + { + float rate = itemType == ItemTypePromissoryNote ? 1.15f : sellRate; + float product = rate * stackValue; + return Math.Max(1L, (long)Math.Ceiling(product - 0.1)); + } + + /// What the vendor pays for one item worth (ACE Vendor.GetBuyCost). + internal static long VendorPaysForStack(float buyRate, uint itemType, long value) + { + float rate = itemType == ItemTypePromissoryNote ? 1.0f : buyRate; + float product = rate * value; + return Math.Max(1L, (long)Math.Floor(product + 0.1)); + } + + /// + /// Cost / slots / burden for buying of , + /// the way ACE creates it: stackables in stacks of MaxStackSize, others one each. + /// A limited listing (usually an item another player sold, which ACE hands over whole) + /// is costed at the larger of the per-unit price and the whole listing. + /// + internal static void EstimateBuy(VendorItemInfo item, int amount, float sellRate, + out long cost, out long slots, out bool containerSlot, out long burden) + { + long unitValue = Math.Max(0, item.UnitValue); + long unitBurden = Math.Max(0, item.UnitBurden); + containerSlot = item.NeedsContainerSlot; + if (item.Stackable) + { + long max = item.MaxStackSize; + long full = amount / max; + long rem = amount % max; + cost = full * PlayerPaysForStack(sellRate, item.ItemType, unitValue * max) + + (rem > 0 ? PlayerPaysForStack(sellRate, item.ItemType, unitValue * rem) : 0); + slots = full + (rem > 0 ? 1 : 0); + } + else + { + cost = amount * PlayerPaysForStack(sellRate, item.ItemType, unitValue); + slots = amount; + } + burden = amount * unitBurden; + + if (!item.Unlimited) + { + cost = Math.Max(cost, PlayerPaysForStack(sellRate, item.ItemType, Math.Max(0, item.Value))); + slots = Math.Max(slots, 1); + burden = Math.Max(burden, Math.Max(0, item.Burden)); + } + } + + internal static int UnitPrice(VendorItemInfo item, float sellRate) => + (int)Math.Min(int.MaxValue, PlayerPaysForStack(sellRate, item.ItemType, Math.Max(0, item.UnitValue))); + + /// + /// Free item slots (main pack + side packs) and container slots, like ACE's + /// GetFreeInventorySlots / GetFreeContainerSlots, from the client's own counts. + /// Main thread. False if the numbers can't be read. + /// + private static bool TryGetFreeSlots(uint player, out int freeItems, out int freeContainers) + { + freeItems = 0; + freeContainers = 0; + if (!ClientObjectHooks.TryGetObjectIntProperty(player, 6u, out int mainCap) || mainCap <= 0) + mainCap = 102; // same default IsFullOwnedContainer uses for the main pack + int mainCount = ClientObjectHooks.GetNumContainedItems(player); + if (mainCount < 0) + return false; + freeItems = Math.Max(0, mainCap - mainCount); + + if (!ClientObjectHooks.TryGetObjectIntProperty(player, 7u, out int containerCap) || containerCap <= 0) + containerCap = 7; + int containers = ClientObjectHooks.GetNumContainedContainers(player); + if (containers < 0) + return false; + freeContainers = Math.Max(0, containerCap - containers); + + foreach (uint pack in OwnedDirectIds(player)) + { + if (!ClientObjectHooks.TryGetObjectIntProperty(pack, 6u, out int cap) || cap <= 0) + continue; // not a pack (or a focus) + int inside = ClientObjectHooks.GetNumContainedItems(pack); + if (inside < 0) + return false; + freeItems += Math.Max(0, cap - inside); + } + return true; + } + + /// ACE: burden limit is 3 x capacity; capacity = 150*Str + 30*Str per carrying aug. + private static bool TryGetAvailableBurden(uint player, out long available) + { + available = 0; + if (!ClientObjectHooks.TryGetObjectIntProperty(player, 5u /* ENCUMB_VAL */, out int carried)) + return false; + long capacity; + if (ClientObjectHooks.TryGetObjectIntProperty(player, 96u /* ENCUMB_CAPACITY */, out int cap) && cap > 0) + capacity = cap; + else if (ClientObjectHooks.TryGetObjectAttribute(player, 1u /* Strength */, 0, out uint str) && str > 0) + { + int augs = ClientObjectHooks.TryGetObjectIntProperty(player, 230u, out int a) && a > 0 ? a : 0; + capacity = 150L * str + 30L * augs * str; + } + else + return false; + available = capacity * 3 - carried; + return true; + } + + /// Ids whose container is the player (main-pack items and side packs). Main thread. + private static List OwnedDirectIds(uint player) + { + var result = new List(); + foreach (uint id in ClientObjectHooks.LiveObjectIds) + { + if (id == player) + continue; + if (ClientObjectHooks.TryGetObjectOwnershipInfo(id, out uint c, out uint w, out _) && c == player && w == 0) + result.Add(id); + } + return result; + } + + /// How many of the player carries (packs included). -1 if unreadable. Main thread. + private static int CountOwnedWcid(uint wcid) + { + if (wcid == 0 || !MainThreadGuard.IsOnMainThread()) + return -1; + uint player = ClientHelperHooks.GetPlayerId(); + uint[] live = ClientObjectHooks.LiveObjectIds; + if (player == 0 || live.Length == 0) + return -1; + + var packs = new HashSet(); + foreach (uint id in OwnedDirectIds(player)) + if (ClientObjectHooks.TryGetObjectIntProperty(id, 6u, out int cap) && cap > 0) + packs.Add(id); + + long total = 0; + foreach (uint id in live) + { + if (id == player || !ClientObjectHooks.TryGetObjectOwnershipInfo(id, out uint c, out uint w, out _)) + continue; + if (w != 0 || (c != player && !packs.Contains(c))) + continue; + if (!ClientObjectHooks.TryGetObjectWcid(id, out uint itemWcid) || itemWcid != wcid) + continue; + total += ClientObjectHooks.TryGetObjectIntProperty(id, 12u, out int s) && s > 0 ? s : 1; + } + return (int)Math.Min(int.MaxValue, total); + } + + // ════════════════════════════════════════════════════════════════════════════ + // Host-API fills (any thread) + // ════════════════════════════════════════════════════════════════════════════ + + public static unsafe int FillInfo(VendorInfoNative* info) + { + if (info == null) + return 0; + *info = default; + VendorSnapshot? snap = _snapshot; + if (snap == null) + return 0; + + info->VendorId = snap.VendorId; + info->Generation = snap.Generation; + info->ShopMode = snap.ShopMode; + info->ItemTypes = snap.ItemTypes; + info->MinValue = snap.MinValue; + info->MaxValue = snap.MaxValue; + info->DealsMagic = snap.DealsMagic; + info->BuyRate = snap.BuyRate; + info->SellRate = snap.SellRate; + info->AltCurrencyWcid = snap.AltCurrencyWcid; + info->AltCurrencyServerCount = snap.AltCurrencyServerCount; + info->AltCurrencyHave = snap.AltCurrencyWcid != 0 ? _altHave : -1; + info->PlayerCoins = _playerCoins; + info->ItemCount = snap.Items.Length; + info->Flags = (TradeAvailable(snap) ? 1u : 0u) | (_inFlight != null || _pendingCount > 0 ? 2u : 0u); + WriteAnsi(info->Name, 64, snap.Name); + WriteAnsi(info->AltCurrencyName, 64, snap.AltCurrencyName); + return 1; + } + + public static unsafe int FillItems(VendorItemNative* items, int maxCount) + { + VendorSnapshot? snap = _snapshot; + if (snap == null) + return -1; + VendorItemInfo[] src = snap.Items; + if (items != null && maxCount > 0) + { + int n = Math.Min(maxCount, src.Length); + for (int i = 0; i < n; i++) + { + VendorItemInfo it = src[i]; + VendorItemNative* d = items + i; + *d = default; + d->ObjectId = it.ObjectId; + d->Wcid = it.Wcid; + d->ItemType = it.ItemType; + d->IconId = it.IconId; + d->Amount = it.Unlimited ? -1 : it.Amount; + d->StackSize = it.StackSize; + d->MaxStackSize = it.MaxStackSize; + d->Value = it.Value; + d->UnitValue = it.UnitValue; + d->UnitPrice = UnitPrice(it, snap.SellRate); + d->Burden = it.Burden; + d->Flags = (it.Unlimited ? 1u : 0u) | (it.Stackable ? 2u : 0u) | (it.NeedsContainerSlot ? 4u : 0u); + WriteAnsi(d->Name, 64, it.Name); + } + } + return src.Length; + } + + public static unsafe int FillStatus(VendorTradeStatusNative* status) + { + if (status == null) + return 0; + *status = default; + lock (_statusLock) + { + if (_stSeq == 0 && _stState == 0) + return 0; + status->RequestId = _stSeq; + status->State = _stState; + status->Result = _stResult; + status->IsBuy = _stIsBuy ? 1 : 0; + status->VendorId = _stVendor; + status->EntryCount = _stCount; + status->Estimate = (int)Math.Clamp(_stEstimate, int.MinValue, int.MaxValue); + WriteAnsi(status->Message, 128, _stMessage); + } + return 1; + } + + private static bool TradeAvailable(VendorSnapshot snap) => + _resolved && _vtablesVerified && snap.LayoutVerified && snap.ProfileRead; + + private static void SetStatus(Txn t, int state, int result, string message, long estimate = long.MinValue) + { + // Always the most recently UPDATED request; RequestId says which one. Plugins + // trade one request at a time (wait for State 3/4 before the next), so this is + // the request they are waiting on. + lock (_statusLock) + { + if (t.Seq != _stSeq && estimate == long.MinValue) + _stEstimate = 0; + _stSeq = t.Seq; + _stState = state; + _stResult = result; + _stIsBuy = t.IsBuy; + _stVendor = t.VendorId; + _stCount = t.Ids.Length; + if (estimate != long.MinValue) + _stEstimate = estimate; + _stMessage = message; + } + } + + // ════════════════════════════════════════════════════════════════════════════ + // /rc vendor ... + // ════════════════════════════════════════════════════════════════════════════ + + /// + /// /rc vendor [list|info|status|buy <id|sel> [n]|sell <id|sel> [id ...]]. + /// Replies go to the log and (capped) to chat from the main-thread drain. + /// + public static void HandleChatCommand(string args) + { + string[] parts = args.Split(' ', StringSplitOptions.RemoveEmptyEntries); + string verb = parts.Length > 0 ? parts[0].ToLowerInvariant() : "list"; + switch (verb) + { + case "list": + case "ls": + PrintVendor(listItems: true); + break; + case "info": + PrintVendor(listItems: false); + break; + case "status": + case "st": + PrintStatus(); + break; + case "buy": + { + if (parts.Length < 2 || !TryParseId(parts[1], out uint id)) + { + Echo("[RC] usage: /rc vendor buy [amount]"); + break; + } + int amount = 1; + if (parts.Length >= 3 && (!int.TryParse(parts[2], out amount) || amount < 1)) + { + Echo("[RC] amount must be a positive number"); + break; + } + uint seq = RequestBuy(0, [id], [amount], echo: true); + if (seq != 0) + Echo($"[RC] vendor #{seq}: buy {amount} x {DescribeVendorItem(id)} queued"); + break; + } + case "sell": + { + if (parts.Length < 2) + { + Echo("[RC] usage: /rc vendor sell [id ...]"); + break; + } + var ids = new List(); + for (int i = 1; i < parts.Length; i++) + { + if (!TryParseId(parts[i], out uint id)) + { + Echo($"[RC] not an object id: {parts[i]}"); + return; + } + ids.Add(id); + } + uint seq = RequestSell(0, ids.ToArray(), echo: true); + if (seq != 0) + Echo($"[RC] vendor #{seq}: sell {ids.Count} item(s) queued"); + break; + } + default: + Echo("[RC] /rc vendor list | info | status | buy [n] | sell [id ...]"); + break; + } + } + + private static void PrintVendor(bool listItems) + { + VendorSnapshot? snap = _snapshot; + if (snap == null) + { + Echo($"[RC] no vendor open. ({_statusMessage})"); + return; + } + string currency = snap.AltCurrencyWcid == 0 + ? $"pyreals (you have {(_playerCoins >= 0 ? _playerCoins.ToString() : "?")})" + : $"{Currency(snap)} wcid {snap.AltCurrencyWcid} (server says {snap.AltCurrencyServerCount}, counted {(_altHave >= 0 ? _altHave.ToString() : "?")})"; + Echo($"[RC] vendor 0x{snap.VendorId:X8} {snap.Name}: {snap.Items.Length} items, sells at {snap.SellRate:0.###}x, buys at {snap.BuyRate:0.###}x, " + + $"types 0x{snap.ItemTypes:X8}, value {snap.MinValue}-{snap.MaxValue}, magic {snap.DealsMagic}, currency {currency}, " + + $"trading {(TradeAvailable(snap) ? "ON" : "OFF")}, gen {snap.Generation}"); + if (!listItems) + return; + + const int chatCap = 30; + int shown = 0; + foreach (VendorItemInfo it in snap.Items) + { + string line = $"[RC] 0x{it.ObjectId:X8} {it.Name} x{(it.Unlimited ? "inf" : it.Amount.ToString())} " + + $"@{UnitPrice(it, snap.SellRate)} (wcid {it.Wcid}, value {it.Value}, stack {it.StackSize}/{it.MaxStackSize}, burden {it.Burden}, type 0x{it.ItemType:X})"; + if (shown < chatCap) + { + Echo(line); + shown++; + } + else + { + RynthLog.Compat(line); + } + } + if (snap.Items.Length > chatCap) + Echo($"[RC] ...{snap.Items.Length - chatCap} more in the RynthCore log"); + } + + private static void PrintStatus() + { + string line; + lock (_statusLock) + { + if (_stSeq == 0 && _stState == 0) + line = "[RC] no vendor trade requested yet"; + else + { + string state = _stState switch { 1 => "queued", 2 => "sent", 3 => "done", 4 => "refused", _ => "?" }; + line = $"[RC] vendor #{_stSeq} {(_stIsBuy ? "buy" : "sell")} {state}" + + (_stState == 3 ? $" (result {_stResult})" : string.Empty) + + $", {_stCount} line(s), est {_stEstimate}: {_stMessage}"; + } + } + Echo(line); + } + + private static bool TryParseId(string token, out uint id) + { + id = 0; + if (token.Equals("sel", StringComparison.OrdinalIgnoreCase) || token.Equals("selected", StringComparison.OrdinalIgnoreCase)) + { + id = ClientHelperHooks.GetSelectedItemId(); + return id != 0; + } + if (token.StartsWith("0x", StringComparison.OrdinalIgnoreCase)) + return uint.TryParse(token.AsSpan(2), System.Globalization.NumberStyles.HexNumber, null, out id) && id != 0; + if (uint.TryParse(token, out id) && id != 0) + return true; + return uint.TryParse(token, System.Globalization.NumberStyles.HexNumber, null, out id) && id != 0; + } + + /// Queue a chat line (also logged). Written by DrainEcho on the main thread. + private static void Echo(string line) + { + RynthLog.Compat(line); + lock (_echoLock) + { + if (_echo.Count >= MaxEcho) + return; + _echo.Enqueue(line); + _echoCount = _echo.Count; + } + } + + private static void DrainEcho() + { + if (!MainThreadGuard.IsOnMainThread()) + return; + while (true) + { + string line; + lock (_echoLock) + { + if (_echo.Count == 0) { _echoCount = 0; return; } + line = _echo.Dequeue(); + _echoCount = _echo.Count; + } + try { ClientHelperHooks.WriteToChat(line, 1); } catch { } + } + } + + // ════════════════════════════════════════════════════════════════════════════ + // Helpers + // ════════════════════════════════════════════════════════════════════════════ + + private static string Currency(VendorSnapshot snap) => + snap.AltCurrencyWcid == 0 ? "pyreals" : (snap.AltCurrencyName.Length > 0 ? snap.AltCurrencyName : $"wcid {snap.AltCurrencyWcid}"); + + private static string DescribeVendorItem(uint id) + { + VendorItemInfo? it = _snapshot?.Find(id); + return it != null && it.Name.Length > 0 ? $"{it.Name} (0x{id:X8})" : $"0x{id:X8}"; + } + + private static string DescribeObject(uint id) => + ClientObjectHooks.TryGetObjectName(id, out string n) && n.Length > 0 ? $"{n} (0x{id:X8})" : $"0x{id:X8}"; + + private static string DescribeLines(Txn t, VendorSnapshot snap) + { + var sb = new StringBuilder(); + for (int i = 0; i < t.Ids.Length && i < 12; i++) + { + if (i > 0) sb.Append(", "); + string name = t.IsBuy ? (snap.Find(t.Ids[i])?.Name ?? string.Empty) : string.Empty; + sb.Append(t.Amounts[i]).Append("x 0x").Append(t.Ids[i].ToString("X8")); + if (name.Length > 0) sb.Append(' ').Append(name); + } + if (t.Ids.Length > 12) sb.Append(", ..."); + return sb.ToString(); + } + + private static bool RateLooksSane(float rate) => float.IsFinite(rate) && rate > 0f && rate < 1000f; + + private static bool InModule(IntPtr p) + { + if (p == IntPtr.Zero || _moduleBase == IntPtr.Zero || _moduleSize <= 0) + return false; + long v = (uint)p.ToInt32(); + long start = (uint)_moduleBase.ToInt32(); + return v >= start && v < start + _moduleSize; + } + + /// Both ends of [p, p+size) committed and readable (spans here are < one page). + private static bool Readable(IntPtr p, int size) => + p != IntPtr.Zero && ClientObjectHooks.IsReadablePointer(p) && ClientObjectHooks.IsReadablePointer(p + (size - 1)); + + private static uint ReadU32(IntPtr p) => unchecked((uint)Marshal.ReadInt32(p)); + + /// + /// AC1Legacy::PStringBase<char> at : pointer to PSRefBuffer + /// { vfptr, refcount, m_len (incl. NUL), m_size, m_hash, m_data[] } — same reader as + /// ClientObjectHooks.TryReadPwdString. + /// + private static bool TryReadLegacyString(IntPtr field, int maxLen, out string value) + { + value = string.Empty; + try + { + if (!Readable(field, 4)) return false; + IntPtr buffer = Marshal.ReadIntPtr(field); + if (buffer == IntPtr.Zero || !Readable(buffer, 20)) return false; + int rawLen = Marshal.ReadInt32(buffer + 8); + if (rawLen <= 1 || rawLen > maxLen) return false; + IntPtr data = buffer + 20; + if (!Readable(data, rawLen - 1)) return false; + value = Marshal.PtrToStringAnsi(data, rawLen - 1) ?? string.Empty; + int nul = value.IndexOf('\0'); + if (nul >= 0) value = value.Substring(0, nul); + return value.Length > 0; + } + catch + { + value = string.Empty; + return false; + } + } + + private static unsafe void WriteAnsi(byte* dest, int capacity, string? text) + { + int n = 0; + if (!string.IsNullOrEmpty(text)) + { + for (; n < text.Length && n < capacity - 1; n++) + { + char c = text[n]; + dest[n] = c < 256 ? (byte)c : (byte)'?'; + } + } + for (int i = n; i < capacity; i++) + dest[i] = 0; + } +} diff --git a/src/RynthCore.Engine/D3D9/EndSceneHook.cs b/src/RynthCore.Engine/D3D9/EndSceneHook.cs index c0fdb0a..6ee6eeb 100644 --- a/src/RynthCore.Engine/D3D9/EndSceneHook.cs +++ b/src/RynthCore.Engine/D3D9/EndSceneHook.cs @@ -334,9 +334,13 @@ internal static class EndSceneHook // is visible even when ImGui per-frame work is disabled. Driven // here exclusively — EngineFrameController.OnEndScene intentionally // does NOT call it (avoids double-blit / TryConsume races). + // The UI hides between characters: nothing is drawn at character select or + // on the way out, and it's back the moment login completes (an engine + // reload synthesises login for a player already in the world). try { - OverlayTextureRenderer.Render(pDevice); + if (Compatibility.LoginLifecycleHooks.HasObservedLoginComplete) + OverlayTextureRenderer.Render(pDevice); } catch (Exception ovEx) { diff --git a/src/RynthCore.Engine/EntryPoint.cs b/src/RynthCore.Engine/EntryPoint.cs index 7485d87..e836237 100644 --- a/src/RynthCore.Engine/EntryPoint.cs +++ b/src/RynthCore.Engine/EntryPoint.cs @@ -190,6 +190,9 @@ public static class EntryPoint private static string? GetEngineDirectory() => GetEngineModulePath() is { } path ? Path.GetDirectoryName(path) : null; + /// Folder of the loaded engine DLL (Runtime\, or Runtime\.engine_loads\ on a staged load). + internal static string? EngineDirectory => GetEngineDirectory(); + /// Full path of the engine DLL actually loaded (the loader's staged copy on hot reload). private static unsafe string? GetEngineModulePath() { @@ -533,6 +536,7 @@ public static class EntryPoint // scenarios where keyboard input isn't reaching AC's chat box. Step("chat file dispatcher", ChatFileDispatcher.Start); Step("logout lifecycle hooks", LogoutLifecycleHooks.Initialize); + Step("logoff origin probe", LogoffOriginProbe.Initialize); Step("session state registry", SessionStateRegistry.Initialize); Step("UI lifecycle hooks", UiLifecycleHooks.Initialize); Step("logo bypass", LogoBypassHooks.Start); diff --git a/src/RynthCore.Engine/ImGui/EngineFrameController.cs b/src/RynthCore.Engine/ImGui/EngineFrameController.cs index 1f8deb6..35faa73 100644 --- a/src/RynthCore.Engine/ImGui/EngineFrameController.cs +++ b/src/RynthCore.Engine/ImGui/EngineFrameController.cs @@ -224,11 +224,11 @@ internal static class EngineFrameController DX9Backend.Shutdown(); // Do NOT call Win32Backend.Shutdown() here. EngineLifecycle.Shutdown // owns that step explicitly, AFTER AvaloniaOverlay.Stop — floating - // panels are destroyed via RunOnGameThread (a SendMessage handled by - // our subclass WndProc), so restoring AC's original WndProc this - // early makes that SendMessage land on AC's proc, get ignored, and - // "succeed" — DestroyWindow never runs and the orphaned panel HWND - // outlives the engine module with its WndProc pointing at freed code. + // panels can only be destroyed on the game thread by our subclass + // WndProc (Win32Backend.Shutdown sweeps any still open before it + // unhooks), so restoring AC's original WndProc this early sends + // those destroys to AC's proc, which ignores them, and the orphaned + // panel HWND outlives the engine load. ImGuiNET.ImGui.DestroyContext(contextToDestroy); _imguiInitialized = false; diff --git a/src/RynthCore.Engine/ImGui/Win32Backend.cs b/src/RynthCore.Engine/ImGui/Win32Backend.cs index ddfbd66..83cb04e 100644 --- a/src/RynthCore.Engine/ImGui/Win32Backend.cs +++ b/src/RynthCore.Engine/ImGui/Win32Backend.cs @@ -78,6 +78,12 @@ internal static unsafe class Win32Backend /// finish. wParam carries the HWND to destroy. public const uint WM_RYNTH_DESTROY_HWND = 0x8003; + /// Destroys floating-panel HWNDs on the game thread (their owner). + /// wParam != 0 includes this engine load's own panels (sent synchronously by + /// Shutdown before unhooking); wParam == 0 removes only panels an earlier + /// load left behind (posted by Init). See LayeredWindow.DestroyThreadPanelWindows. + public const uint WM_RYNTH_SWEEP_PANELS = 0x8004; + private const int VK_CONTROL = 0x11; private const int VK_SHIFT = 0x10; private const int VK_MENU = 0x12; // Alt @@ -274,6 +280,8 @@ internal static unsafe class Win32Backend { if (_originalWndProc == IntPtr.Zero || _gameHwnd == IntPtr.Zero) return IntPtr.Zero; + // Diag (diag/logoff-origin): engine-synthesised input bypasses the subclass. + Compatibility.LogoffOriginProbe.RecordWndMsg(msg, wParam, lParam, synthetic: true); return CallWindowProcA(_originalWndProc, _gameHwnd, msg, wParam, lParam); } @@ -507,6 +515,12 @@ internal static unsafe class Win32Backend _initialized = true; RynthLog.Render("Win32Backend: Initialized (WndProc subclassed)."); RynthLog.Render("Win32Backend: UI capture ENABLED by default (Insert to release)."); + + // A previous engine load may have left floating panels behind (its + // teardown predates the synchronous sweep in Shutdown, or the game + // thread was stalled past the timeout) — clear them now, while + // sparing this load's own. + PostMessage(_gameHwnd, WM_RYNTH_SWEEP_PANELS, IntPtr.Zero, IntPtr.Zero); return true; } @@ -517,6 +531,16 @@ internal static unsafe class Win32Backend { if (!_initialized) return; + // Destroy floating panels while our hook can still run on the game + // thread. LayeredWindow.Dispose only POSTS its destroy, and the game + // thread usually hasn't reached that post by the time we unhook below — + // AC's own WndProc then drops it and the panel outlives this engine + // load, frozen and unclickable (duplicate RynthAi dashboard after RL). + IntPtr swept = SendMessageTimeout(_gameHwnd, WM_RYNTH_SWEEP_PANELS, new IntPtr(1), IntPtr.Zero, + SMTO_NORMAL, 2000, out _); + if (swept == IntPtr.Zero) + RynthLog.Info($"Win32Backend: Shutdown — panel sweep didn't run on the game thread (err={Marshal.GetLastWin32Error()}); the next engine load clears what's left."); + // Restore the original WndProc ONLY if we are still the head of the // chain. If something subclassed on top of us after Init (Decal / // DINPUT8 re-hooks, a newer engine generation), a blind restore RIPS @@ -695,6 +719,17 @@ internal static unsafe class Win32Backend return IntPtr.Zero; } + if (msg == WM_RYNTH_SWEEP_PANELS) + { + try { UI.LayeredWindow.DestroyThreadPanelWindows(includeThisGeneration: wParam != IntPtr.Zero); } + catch (Exception ex) { RynthLog.Info($"Win32Backend: WM_RYNTH_SWEEP_PANELS threw {ex.GetType().Name}: {ex.Message}"); } + return IntPtr.Zero; + } + + // Diag (diag/logoff-origin): ring of recent key/click/focus/close messages, + // dumped when the client requests a logoff. Filters first; never throws. + Compatibility.LogoffOriginProbe.RecordWndMsg(msg, wParam, lParam, synthetic: false); + // ── User clicked X / Alt+F4 on AC window — tear our overlay down NOW ── // AC's own shutdown takes 20-30 s (network logout, save, etc.) before // it finally calls ExitProcess and triggers ProcessExitHooks. During @@ -885,7 +920,14 @@ internal static unsafe class Win32Backend return IntPtr.Zero; // ── Avalonia panel hit-test & input forwarding ──────────────── - if (IsMouseMessage(msg)) + // Only in the world: between characters the overlay isn't drawn, so its + // panels mustn't take clicks meant for character select. + bool overlayLive = RynthCore.Engine.Compatibility.LoginLifecycleHooks.HasObservedLoginComplete; + if (!overlayLive) + { + // fall through: AC gets the message + } + else if (IsMouseMessage(msg)) { bool handled = TryForwardToAvalonia(msg, wParam, lParam); if (handled) @@ -1108,6 +1150,16 @@ internal static unsafe class Win32Backend { if (msg == WM_LBUTTONUP) _pendingBarButtonTitle = null; + + // An open Flyout / ContextMenu / dropdown is embedded in the + // overlay window, but a click on the game world is never + // forwarded, so Avalonia's light-dismiss never sees it. Close + // it here; the click still goes to AC. + if ((msg == WM_LBUTTONDOWN || msg == WM_RBUTTONDOWN || msg == WM_MBUTTONDOWN) + && AvaloniaOverlay.HasOpenLightDismissPopup) + { + AvaloniaOverlay.DismissLightDismissPopups(); + } return false; } diff --git a/src/RynthCore.Engine/Plugins/EngineSettings.cs b/src/RynthCore.Engine/Plugins/EngineSettings.cs index 2fd970c..c4b4452 100644 --- a/src/RynthCore.Engine/Plugins/EngineSettings.cs +++ b/src/RynthCore.Engine/Plugins/EngineSettings.cs @@ -23,6 +23,7 @@ internal static class EngineSettings private static bool _enableImGuiBackend = true; private static bool _enableHangMinidump = true; private static bool _drawCustomVitalBars = true; + private static bool _preventIdleLogoff = true; private static bool _loaded; public static IReadOnlyList PluginPaths @@ -178,6 +179,20 @@ internal static class EngineSettings } } + /// When true (default), the engine keeps the retail client's idle clock fresh + /// while in the world, so ClientUISystem::UseTime's 20-minute idle auto-logoff + /// (InactiveTimeBeforeLogout) can't log off a character a bot is playing: the bot's + /// actions aren't keyboard/mouse input, so the client counted it as idle. Set false in + /// engine.json to get the retail behaviour back. + public static bool PreventIdleLogoff + { + get + { + EnsureLoaded(); + return _preventIdleLogoff; + } + } + public static void AddPluginPath(string path) { EnsureLoaded(); @@ -287,6 +302,12 @@ internal static class EngineSettings { _drawCustomVitalBars = cvbEl.GetBoolean(); } + + if (doc.RootElement.TryGetProperty("PreventIdleLogoff", out var pilEl) && + (pilEl.ValueKind == JsonValueKind.True || pilEl.ValueKind == JsonValueKind.False)) + { + _preventIdleLogoff = pilEl.GetBoolean(); + } } catch (Exception ex) { @@ -319,6 +340,7 @@ internal static class EngineSettings w.WriteBoolean("EnableImGuiBackend", _enableImGuiBackend); w.WriteBoolean("EnableHangMinidump", _enableHangMinidump); w.WriteBoolean("DrawCustomVitalBars", _drawCustomVitalBars); + w.WriteBoolean("PreventIdleLogoff", _preventIdleLogoff); w.WriteEndObject(); } File.WriteAllBytes(SettingsPath, ms.ToArray()); diff --git a/src/RynthCore.Engine/Plugins/PluginContract.cs b/src/RynthCore.Engine/Plugins/PluginContract.cs index 6223318..116fc52 100644 --- a/src/RynthCore.Engine/Plugins/PluginContract.cs +++ b/src/RynthCore.Engine/Plugins/PluginContract.cs @@ -596,6 +596,138 @@ internal struct RynthCoreAPI /// owned by the target plugin (valid until its next call on that export); copy it immediately. Requires /// API v66+. APPENDED-AT-END for ABI safety. public IntPtr GetPluginExportJsonFn; + + // ── Vendor trading (v67) ───────────────────────────────────────────── + // Decal's WorldFilter.OpenVendor + Actions.VendorBuyAll/VendorSellAll, as + // stateless batch calls. Reads come from a snapshot the engine takes on AC's + // main thread when the server's vendor list (ApproachVendor 0x0062) is + // opened; buy/sell are queued and sent on AC's main thread through the + // client's own gmVendorUI::SendShopEvent (CM_Vendor::Event_Buy/Event_Sell). + // See Compatibility/VendorTrade.cs. APPENDED-AT-END for ABI safety. + + /// Function pointer: int GetVendorInfo(VendorInfoNative* info) + /// Fills info for the vendor that is open right now. Returns 1 + /// if a vendor is open, 0 if not (info is zeroed). Any thread. Requires API v67+. + public IntPtr GetVendorInfoFn; + + /// Function pointer: int GetVendorItems(VendorItemNative* items, int maxCount) + /// Copies up to maxCount of the open vendor's items. Returns the TOTAL item count + /// (call with maxCount=0 to size a buffer), or -1 if no vendor is open. Any thread. + /// Requires API v67+. + public IntPtr GetVendorItemsFn; + + /// Function pointer: uint VendorBuy(uint vendorId, VendorTradeEntryNative* entries, int count) + /// Buys (objectId, amount) pairs from the open vendor (vendorId 0 = whichever is open). + /// Returns a request id (>0) once the request passes the snapshot checks and is + /// queued, or 0 if it was refused (reason in GetVendorTradeStatus and the log). + /// Funds, pack slots and burden are checked again on AC's main thread before the + /// packet goes out; poll GetVendorTradeStatus for the outcome. One transaction is in + /// flight at a time. Requires API v67+. + public IntPtr VendorBuyFn; + + /// Function pointer: uint VendorSell(uint vendorId, uint* itemIds, int count) + /// Sells the player's own items (whole stacks) to the open vendor. Same return and + /// status contract as VendorBuy. Requires API v67+. + public IntPtr VendorSellFn; + + /// Function pointer: int GetVendorTradeStatus(VendorTradeStatusNative* status) + /// Fills the state of the most recent VendorBuy/VendorSell request. Returns 1 if a + /// request has been made this session, 0 if not. Any thread. Requires API v67+. + public IntPtr GetVendorTradeStatusFn; +} + +// ─── Vendor trading ABI structs (v67) ─────────────────────────────────── +// Blittable, Pack=4, 4-byte fields + fixed ANSI buffers only. Mirrored exactly +// by RynthCore.PluginSdk/VendorTypes.cs. Never reorder or resize; add new calls +// instead of growing these. + +/// The open vendor (VendorProfile from ApproachVendor 0x0062). 192 bytes. +[StructLayout(LayoutKind.Sequential, Pack = 4)] +internal unsafe struct VendorInfoNative +{ + public uint VendorId; + /// Bumps every time the server (re)sends the vendor list: on open and after + /// each accepted buy/sell. Compare before/after a trade to see the refresh. + public uint Generation; + /// ShopMode passed to gmVendorUI::OpenVendor (raw client value). + public int ShopMode; + /// ITEM_TYPE mask of what the vendor buys. + public uint ItemTypes; + public int MinValue; + public int MaxValue; + public int DealsMagic; + /// Vendor pays value * BuyRate when you sell. + public float BuyRate; + /// Vendor charges value * SellRate when you buy. + public float SellRate; + /// WCID of the vendor's currency; 0 = pyreals. + public uint AltCurrencyWcid; + /// Alt currency count as the server reported it in the vendor list (-1 if none). + public int AltCurrencyServerCount; + /// Alt currency the engine counted in the player's packs (-1 = not counted yet). + public int AltCurrencyHave; + /// Player's pyreals (CoinValue), refreshed on AC's main thread; -1 unknown. + public int PlayerCoins; + public int ItemCount; + /// bit0 = trading available (client functions resolved and layout verified), + /// bit1 = a transaction is in flight. + public uint Flags; + public uint Reserved0; + public fixed byte Name[64]; + public fixed byte AltCurrencyName[64]; +} + +/// One item on the vendor's list (ItemProfile + its PublicWeenieDesc). 120 bytes. +[StructLayout(LayoutKind.Sequential, Pack = 4)] +internal unsafe struct VendorItemNative +{ + public uint ObjectId; + public uint Wcid; + public uint ItemType; + public uint IconId; + /// How many the vendor has; -1 = unlimited. + public int Amount; + public int StackSize; + public int MaxStackSize; + /// PWD value of the listed stack. + public int Value; + /// Value of one unit (Value / StackSize for stacks). + public int UnitValue; + /// What one unit costs the player here (server rounding; notes at 1.15x). + public int UnitPrice; + public int Burden; + /// bit0 unlimited, bit1 stackable, bit2 needs a container slot (pack/foci). + public uint Flags; + public uint Reserved0; + public uint Reserved1; + public fixed byte Name[64]; +} + +/// One buy line: vendor object id + how many. +[StructLayout(LayoutKind.Sequential, Pack = 4)] +internal struct VendorTradeEntryNative +{ + public uint ObjectId; + public int Amount; +} + +/// State of the most recent trade request. 160 bytes. +[StructLayout(LayoutKind.Sequential, Pack = 4)] +internal unsafe struct VendorTradeStatusNative +{ + public uint RequestId; + /// 1 queued, 2 sent (waiting for the server), 3 done, 4 refused (never sent). + public int State; + /// With State 3: 1 = server accepted (vendor list re-sent), 2 = server answered + /// without re-sending the list (refused: funds/busy/space), 3 = no answer (timed out). + public int Result; + public int IsBuy; + public uint VendorId; + public int EntryCount; + /// Buy: estimated cost (pyreals or alt currency). Sell: estimated payout. + public int Estimate; + public uint Reserved0; + public fixed byte Message[128]; } @@ -603,7 +735,7 @@ internal struct RynthCoreAPI /// Current API version. Bump when adding fields to RynthCoreAPI. internal static class PluginContractVersion { - public const uint Current = 66; + public const uint Current = 67; } internal static class ClientActionHookFlags @@ -1055,3 +1187,18 @@ internal unsafe delegate int GetObjectDataIdPropertyCallbackDelegate(uint object [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate IntPtr GetPluginExportJsonCallbackDelegate(IntPtr pluginNameAnsi, IntPtr exportNameAnsi); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate int GetVendorInfoCallbackDelegate(VendorInfoNative* info); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate int GetVendorItemsCallbackDelegate(VendorItemNative* items, int maxCount); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate uint VendorBuyCallbackDelegate(uint vendorId, VendorTradeEntryNative* entries, int count); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate uint VendorSellCallbackDelegate(uint vendorId, uint* itemIds, int count); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate int GetVendorTradeStatusCallbackDelegate(VendorTradeStatusNative* status); diff --git a/src/RynthCore.Engine/Plugins/PluginManager.cs b/src/RynthCore.Engine/Plugins/PluginManager.cs index 10387ea..c74693c 100644 --- a/src/RynthCore.Engine/Plugins/PluginManager.cs +++ b/src/RynthCore.Engine/Plugins/PluginManager.cs @@ -234,6 +234,11 @@ internal static class PluginManager private static SendPluginCommandCallbackDelegate? _sendPluginCommandCallback; private static GetObjectDataIdPropertyCallbackDelegate? _getObjectDataIdPropertyCallback; private static GetPluginExportJsonCallbackDelegate? _getPluginExportJsonCallback; + private static GetVendorInfoCallbackDelegate? _getVendorInfoCallback; + private static GetVendorItemsCallbackDelegate? _getVendorItemsCallback; + private static VendorBuyCallbackDelegate? _vendorBuyCallback; + private static VendorSellCallbackDelegate? _vendorSellCallback; + private static GetVendorTradeStatusCallbackDelegate? _getVendorTradeStatusCallback; private static ForceResetBusyCountCallbackDelegate? _forceResetBusyCountCallback; private static GetObjectSpellIdsCallbackDelegate? _getObjectSpellIdsCallback; private static GetObjectSkillLevelCallbackDelegate? _getObjectSkillBuffedCallback; @@ -2394,6 +2399,11 @@ internal static class PluginManager _sendPluginCommandCallback ??= SendPluginCommandAction; _getObjectDataIdPropertyCallback ??= GetObjectDataIdPropertyAction; _getPluginExportJsonCallback ??= GetPluginExportJsonAction; + _getVendorInfoCallback ??= GetVendorInfoAction; + _getVendorItemsCallback ??= GetVendorItemsAction; + _vendorBuyCallback ??= VendorBuyAction; + _vendorSellCallback ??= VendorSellAction; + _getVendorTradeStatusCallback ??= GetVendorTradeStatusAction; _api.Version = PluginContractVersion.Current; _api.LogFn = Marshal.GetFunctionPointerForDelegate(_logCallback); @@ -2505,6 +2515,11 @@ internal static class PluginManager _api.SendPluginCommandFn = Marshal.GetFunctionPointerForDelegate(_sendPluginCommandCallback); _api.GetObjectDataIdPropertyFn = Marshal.GetFunctionPointerForDelegate(_getObjectDataIdPropertyCallback); _api.GetPluginExportJsonFn = Marshal.GetFunctionPointerForDelegate(_getPluginExportJsonCallback); + _api.GetVendorInfoFn = Marshal.GetFunctionPointerForDelegate(_getVendorInfoCallback); + _api.GetVendorItemsFn = Marshal.GetFunctionPointerForDelegate(_getVendorItemsCallback); + _api.VendorBuyFn = Marshal.GetFunctionPointerForDelegate(_vendorBuyCallback); + _api.VendorSellFn = Marshal.GetFunctionPointerForDelegate(_vendorSellCallback); + _api.GetVendorTradeStatusFn = Marshal.GetFunctionPointerForDelegate(_getVendorTradeStatusCallback); } private static void ProbeClientHooks() @@ -3270,6 +3285,56 @@ internal static class PluginManager private static int GetUseDoneSeqAction() => SmartBoxHooks.GetUseDoneSeq(); + // ── Vendor trading (v67) — see Compatibility/VendorTrade.cs ───────────── + // Reads are served from the main-thread snapshot; buy/sell only queue here + // (checked against the snapshot) and go out on AC's main thread. + private static unsafe int GetVendorInfoAction(VendorInfoNative* info) + { + try { return VendorTrade.FillInfo(info); } + catch { return 0; } + } + + private static unsafe int GetVendorItemsAction(VendorItemNative* items, int maxCount) + { + try { return VendorTrade.FillItems(items, maxCount); } + catch { return -1; } + } + + private static unsafe uint VendorBuyAction(uint vendorId, VendorTradeEntryNative* entries, int count) + { + try + { + if (entries == null || count <= 0 || count > 1000) + return VendorTrade.RefuseRequest(true, vendorId, count, entries == null ? "null entry list" : $"bad line count {count}"); + var ids = new uint[count]; + var amounts = new int[count]; + for (int i = 0; i < count; i++) + { + ids[i] = entries[i].ObjectId; + amounts[i] = entries[i].Amount; + } + return VendorTrade.RequestBuy(vendorId, ids, amounts); + } + catch { return 0; } + } + + private static unsafe uint VendorSellAction(uint vendorId, uint* itemIds, int count) + { + try + { + if (itemIds == null || count <= 0 || count > 1000) + return VendorTrade.RefuseRequest(false, vendorId, count, itemIds == null ? "null item list" : $"bad line count {count}"); + return VendorTrade.RequestSell(vendorId, new ReadOnlySpan(itemIds, count)); + } + catch { return 0; } + } + + private static unsafe int GetVendorTradeStatusAction(VendorTradeStatusNative* status) + { + try { return VendorTrade.FillStatus(status); } + catch { return 0; } + } + private static void ForceResetBusyCountAction() => BusyCountHooks.ForceResetBusyCount(); private static unsafe int GetObjectSpellIdsAction(uint guid, uint* spellIds, int maxCount) diff --git a/src/RynthCore.Engine/UI/AvaloniaOverlay.cs b/src/RynthCore.Engine/UI/AvaloniaOverlay.cs index 9108e4c..c5636ad 100644 --- a/src/RynthCore.Engine/UI/AvaloniaOverlay.cs +++ b/src/RynthCore.Engine/UI/AvaloniaOverlay.cs @@ -68,6 +68,19 @@ internal static class AvaloniaOverlay // Same slot pattern as radar, for chat's own Ctrl-gated click-through // option (live-testing finding 2026-09-02). private static PhysicalRect? _chatPanelRect; + // Open Flyout / ContextMenu / ComboBox dropdowns, embedded in the overlay + // window's OverlayLayer (Win32PlatformOptions.OverlayPopups). They can hang + // past their panel's rect, so they're published separately and are always + // interactive. ToolTips are left out: they never take clicks. + private static PhysicalRect[] _popupRects = Array.Empty(); + + /// + /// True while a light-dismiss popup (Flyout, ContextMenu, ComboBox + /// dropdown) is open. A click on the game world is never forwarded to + /// Avalonia, so its own light-dismiss can't see it; Win32Backend checks + /// this and calls instead. + /// + internal static volatile bool HasOpenLightDismissPopup; [DllImport("user32.dll")] private static extern short GetAsyncKeyState(int vKey); @@ -226,6 +239,13 @@ internal static class AvaloniaOverlay lock (HitTestLock) { + // Open popups sit above every panel and are always interactive. + foreach (PhysicalRect rect in _popupRects) + { + if (rect.Contains(gameClientX, gameClientY)) + return true; + } + foreach (PhysicalRect rect in _panelRects) { if (rect.Contains(gameClientX, gameClientY)) @@ -348,6 +368,37 @@ internal static class AvaloniaOverlay Dispatcher.UIThread.Post(() => _window?.OnCustomFrameSubmitted(width, height), DispatcherPriority.Render); } + /// + /// Publish the physical bounds (game client pixels) of every open + /// interactive popup in the overlay window's OverlayLayer. Empty = none. + /// + internal static void PublishPopupRects(List<(double Left, double Top, double Width, double Height)> rects) + { + var snapshots = new PhysicalRect[rects.Count]; + for (int i = 0; i < rects.Count; i++) + { + snapshots[i] = new PhysicalRect( + (int)Math.Round(rects[i].Left), + (int)Math.Round(rects[i].Top), + (int)Math.Round(rects[i].Left + rects[i].Width), + (int)Math.Round(rects[i].Top + rects[i].Height)); + } + + lock (HitTestLock) + _popupRects = snapshots; + } + + /// + /// Close every open light-dismiss popup (Flyout, ContextMenu, dropdown). + /// Called from the game thread when the user clicks the game world while + /// one is open; the click itself still goes to AC. + /// + internal static void DismissLightDismissPopups() + { + HasOpenLightDismissPopup = false; + Dispatcher.UIThread.Post(() => _window?.CloseLightDismissPopups(), DispatcherPriority.Input); + } + internal static void PublishPanelRects(params (double Left, double Top, double Width, double Height)[] rects) { var snapshots = new PhysicalRect[rects.Length]; @@ -590,9 +641,11 @@ internal static class AvaloniaOverlay _window = null; _started = false; AvaloniaHwnd = IntPtr.Zero; + HasOpenLightDismissPopup = false; lock (HitTestLock) { _panelRects = Array.Empty(); + _popupRects = Array.Empty(); _barButtonRects = new Dictionary(StringComparer.OrdinalIgnoreCase); } } @@ -626,7 +679,19 @@ internal static class AvaloniaOverlay [ Win32CompositionMode.RedirectionSurface ], - ShouldRenderOnUIThread = true + ShouldRenderOnUIThread = true, + // Popup flash fix: without this every ToolTip, Flyout, + // ContextMenu and ComboBox dropdown opens as its own PopupRoot + // TopLevel (a native popup HWND), which the custom producer + // path rendered through the overlay's one render target - a + // popup-only frame reached the game and every docked panel + // vanished until the overlay window drew again. With + // OverlayPopups the popups live in the overlay window's + // OverlayLayer and are drawn in the same frame as the panels + // (no extra HWND, readback or focus change). The software + // fallback renders each TopLevel into its own framebuffer, so it + // keeps native popups as before. + OverlayPopups = UseCustomSkiaBridge, }; if (UseCustomSkiaBridge) @@ -1004,8 +1069,8 @@ internal class RynthOverlayWindow : Window // working) but the canvas RTT clips it; the host renders the Border into // its own RTT and pushes the pixels to the layered window via // UpdateLayeredWindow. This sidesteps OverlaySkiaPlatformGraphics - // entirely — the bridge is a singleton with one shared render target, - // so a real visible Avalonia Window would thrash that target. + // entirely - only the overlay window's render target reaches the game, so + // a real Avalonia Window would get a detached target and draw nowhere. private readonly Dictionary _floatingPanels = new(StringComparer.OrdinalIgnoreCase); private readonly Dictionary _panelContents = new(StringComparer.OrdinalIgnoreCase); // Each floating panel parks its chrome Border past the right edge of @@ -1177,6 +1242,11 @@ internal class RynthOverlayWindow : Window AvaloniaOverlay.RegisterWindow(this); + // Popups are embedded in this window's OverlayLayer (OverlayPopups). + // Track them for hit-testing, game-world light-dismiss and the + // popup-flash diagnostics (see the "Embedded popups" section). + InstallPopupTracking(); + _captureTimer = new DispatcherTimer(TimeSpan.FromMilliseconds(16), DispatcherPriority.Render, (_, _) => { if (_captureDirty) @@ -3859,6 +3929,266 @@ internal class RynthOverlayWindow : Window AvaloniaOverlay.PublishChatPanelRect(chatRect); } + // ── Embedded popups ──────────────────────────────────────────────────── + // With Win32PlatformOptions.OverlayPopups every Popup (ToolTip, Flyout, + // ContextMenu, ComboBox dropdown) is an OverlayPopupHost inside this + // window's OverlayLayer, so it is drawn in the same frame as the docked + // panels. Three things still need help from us: + // 1. hit-testing - a Flyout/menu can hang past its panel's rect, and + // Win32Backend only forwards clicks that land on published rects; + // 2. light-dismiss - a click on the game world never reaches Avalonia; + // 3. diagnostics - log whether a popup ever rebuilt the overlay surface + // or got its own TopLevel (the old "panel flash"). + + [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); + + private sealed class PopupTrack + { + public int Serial; + public string Kind = ""; + public string Host = ""; + public bool Suppressed; + public int SurfaceCreatesAtOpen; + public int DetachedTargetsAtOpen; + } + + private const int PopupLogNormalLineBudget = 40; + private const int PopupLogAnomalyLineBudget = 200; + private static RynthOverlayWindow? _popupOwner; + private static bool _popupClassHandlerInstalled; + private readonly Dictionary _openPopups = new(); + private int _popupSerial; + private int _popupNormalLines; + private int _popupAnomalyLines; + private bool _popupRectsPublished; + + private void InstallPopupTracking() + { + _popupOwner = this; + if (!_popupClassHandlerInstalled) + { + _popupClassHandlerInstalled = true; + Avalonia.Controls.Primitives.Popup.IsOpenProperty.Changed.AddClassHandler( + (popup, e) => _popupOwner?.OnAnyPopupIsOpenChanged(popup, e.NewValue.GetValueOrDefault())); + } + + // Fires after every layout pass: keeps popup hit rects in step with + // Flyout content changes and repositioning. Returns at once when no + // popup is open. + LayoutUpdated += (_, _) => RefreshPopupHitRects(); + } + + private void OnAnyPopupIsOpenChanged(Avalonia.Controls.Primitives.Popup popup, bool isOpen) + { + try + { + if (isOpen) + { + if (_openPopups.ContainsKey(popup)) + return; + + var track = new PopupTrack + { + Serial = ++_popupSerial, + Kind = DescribePopup(popup), + Host = popup.Host?.GetType().Name ?? "none", + SurfaceCreatesAtOpen = OverlaySkiaRenderTarget.SurfaceCreateCount, + DetachedTargetsAtOpen = OverlaySkiaGpuContext.DetachedTargetCount, + }; + _openPopups[popup] = track; + UpdateLightDismissFlag(); + + // A ToolTip for a control inside a popped-out panel: that + // control lives in the off-bounds canvas strip, so the embedded + // tooltip would be clamped onto the edge of the in-game overlay, + // nowhere near the floating window. Don't show it. + if (popup.Child is ToolTip && popup.PlacementTarget is Control tipTarget && !IsInsideOverlayClientArea(tipTarget)) + { + track.Suppressed = true; + Dispatcher.UIThread.Post(() => + { + try { ToolTip.SetIsOpen(tipTarget, false); } catch { } + }, DispatcherPriority.Send); + } + + Dispatcher.UIThread.Post(() => + { + RefreshPopupHitRects(); + LogPopupOpened(track); + }, DispatcherPriority.Background); + } + else + { + if (!_openPopups.Remove(popup, out PopupTrack? track)) + return; + + UpdateLightDismissFlag(); + RefreshPopupHitRects(); + + // The old flash rebuilt the overlay surface on the window's next + // frame after the popup closed, so check a moment later. + DispatcherTimer.RunOnce(() => LogPopupClosed(track), TimeSpan.FromMilliseconds(1000), DispatcherPriority.Background); + } + } + catch (Exception ex) + { + RynthLog.UI($"OverlayPopup: tracking threw {ex.GetType().Name}: {ex.Message}"); + } + } + + private static string DescribePopup(Avalonia.Controls.Primitives.Popup popup) + { + string child = popup.Child?.GetType().Name ?? "empty"; + string? owner = popup.TemplatedParent?.GetType().Name; + return owner != null ? $"{owner}/{child}" : child; + } + + private bool IsInsideOverlayClientArea(Control control) + { + Point? origin = control.TranslatePoint(default, this); + if (origin == null) + return true; + + double width = Bounds.Width > 0 ? Bounds.Width : Width; + double height = Bounds.Height > 0 ? Bounds.Height : Height; + return origin.Value.X < width && origin.Value.Y < height && + origin.Value.X + control.Bounds.Width > 0 && origin.Value.Y + control.Bounds.Height > 0; + } + + private void UpdateLightDismissFlag() + { + bool any = false; + foreach (Avalonia.Controls.Primitives.Popup popup in _openPopups.Keys) + { + if (popup.IsLightDismissEnabled) + { + any = true; + break; + } + } + + AvaloniaOverlay.HasOpenLightDismissPopup = any; + } + + /// + /// Close open light-dismiss popups because the user clicked the game world. + /// Popup.Close is the same call Avalonia's own light-dismiss makes, so + /// Flyout/ContextMenu/ComboBox state stays in sync. + /// + internal void CloseLightDismissPopups() + { + foreach (Avalonia.Controls.Primitives.Popup popup in _openPopups.Keys.ToArray()) + { + if (!popup.IsOpen || !popup.IsLightDismissEnabled) + continue; + + try { popup.Close(); } + catch (Exception ex) { RynthLog.UI($"OverlayPopup: dismiss threw {ex.GetType().Name}: {ex.Message}"); } + } + + UpdateLightDismissFlag(); + } + + private void RefreshPopupHitRects() + { + if (_openPopups.Count == 0) + { + if (_popupRectsPublished) + { + AvaloniaOverlay.PublishPopupRects(new List<(double, double, double, double)>()); + _popupRectsPublished = false; + } + return; + } + + float scale = (float)GetEffectiveRenderScale(); + var rects = new List<(double Left, double Top, double Width, double Height)>(_openPopups.Count); + List? stale = null; + foreach ((Avalonia.Controls.Primitives.Popup popup, PopupTrack track) in _openPopups) + { + if (!popup.IsOpen) + { + (stale ??= new()).Add(popup); + continue; + } + + // ToolTips never take clicks; a click over one must reach AC. + if (track.Suppressed || popup.Child is ToolTip) + continue; + + // OverlayPopupHost is a control in this window's OverlayLayer. A + // native PopupRoot (not expected) would be its own root: skipped. + if (popup.Host is not Visual host || !host.IsVisible) + continue; + + Point? origin = host.TranslatePoint(default, _desktopCanvas); + if (origin == null || host.Bounds.Width <= 0 || host.Bounds.Height <= 0) + continue; + + rects.Add((origin.Value.X * scale, origin.Value.Y * scale, host.Bounds.Width * scale, host.Bounds.Height * scale)); + } + + if (stale != null) + { + foreach (Avalonia.Controls.Primitives.Popup popup in stale) + _openPopups.Remove(popup); + UpdateLightDismissFlag(); + } + + AvaloniaOverlay.PublishPopupRects(rects); + _popupRectsPublished = rects.Count > 0; + } + + private bool TakePopupLogLine(bool anomaly) + { + if (anomaly) + return _popupAnomalyLines++ < PopupLogAnomalyLineBudget; + + if (_popupNormalLines < PopupLogNormalLineBudget) + { + _popupNormalLines++; + return true; + } + + if (_popupNormalLines == PopupLogNormalLineBudget) + { + _popupNormalLines++; + RynthLog.UI("OverlayPopup: normal popup open/close lines muted for this session; anomalies are still logged."); + } + return false; + } + + private void LogPopupOpened(PopupTrack track) + { + // Expected: host=OverlayPopupHost (drawn in the overlay frame). A + // PopupRoot here means a native popup TopLevel - the flash path. + bool anomaly = !track.Suppressed && track.Host != "OverlayPopupHost"; + if (!TakePopupLogLine(anomaly)) + return; + + IntPtr game = Win32Backend.GameHwnd; + string fg = game == IntPtr.Zero ? "?" : GetForegroundWindow() == game ? "game" : "other"; + RynthLog.UI( + $"OverlayPopup: open #{track.Serial} {track.Kind} host={track.Host}" + + (track.Suppressed ? " (tooltip of a popped-out panel - not shown)" : "") + + $" surfaceCreates={track.SurfaceCreatesAtOpen} detachedTargets={track.DetachedTargetsAtOpen} foreground={fg}."); + } + + private void LogPopupClosed(PopupTrack track) + { + int rebuilds = OverlaySkiaRenderTarget.SurfaceCreateCount - track.SurfaceCreatesAtOpen; + int detached = OverlaySkiaGpuContext.DetachedTargetCount - track.DetachedTargetsAtOpen; + bool anomaly = rebuilds != 0 || detached != 0; + if (!TakePopupLogLine(anomaly)) + return; + + IntPtr game = Win32Backend.GameHwnd; + string fg = game == IntPtr.Zero ? "?" : GetForegroundWindow() == game ? "game" : "other"; + RynthLog.UI( + $"OverlayPopup: close #{track.Serial} {track.Kind} surfaceRebuilds=+{rebuilds} detachedTargets=+{detached} foreground={fg}" + + (anomaly ? " - overlay surface was rebuilt or a popup TopLevel appeared (panel flash / resize)." : " - no flash.")); + } + private void QueueCapture() { if (AvaloniaOverlay.ShouldUseCustomSkiaProducer || _captureQueued) @@ -3882,6 +4212,16 @@ internal class RynthOverlayWindow : Window /// internal void TickFloatingPanels() { + // The UI hides between characters: popped-out panels (and a floating bar) are + // real windows, so they're hidden outright while not in the world rather than + // left sitting over character select. SetShown only acts on a change. + bool inWorld = Compatibility.LoginLifecycleHooks.HasObservedLoginComplete; + foreach (FloatingPanelHost host in _floatingPanels.Values) + host.SetShown(inWorld); + _floatingBar?.SetShown(inWorld); + if (!inWorld) + return; + if (_floatingPanels.Count > 0) { foreach (FloatingPanelHost host in _floatingPanels.Values) @@ -3916,9 +4256,11 @@ internal class RynthOverlayWindow : Window /// forwarded to the off-screen Avalonia HWND with translated coords so the /// panel's buttons/scrollbars/etc. behave the same as when docked. /// -/// This deliberately does NOT use Avalonia's Window — a second Avalonia -/// top-level routes through OverlaySkiaPlatformGraphics' singleton render -/// target and thrashes the in-AC capture (the original "flashing" bug). +/// This deliberately does NOT use Avalonia's Window. A second Avalonia +/// top-level used to share OverlaySkiaPlatformGraphics' render target and +/// blank the in-AC capture (the original "flashing" bug); it now gets a +/// detached target (see OverlaySkiaGpuContext.TryCreateRenderTarget), so it +/// would draw nowhere at all. /// internal sealed unsafe class FloatingPanelHost : IDisposable { @@ -4156,6 +4498,23 @@ internal sealed unsafe class FloatingPanelHost : IDisposable /// RynthOverlayWindow's _captureTimer so render and panel state stay in /// sync. Skips the heavy work if the panel hasn't been arranged yet. /// + // Created shown (the constructor shows the window); SetShown tracks changes from there. + private volatile bool _windowShown = true; + + /// + /// Hide or show the popped-out window (the UI hides between characters). Only acts + /// on a change; the window belongs to AC's thread, so the call is marshalled there. + /// + internal void SetShown(bool shown) + { + if (_disposed || _layered.Hwnd == IntPtr.Zero || _windowShown == shown) return; + _windowShown = shown; + ImGuiBackend.Win32Backend.RunOnGameThread(() => + { + if (shown) _layered.Show(); else _layered.Hide(); + }); + } + public void Tick() { if (_disposed || _layered.Hwnd == IntPtr.Zero) return; diff --git a/src/RynthCore.Engine/UI/LayeredWindow.cs b/src/RynthCore.Engine/UI/LayeredWindow.cs index 7d0cbbd..cf45708 100644 --- a/src/RynthCore.Engine/UI/LayeredWindow.cs +++ b/src/RynthCore.Engine/UI/LayeredWindow.cs @@ -42,7 +42,8 @@ internal sealed unsafe class LayeredWindow : IDisposable // class because its WndProc points into the unloaded DLL. So bake a // per-DLL-load Guid into the name — each engine instance gets a fresh // class atom backed by its own WndProc pointer. - private static readonly string ClassName = "RynthCoreLayeredPanel_" + Guid.NewGuid().ToString("N"); + private const string ClassNamePrefix = "RynthCoreLayeredPanel_"; + private static readonly string ClassName = ClassNamePrefix + Guid.NewGuid().ToString("N"); private const int WS_POPUP = unchecked((int)0x80000000); private const int WS_EX_LAYERED = 0x00080000; @@ -273,6 +274,68 @@ internal sealed unsafe class LayeredWindow : IDisposable return DefWindowProcW(hwnd, msg, wParam, lParam); } + [DllImport("user32.dll")] + private static extern int EnumThreadWindows(uint dwThreadId, delegate* unmanaged[Stdcall] lpfn, IntPtr lParam); + + [DllImport("user32.dll", CharSet = CharSet.Unicode)] + private static extern int GetClassNameW(IntPtr hWnd, char* lpClassName, int nMaxCount); + + [UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvStdcall) })] + private static int CollectThreadWindow(IntPtr hwnd, IntPtr lParam) + { + if (GCHandle.FromIntPtr(lParam).Target is List found) + found.Add(hwnd); + return 1; + } + + /// + /// Destroys panel windows owned by the calling thread. + /// Must run on AC's game thread — the panels are created there (see + /// FloatingPanelHost's RunOnGameThread) and DestroyWindow only works on + /// the owning thread. + /// + /// Dispose only posts the destroy, and Win32Backend.Shutdown unhooks the + /// game WndProc ~1 ms after the overlay stops — usually before the game + /// thread gets to the post. AC's own WndProc then drops it, and because + /// the engine module is never unloaded the panel lives on: frozen on its + /// last frame, deaf to input, and hidden under the next generation's copy + /// of it until that one is moved ("two RynthAi windows"). + /// + /// =false spares this engine + /// load's own windows (class names carry a per-load Guid) and removes only + /// ones an earlier load left behind. + /// + internal static void DestroyThreadPanelWindows(bool includeThisGeneration) + { + var found = new List(); + GCHandle handle = GCHandle.Alloc(found); + try + { + EnumThreadWindows(GetCurrentThreadId(), &CollectThreadWindow, GCHandle.ToIntPtr(handle)); + } + finally + { + handle.Free(); + } + + char* buffer = stackalloc char[128]; + foreach (IntPtr hwnd in found) + { + int length = GetClassNameW(hwnd, buffer, 128); + if (length <= 0) + continue; + string className = new(buffer, 0, length); + if (!className.StartsWith(ClassNamePrefix, StringComparison.Ordinal)) + continue; + bool thisGeneration = className == ClassName; + if (thisGeneration && !includeThisGeneration) + continue; + + bool ok = DestroyWindow(hwnd); + RynthCore.Engine.RynthLog.Info($"LayeredWindow: DestroyWindow(0x{hwnd.ToInt64():X}) = {ok} — {(thisGeneration ? "still open at shutdown" : "left over from an earlier engine load")}."); + } + } + // ─── Instance state ──────────────────────────────────────────────────── public IntPtr Hwnd { get; private set; } public int Width { get; private set; } diff --git a/src/RynthCore.Engine/UI/OverlaySkiaPlatformGraphics.cs b/src/RynthCore.Engine/UI/OverlaySkiaPlatformGraphics.cs index 531813a..6fa576e 100644 --- a/src/RynthCore.Engine/UI/OverlaySkiaPlatformGraphics.cs +++ b/src/RynthCore.Engine/UI/OverlaySkiaPlatformGraphics.cs @@ -24,9 +24,18 @@ internal sealed class OverlaySkiaPlatformGraphics : IPlatformGraphicsWithFeature internal sealed class OverlaySkiaGpuContext : ISkiaGpu { private static readonly IDisposable NoopLease = new NoopDisposable(); + private static int _detachedTargetCount; private readonly object _sync = new(); private OverlaySkiaRenderTarget? _renderTarget; + /// + /// How many TopLevels other than the overlay window asked for a render + /// target this session. Expected to stay 0: popups are embedded in the + /// overlay window (Win32PlatformOptions.OverlayPopups). Logged with every + /// popup open/close so a regression is visible in the per-pid log. + /// + internal static int DetachedTargetCount => Volatile.Read(ref _detachedTargetCount); + public bool IsLost => false; public IDisposable EnsureCurrent() => NoopLease; @@ -37,11 +46,53 @@ internal sealed class OverlaySkiaGpuContext : ISkiaGpu { lock (_sync) { - _renderTarget ??= new OverlaySkiaRenderTarget(); + // Only the overlay window may own the render target whose frames go + // to the game. Every Avalonia TopLevel calls this - before the + // OverlayPopups fix each ToolTip/Flyout/ContextMenu/ComboBox opened + // a PopupRoot TopLevel that got this same target: its render cleared + // the shared surface and submitted a popup-only frame (every docked + // panel vanished), and closing it disposed the surface under the + // overlay window (rebuilt on its next frame). Any other TopLevel now + // gets a detached target that renders nowhere. + IntPtr hwnd = TryGetHwnd(surfaces); + IntPtr overlayHwnd = AvaloniaOverlay.AvaloniaHwnd; + bool isOverlayWindow = overlayHwnd != IntPtr.Zero && hwnd != IntPtr.Zero + ? hwnd == overlayHwnd + : _renderTarget == null || _renderTarget.IsDisposed; + + if (!isOverlayWindow) + { + int n = Interlocked.Increment(ref _detachedTargetCount); + RynthLog.UI($"OverlaySkiaGpuContext: TopLevel hwnd=0x{hwnd.ToInt64():X} is not the overlay window (0x{overlayHwnd.ToInt64():X}); gave it detached render target #{n} so it can't blank the docked panels."); + return new DetachedOverlayRenderTarget(); + } + + if (_renderTarget == null || _renderTarget.IsDisposed) + _renderTarget = new OverlaySkiaRenderTarget(); return _renderTarget; } } + private static IntPtr TryGetHwnd(IEnumerable surfaces) + { + try + { + foreach (object surface in surfaces) + { + if (surface is IPlatformHandle handle && + string.Equals(handle.HandleDescriptor, "HWND", StringComparison.OrdinalIgnoreCase)) + { + return handle.Handle; + } + } + } + catch + { + } + + return IntPtr.Zero; + } + public ISkiaSurface? TryCreateSurface(PixelSize size, ISkiaGpuRenderSession? session) { if (size.Width <= 0 || size.Height <= 0) @@ -85,6 +136,20 @@ internal sealed class OverlaySkiaRenderTarget : ISkiaGpuRenderTarget private int _width; private int _height; private int _loggedSharedTextureDisabled; + private bool _disposed; + private static int _surfaceCreateCount; + + /// + /// Full-size raster surfaces created this session (startup + resizes, and + /// the old popup-flash rebuilds). Popup open/close logging compares it + /// before and after each popup: anything other than +0 is the flash. + /// + internal static int SurfaceCreateCount => Volatile.Read(ref _surfaceCreateCount); + + internal bool IsDisposed + { + get { lock (_sync) return _disposed; } + } public bool IsCorrupted => false; @@ -105,10 +170,12 @@ internal sealed class OverlaySkiaRenderTarget : ISkiaGpuRenderTarget { lock (_sync) { + _disposed = true; _surface?.Dispose(); _surface = null; _softwareBuffer = null; _sharedTexturePublisher?.Dispose(); + _sharedTexturePublisher = null; _width = 0; _height = 0; } @@ -174,13 +241,22 @@ internal sealed class OverlaySkiaRenderTarget : ISkiaGpuRenderTarget if (_surface != null && width == _width && height == _height) return; + // Why the surface is being (re)built. "recreate-after-dispose" at an + // unchanged size is the old popup-flash signature: a TopLevel disposed + // this target and the overlay window had to rebuild it. + string reason = _surface != null + ? $"resize {_width}x{_height}->{width}x{height}" + : _disposed ? "recreate-after-dispose" : "initial"; + _disposed = false; + _surface?.Dispose(); _width = width; _height = height; var info = new SKImageInfo(width, height, SKColorType.Bgra8888, SKAlphaType.Premul); _surface = SKSurface.Create(info); - RynthLog.UI($"OverlaySkiaRenderTarget: Created raster render surface {_width}x{_height}."); + int total = Interlocked.Increment(ref _surfaceCreateCount); + RynthLog.UI($"OverlaySkiaRenderTarget: Created raster render surface {_width}x{_height} (reason={reason}, total={total})."); } } @@ -259,6 +335,53 @@ internal sealed class OverlaySkiaRenderSession : ISkiaGpuRenderSession } } +/// +/// Render target for any Avalonia TopLevel that is not the overlay window. +/// Avalonia needs somewhere to draw, but only the overlay window's frames may +/// reach the game: this target draws into a private 1x1 raster surface and +/// never submits, reads back or clears anything shared. +/// +internal sealed class DetachedOverlayRenderTarget : ISkiaGpuRenderTarget +{ + private readonly object _sync = new(); + private SKSurface? _surface; + + public bool IsCorrupted => false; + + public ISkiaGpuRenderSession BeginRenderingSession() + { + lock (_sync) + { + _surface ??= SKSurface.Create(new SKImageInfo(1, 1, SKColorType.Bgra8888, SKAlphaType.Premul)) + ?? throw new InvalidOperationException("Detached overlay render surface could not be created."); + return new Session(_surface); + } + } + + public void Dispose() + { + lock (_sync) + { + _surface?.Dispose(); + _surface = null; + } + } + + private sealed class Session : ISkiaGpuRenderSession + { + public Session(SKSurface surface) => SkSurface = surface; + + public GRContext GrContext => null!; + public double ScaleFactor => 1.0d; + public SKSurface SkSurface { get; } + public GRSurfaceOrigin SurfaceOrigin => GRSurfaceOrigin.TopLeft; + + public void Dispose() + { + } + } +} + internal sealed class OverlaySkiaSurface : ISkiaSurface { public OverlaySkiaSurface(int width, int height) diff --git a/src/RynthCore.Engine/UI/Panels/MetaPanel.cs b/src/RynthCore.Engine/UI/Panels/MetaPanel.cs index 416ddf5..73109a0 100644 --- a/src/RynthCore.Engine/UI/Panels/MetaPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/MetaPanel.cs @@ -111,6 +111,20 @@ internal static class MetaPanel // Composite condition indices: All=2, Any=3, Not=20 private static bool IsCompositeCondition(int idx) => idx is 2 or 3 or 20; + + /// One condition as text, nested ones included: "Not No Monsters Within Dist: 5", + /// "Any(Chat Message: …, Navroute Empty)". + private static string CondText(MetaRuleDto c, int depth = 0) + { + string name = c.Condition >= 0 && c.Condition < ConditionNames.Length + ? ConditionNames[c.Condition] : $"Cond({c.Condition})"; + if (IsCompositeCondition(c.Condition) && c.Children.Count > 0 && depth < MaxSubConditionDepth) + { + if (c.Condition == 20) return $"Not {CondText(c.Children[0], depth + 1)}"; + return $"{name}({string.Join(", ", c.Children.Select(x => CondText(x, depth + 1)))})"; + } + return string.IsNullOrEmpty(c.ConditionData) ? name : $"{name}: {c.ConditionData}"; + } // All action index = 4 private static bool IsAllAction(int idx) => idx == 4; @@ -796,10 +810,7 @@ internal static class MetaPanel string condText; if (IsCompositeCondition(rule.Condition) && rule.Children.Count > 0) { - var first = rule.Children[0]; - string fn = first.Condition >= 0 && first.Condition < ConditionNames.Length - ? ConditionNames[first.Condition] : $"Cond({first.Condition})"; - string ft = string.IsNullOrEmpty(first.ConditionData) ? fn : $"{fn}: {first.ConditionData}"; + string ft = CondText(rule.Children[0]); condText = rule.Children.Count > 1 ? $"{condName}: {ft} (+{rule.Children.Count - 1})" : $"{condName}: {ft}"; @@ -869,9 +880,7 @@ internal static class MetaPanel }); foreach (var child in rule.Children) { - string cn = child.Condition >= 0 && child.Condition < ConditionNames.Length - ? ConditionNames[child.Condition] : $"Cond({child.Condition})"; - string ct = string.IsNullOrEmpty(child.ConditionData) ? cn : $"{cn}: {child.ConditionData}"; + string ct = CondText(child); groupPanel.Children.Add(new TextBlock { Text = $" • {ct}", Foreground = ColMute, FontSize = 9, @@ -1133,7 +1142,9 @@ internal static class MetaPanel } else { - BuildSubRuleSection(content, ps, picker, rebuild, r.Children, "Sub-Conditions", isAction: false); + BuildSubRuleSection(content, ps, picker, rebuild, r.Children, + r.Condition == 20 ? "Not (one condition):" : "Sub-Conditions", isAction: false, + maxCount: r.Condition == 20 ? 1 : int.MaxValue); } // ── Action ──────────────────────────────────────────────────────────── @@ -1227,9 +1238,14 @@ internal static class MetaPanel content.Children.Add(btnRow); } + // Sub-conditions nest: a Not/All/Any sub-condition gets its own indented list below its + // row (a Not takes exactly one). They used to be single flat rows, so a Not under an All + // had nowhere to say what it negates. Deep enough for anything a meta writes. + private const int MaxSubConditionDepth = 4; + private static void BuildSubRuleSection( StackPanel content, PanelState ps, PickerState picker, Action rebuild, - List subRules, string label, bool isAction) + List subRules, string label, bool isAction, int depth = 0, int maxCount = int.MaxValue) { content.Children.Add(new TextBlock { @@ -1255,11 +1271,30 @@ internal static class MetaPanel { if (isAction) sub.Action = idx; else sub.Condition = idx; typeBtn.Content = names[idx]; + if (!isAction) + { + // Composite ↔ simple changes the row's shape: redraw it. + if (!IsCompositeCondition(idx)) sub.Children.Clear(); + else if (idx == 20 && sub.Children.Count > 1) sub.Children.RemoveRange(1, sub.Children.Count - 1); + rebuild(); + } }); }; Grid.SetColumn(typeBtn, 0); subRow.Children.Add(typeBtn); + bool nests = !isAction && IsCompositeCondition(sub.Condition) && depth < MaxSubConditionDepth; + if (nests) + { + subRow.Children.Add(new TextBlock + { + Text = sub.Condition == 20 ? "(the condition below)" : "(the conditions below)", + Foreground = ColTextDim, FontSize = 9, VerticalAlignment = VerticalAlignment.Center, + Margin = new Thickness(6, 0, 0, 0), + }); + Grid.SetColumn(subRow.Children[^1], 1); + } + var dataBox = new TextBox { Text = isAction ? sub.ActionData : sub.ConditionData, @@ -1270,7 +1305,7 @@ internal static class MetaPanel }; dataBox.TextChanged += (_, _) => { if (isAction) sub.ActionData = dataBox.Text ?? ""; else sub.ConditionData = dataBox.Text ?? ""; }; Grid.SetColumn(dataBox, 1); - subRow.Children.Add(dataBox); + if (!nests) subRow.Children.Add(dataBox); var rmBtn = new Button { @@ -1286,8 +1321,19 @@ internal static class MetaPanel subRow.Children.Add(rmBtn); content.Children.Add(subRow); + + if (nests) + { + var nested = new StackPanel { Margin = new Thickness(14, 0, 0, 2) }; + string nestedLabel = sub.Condition switch { 20 => "Not:", 2 => "All of:", _ => "Any of:" }; + BuildSubRuleSection(nested, ps, picker, rebuild, sub.Children, nestedLabel, isAction: false, + depth + 1, maxCount: sub.Condition == 20 ? 1 : int.MaxValue); + content.Children.Add(nested); + } } + if (subRules.Count >= maxCount) return; // a Not already has its one operand + var addSubBtn = new Button { Content = $"+ Add", diff --git a/src/RynthCore.Engine/UI/Panels/RadarPanel.cs b/src/RynthCore.Engine/UI/Panels/RadarPanel.cs index fa5d42a..e591de8 100644 --- a/src/RynthCore.Engine/UI/Panels/RadarPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/RadarPanel.cs @@ -1148,10 +1148,11 @@ internal static partial class RadarPanel HorizontalContentAlignment = HorizontalAlignment.Center, VerticalContentAlignment = VerticalAlignment.Center, }; - // Tooltip parameter intentionally unused: ToolTip.SetTip() schedules - // an Avalonia ToolTip Popup whose hover-enter side effects flash the - // entire overlay capture pipeline (a one-frame invalidation that's - // very visible against AC's frame). Glyphs are self-descriptive. + // Tooltip parameter intentionally unused. It was dropped because a + // ToolTip popup used to blank every docked panel (the "panel flash"). + // Popups are now drawn inside the overlay frame (OverlayPopups, see + // AvaloniaOverlay.ThreadMain), so ToolTip.SetTip would be safe here; + // the glyphs are self-descriptive, so they stay tooltip-less. _ = tooltip; // Eat pointer events so they don't bubble through to the radar // surface's drag handler beneath. diff --git a/src/RynthCore.Engine/UI/Panels/RynthAiPanel.cs b/src/RynthCore.Engine/UI/Panels/RynthAiPanel.cs index bfb3c89..62d184b 100644 --- a/src/RynthCore.Engine/UI/Panels/RynthAiPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/RynthAiPanel.cs @@ -487,7 +487,22 @@ internal static partial class RynthAiPanel rightStack.Children.Add(BuildSelectorRow("Profile:", profileSelector)); rightStack.Children.Add(BuildSelectorRow("Nav:", navSelector)); - rightStack.Children.Add(BuildSelectorRow("Loot:", lootSelector)); + // ✎ opens the standalone Loot Editor on the loot profile in use - or, while a + // vendor is open, on that vendor's AutoVendor profile (both are .utl files). + var lootEditButton = new Button + { + Content = "✎", + FontSize = 10, + Padding = new Thickness(5, 0), + Margin = new Thickness(3, 0, 0, 0), + MinHeight = 0, + Background = new SolidColorBrush(Color.FromRgb(0x2D, 0x38, 0x47)), + Foreground = ColMute, + BorderThickness = new Thickness(0), + VerticalAlignment = VerticalAlignment.Stretch, + }; + ToolTip.SetTip(lootEditButton, "Edit in the Loot Editor: the loot profile in use, or the open vendor's AutoVendor profile."); + rightStack.Children.Add(BuildSelectorRow("Loot:", lootSelector, lootEditButton)); rightStack.Children.Add(BuildSelectorRow("Meta:", metaSelector)); headerGrid.Children.Add(rightStack); @@ -835,6 +850,12 @@ internal static partial class RynthAiPanel ShowPicker(navSelector, snap.NavProfiles, snap.SelectedNavIdx, idx => _selectProfile?.Invoke(0, idx)); lootSelector.Click += (_, _) => ShowPicker(lootSelector, snap.LootProfiles, snap.SelectedLootIdx, idx => _selectProfile?.Invoke(1, idx)); + lootEditButton.Click += (_, _) => + { + ClosePicker(); + string path = !string.IsNullOrEmpty(snap.VendorProfilePath) ? snap.VendorProfilePath : snap.CurrentLootPath; + LaunchLootEditor(path); + }; metaSelector.Click += (_, _) => ShowPicker(metaSelector, snap.MetaProfiles, snap.SelectedMetaIdx, idx => _selectProfile?.Invoke(2, idx)); @@ -1035,11 +1056,11 @@ internal static partial class RynthAiPanel return stack; } - private static Grid BuildSelectorRow(string label, Button selector) + private static Grid BuildSelectorRow(string label, Button selector, Button? trailing = null) { var row = new Grid { - ColumnDefinitions = new ColumnDefinitions("36,*"), + ColumnDefinitions = new ColumnDefinitions(trailing == null ? "36,*" : "36,*,Auto"), Margin = new Thickness(0, 0, 0, 0) }; row.Children.Add(new TextBlock @@ -1051,9 +1072,52 @@ internal static partial class RynthAiPanel }); row.Children.Add(selector); Grid.SetColumn(selector, 1); + if (trailing != null) + { + row.Children.Add(trailing); + Grid.SetColumn(trailing, 2); + } return row; } + [DllImport("shell32.dll", CharSet = CharSet.Unicode, EntryPoint = "ShellExecuteW")] + private static extern IntPtr ShellExecuteW(IntPtr hwnd, string lpOperation, string lpFile, + string? lpParameters, string? lpDirectory, int nShowCmd); + + /// + /// Starts the standalone Loot Editor on (empty = no file). + /// The installer puts it in {app}\Tools\LootEditor next to Runtime\, so walk up from the + /// engine module (Runtime\ or Runtime\.engine_loads\) to find it. ShellExecute, not + /// Process.Start: the Process API is the documented AV hazard inside acclient.exe. + /// + private static void LaunchLootEditor(string? profilePath) + { + try + { + string? exe = null; + string? dir = EntryPoint.EngineDirectory; + for (int i = 0; i < 4 && !string.IsNullOrEmpty(dir) && exe == null; i++, dir = System.IO.Path.GetDirectoryName(dir)) + { + string candidate = System.IO.Path.Combine(dir, "Tools", "LootEditor", "RynthCore.LootEditor.exe"); + if (System.IO.File.Exists(candidate)) exe = candidate; + } + exe ??= @"C:\Games\RynthCore\Tools\LootEditor\RynthCore.LootEditor.exe"; + if (!System.IO.File.Exists(exe)) + { + RynthLog.Info($"RynthAiPanel: Loot Editor not found (looked for {exe})."); + return; + } + + string? args = string.IsNullOrEmpty(profilePath) ? null : $"\"{profilePath}\""; + IntPtr r = ShellExecuteW(IntPtr.Zero, "open", exe, args, System.IO.Path.GetDirectoryName(exe), 1 /* SW_SHOWNORMAL */); + RynthLog.Info($"RynthAiPanel: Loot Editor {(r.ToInt64() > 32 ? "started" : $"failed to start (code {r.ToInt64()})")}: {exe} {args}"); + } + catch (Exception ex) + { + RynthLog.Info($"RynthAiPanel: Loot Editor launch threw {ex.GetType().Name}: {ex.Message}"); + } + } + private static Button CreateSelector(string text) { // ImGui dashboard pushes ImGuiCol.FrameBg = (0.18, 0.22, 0.28) → #2D3847 @@ -1507,6 +1571,9 @@ internal static partial class RynthAiPanel [JsonPropertyName("metaProfiles")] public string[] MetaProfiles { get; set; } = Array.Empty(); [JsonPropertyName("currentNavName")] public string CurrentNavName { get; set; } = string.Empty; [JsonPropertyName("currentLootName")] public string CurrentLootName { get; set; } = string.Empty; + [JsonPropertyName("currentLootPath")] public string CurrentLootPath { get; set; } = string.Empty; + // Set while a vendor is open: the AutoVendor profile it would use (may not exist yet). + [JsonPropertyName("vendorProfilePath")] public string VendorProfilePath { get; set; } = string.Empty; [JsonPropertyName("currentMetaName")] public string CurrentMetaName { get; set; } = string.Empty; [JsonPropertyName("selectedNavIdx")] public int SelectedNavIdx { get; set; } [JsonPropertyName("selectedLootIdx")] public int SelectedLootIdx { get; set; } diff --git a/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs b/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs index bbcb3c3..cb613ae 100644 --- a/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs @@ -61,7 +61,7 @@ internal static class SettingsPanel private static readonly string[] Tabs = { "Display", "UI", "Misc", "Recharge", "Melee Combat", "Spell Combat", - "Ranges", "Navigation", "Buffing", "Crafting", "Looting" }; + "Ranges", "Navigation", "Buffing", "Crafting", "Looting", "Vendoring" }; private static readonly string[] AttackHeights = { "Low", "Medium", "High" }; private static readonly string[] LootOwnershipModes = { "My Kills Only", "Fellowship Kills", "All Corpses" }; @@ -93,11 +93,27 @@ internal static class SettingsPanel public bool EnableRaycasting { get; set; } public bool UseArcs { get; set; } public float BowArcVelocity { get; set; } = 25f; + public float MissileArcClearance { get; set; } = 0.5f; + // Vendoring (RynthAi AutoVendor; defaults match LegacyUiSettings) + public bool AutoVendorEnabled { get; set; } + public bool AutoVendorEnableBuying { get; set; } = true; + public bool AutoVendorEnableSelling { get; set; } = true; + public bool AutoVendorTestMode { get; set; } = true; + public bool AutoVendorThink { get; set; } + public bool AutoVendorShowMerchantInfo { get; set; } = true; + public bool AutoVendorOnlyFromMainPack { get; set; } + public int AutoVendorTries { get; set; } = 4; + public int AutoVendorTriesTime { get; set; } = 5000; + public bool LosDebugLog { get; set; } public float CrossbowArcVelocity { get; set; } = 40f; public float AtlatlArcVelocity { get; set; } = 22f; public float MagicArcVelocity { get; set; } = 25f; public int BlacklistAttempts { get; set; } = 3; public int BlacklistTimeoutSec { get; set; } = 30; + // Not shown in this panel, but carried so a save doesn't send them missing: + // RynthAi applied the missing value as 0 on every panel click (2026-09-27). + public int BlacklistCastSettleMs { get; set; } = 1500; + public int MonsterDisengageRange { get; set; } public int TargetNoProgressTimeoutSec { get; set; } public int GiveQueueIntervalMs { get; set; } = 150; // Recharge @@ -155,6 +171,7 @@ internal static class SettingsPanel public float NavDeadZone { get; set; } = 4f; public float NavSweepMult { get; set; } = 2.5f; public float NavLookaheadYards { get; set; } = 4f; + public float NavShortcutYards { get; set; } = 1f; public float NavTurnRateDegPerSec { get; set; } = 270f; public float NavTier1TurnSpeed { get; set; } = 3f; public float PostPortalDelaySec { get; set; } = 4f; @@ -168,6 +185,7 @@ internal static class SettingsPanel public bool EnableBuffing { get; set; } = true; public bool RebuffWhenIdle { get; set; } public int RebuffSecondsRemaining { get; set; } = 300; + public int RebuffTopOffSecondsRemaining { get; set; } = 1200; public int BuffMinSkillLevelTier1 { get; set; } = 35; public int BuffMinSkillLevelTier2 { get; set; } = 85; public int BuffMinSkillLevelTier3 { get; set; } = 135; @@ -480,6 +498,7 @@ internal static class SettingsPanel case 8: BuildBuffingTab(state, panel, picker); break; case 9: BuildCraftingTab(state, panel, picker); break; case 10: BuildLootingTab(state, panel, picker); break; + case 11: BuildVendoringTab(state, panel, picker); break; } } @@ -558,14 +577,20 @@ internal static class SettingsPanel p.Children.Add(SectionHeader("Missile Arc Velocities (m/s)")); p.Children.Add(BoolRow("Use Arcs for Missile LoS", state.Data.UseArcs, v => { state.Data.UseArcs = v; Push(state); state.Rebuild?.Invoke(); }, - "When off, all missile LoS checks are linear (eye-to-eye).")); + "A missile target must pass both the straight line and the real arrow arc, ceilings included (dungeons too).\nWhen off, all missile LoS checks are linear (eye-to-eye).")); if (state.Data.UseArcs) { p.Children.Add(FloatRow("Bow", state.Data.BowArcVelocity, 10f, 60f, 0.5f, v => { state.Data.BowArcVelocity = v; Push(state); }, "Bow projectile speed (m/s). Lower = higher arc.")); p.Children.Add(FloatRow("Crossbow", state.Data.CrossbowArcVelocity, 10f, 80f, 0.5f, v => { state.Data.CrossbowArcVelocity = v; Push(state); })); p.Children.Add(FloatRow("Atlatl", state.Data.AtlatlArcVelocity, 10f, 60f, 0.5f, v => { state.Data.AtlatlArcVelocity = v; Push(state); })); p.Children.Add(FloatRow("Magic Arc", state.Data.MagicArcVelocity, 10f, 60f, 0.5f, v => { state.Data.MagicArcVelocity = v; Push(state); })); + p.Children.Add(FloatRow("Arc Clearance (m)", state.Data.MissileArcClearance, 0f, 3f, 0.1f, + v => { state.Data.MissileArcClearance = MathF.Max(0f, v); Push(state); }, + "Extra headroom the arc must have at mid-flight. Raise it if arrows still hit ceilings; lower it if reachable mobs get skipped.")); } + p.Children.Add(BoolRow("LoS Debug Log", state.Data.LosDebugLog, + v => { state.Data.LosDebugLog = v; Push(state); }, + "Log each blocked missile target and why (arc peak, where it hits) to the RynthCore log. /ra lostest bow tests the selected mob.")); p.Children.Add(Spacer()); p.Children.Add(SectionHeader("Monster Blacklist")); @@ -772,6 +797,9 @@ internal static class SettingsPanel p.Children.Add(FloatRow("Lookahead (yd)", state.Data.NavLookaheadYards, 0f, 30f, 0.5f, v => { state.Data.NavLookaheadYards = MathF.Max(0f, v); Push(state); }, "Within this distance of a waypoint, blend the aim point toward the next one to cut corners smoothly. 0 = off.")); + p.Children.Add(FloatRow("Shortcut Tolerance (yd)", state.Data.NavShortcutYards, 0f, 10f, 0.5f, + v => { state.Data.NavShortcutYards = MathF.Max(0f, v); Push(state); }, + "On reaching a waypoint, skip ahead only past points that all lie within this distance of the straight line to the new target. 0 = visit every waypoint.")); p.Children.Add(FloatRow("Turn Rate (deg/s)", state.Data.NavTurnRateDegPerSec, 30f, 720f, 15f, v => { state.Data.NavTurnRateDegPerSec = v; Push(state); }, "Legacy / Mode 0 heading-servo max turn speed. Ignored by Tier 1 and Tier 2.")); @@ -804,6 +832,9 @@ internal static class SettingsPanel p.Children.Add(IntRow("Rebuff With (seconds left)", state.Data.RebuffSecondsRemaining, 30, 1800, 30, v => { state.Data.RebuffSecondsRemaining = v; Push(state); }, "Recast a self buff when its remaining duration drops below this value.\nDefault 300 (5 minutes). Lower values rebuff more eagerly.")); + p.Children.Add(IntRow("Also Refresh Under (seconds left)", state.Data.RebuffTopOffSecondsRemaining, 30, 3600, 60, + v => { state.Data.RebuffTopOffSecondsRemaining = v; Push(state); }, + "When a buff is due, also recast every other buff with less than this much time left,\nso they land together. Buffs with more time are left alone. Default 1200 (20 minutes).\nAt or below 'Rebuff With', only the expiring buff is recast.")); p.Children.Add(Spacer()); p.Children.Add(SectionHeader("Buff Difficulty (Min Buffed Skill)")); @@ -859,6 +890,43 @@ internal static class SettingsPanel } } + private static void BuildVendoringTab(PanelState state, StackPanel p, PickerState picker) + { + p.Children.Add(SectionHeader("AutoVendor")); + p.Children.Add(BoolRow("Enabled", state.Data.AutoVendorEnabled, + v => { state.Data.AutoVendorEnabled = v; Push(state); }, + "Buy and sell by a loot profile when a vendor opens (and allow /ub autovendor).\nProfile: .utl, else default.utl, in the AutoVendor folder.")); + p.Children.Add(BoolRow("Test Mode (only print what it would do)", state.Data.AutoVendorTestMode, + v => { state.Data.AutoVendorTestMode = v; Push(state); }, + "Lists what would be bought and sold without trading. Leave this on until the lists look right.")); + p.Children.Add(BoolRow("Buy", state.Data.AutoVendorEnableBuying, + v => { state.Data.AutoVendorEnableBuying = v; Push(state); })); + p.Children.Add(BoolRow("Sell", state.Data.AutoVendorEnableSelling, + v => { state.Data.AutoVendorEnableSelling = v; Push(state); })); + p.Children.Add(BoolRow("Only Sell From Main Pack", state.Data.AutoVendorOnlyFromMainPack, + v => { state.Data.AutoVendorOnlyFromMainPack = v; Push(state); })); + p.Children.Add(BoolRow("Show Merchant Info", state.Data.AutoVendorShowMerchantInfo, + v => { state.Data.AutoVendorShowMerchantInfo = v; Push(state); }, + "Print the vendor's buy/sell rates and max value when it opens.")); + p.Children.Add(BoolRow("Think When Finished", state.Data.AutoVendorThink, + v => { state.Data.AutoVendorThink = v; Push(state); }, + "Send 'AutoVendor finished: ' (and failures) as a /tell to yourself, for metas.")); + + p.Children.Add(Spacer()); + p.Children.Add(SectionHeader("/ub vendor open")); + p.Children.Add(IntRow("Tries", state.Data.AutoVendorTries, 1, 20, 1, + v => { state.Data.AutoVendorTries = v; Push(state); })); + p.Children.Add(IntRow("Time Between Tries (ms)", state.Data.AutoVendorTriesTime, 500, 30000, 250, + v => { state.Data.AutoVendorTriesTime = v; Push(state); })); + + p.Children.Add(Spacer()); + p.Children.Add(new TextBlock + { + Text = "Never sold: equipped, attuned, bonded, retained, tinkered, imbued, inscribed, rare, zero value, packs, or anything a Keep rule could match.", + Foreground = ColMute, FontSize = 10, TextWrapping = Avalonia.Media.TextWrapping.Wrap, Margin = new Thickness(0, 2, 0, 0), + }); + } + private static void BuildLootingTab(PanelState state, StackPanel p, PickerState picker) { p.Children.Add(BoolRow("Enable Looting", state.Data.EnableLooting, diff --git a/src/RynthCore.PluginCore/RynthPluginBase.cs b/src/RynthCore.PluginCore/RynthPluginBase.cs index bfab157..1c3aa95 100644 --- a/src/RynthCore.PluginCore/RynthPluginBase.cs +++ b/src/RynthCore.PluginCore/RynthPluginBase.cs @@ -6,7 +6,7 @@ namespace RynthCore.PluginCore; public abstract class RynthPluginBase { - public virtual uint MinimumApiVersion => RynthCoreHost.CurrentApiVersion; + public virtual uint MinimumApiVersion => RynthCoreHost.BaselineApiVersion; protected RynthCoreApiNative Api { get; private set; } protected RynthCoreHost Host { get; private set; } diff --git a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs index baeaf81..46231a5 100644 --- a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs +++ b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs @@ -119,4 +119,10 @@ public struct RynthCoreApiNative public IntPtr SendPluginCommandFn; // v64: forward (action,value) to a named plugin's command export public IntPtr GetObjectDataIdPropertyFn; // v65: read a PWD DataID property (Icon=8 → _iconID) for inventory icons public IntPtr GetPluginExportJsonFn; // v66: broker any RynthPluginGet*Json export on a named plugin + // v67: vendor trading (see VendorTypes.cs / RynthCoreHost vendor section) + public IntPtr GetVendorInfoFn; // int GetVendorInfo(VendorInfoNative*) + public IntPtr GetVendorItemsFn; // int GetVendorItems(VendorItemNative*, int maxCount) + public IntPtr VendorBuyFn; // uint VendorBuy(uint vendorId, VendorTradeEntryNative*, int count) + public IntPtr VendorSellFn; // uint VendorSell(uint vendorId, uint* itemIds, int count) + public IntPtr GetVendorTradeStatusFn; // int GetVendorTradeStatus(VendorTradeStatusNative*) } diff --git a/src/RynthCore.PluginSdk/RynthCoreHost.cs b/src/RynthCore.PluginSdk/RynthCoreHost.cs index 3fbff4a..485ed4d 100644 --- a/src/RynthCore.PluginSdk/RynthCoreHost.cs +++ b/src/RynthCore.PluginSdk/RynthCoreHost.cs @@ -1,11 +1,23 @@ using System; +using System.Collections.Generic; using System.Runtime.InteropServices; namespace RynthCore.PluginSdk; public readonly unsafe struct RynthCoreHost { - public const uint CurrentApiVersion = 66; + public const uint CurrentApiVersion = 67; + + /// + /// The oldest engine API a plugin built on this SDK loads on by default + /// (). Players get + /// plugin updates automatically but engine updates only when they click, so defaulting + /// to made every rebuilt plugin refuse the engine most + /// players still run. Calls newer than this are version-checked by their wrappers + /// (e.g. HasVendorTrade); a plugin that truly needs a newer engine overrides + /// MinimumApiVersion. Raise this only with a release that forces the engine update. + /// + public const uint BaselineApiVersion = 66; private readonly RynthCoreApiNative _api; @@ -1446,4 +1458,206 @@ public readonly unsafe struct RynthCoreHost Marshal.FreeHGlobal(valuePtr); } } + + // ─── Vendor trading (API v67) ────────────────────────────────────────── + // Decal's WorldFilter.OpenVendor + Actions.VendorBuyAll/VendorSellAll shape as + // stateless calls (VendorCart adds the Add/Clear list shape on top). Reads come + // from a snapshot the engine takes on AC's main thread when the vendor list + // arrives. Buy/sell are checked, queued, re-checked on AC's main thread (funds, + // pack slots, burden, ownership) and sent through the client's own + // gmVendorUI::SendShopEvent. One transaction is in flight at a time: wait for + // GetVendorTradeStatus to finish before sending the next batch. + + /// True when the engine exposes vendor trading (API v67+). + public bool HasVendorTrade => _api.Version >= 67 + && _api.GetVendorInfoFn != IntPtr.Zero && _api.GetVendorItemsFn != IntPtr.Zero + && _api.VendorBuyFn != IntPtr.Zero && _api.VendorSellFn != IntPtr.Zero + && _api.GetVendorTradeStatusFn != IntPtr.Zero; + + /// The vendor that is open right now, or false if none (or pre-v67 engine). + public bool TryGetVendorInfo(out VendorInfo info) + { + info = null!; + if (_api.Version < 67 || _api.GetVendorInfoFn == IntPtr.Zero) + return false; + + VendorInfoNative raw; + if (((delegate* unmanaged[Cdecl])_api.GetVendorInfoFn)(&raw) == 0) + return false; + + info = new VendorInfo + { + VendorId = raw.VendorId, + Name = ReadAnsi(raw.Name, 64), + Generation = raw.Generation, + ShopMode = raw.ShopMode, + ItemTypes = raw.ItemTypes, + MinValue = raw.MinValue, + MaxValue = raw.MaxValue, + DealsMagic = raw.DealsMagic != 0, + BuyRate = raw.BuyRate, + SellRate = raw.SellRate, + AltCurrencyWcid = raw.AltCurrencyWcid, + AltCurrencyName = ReadAnsi(raw.AltCurrencyName, 64), + AltCurrencyServerCount = raw.AltCurrencyServerCount, + AltCurrencyHave = raw.AltCurrencyHave, + PlayerCoins = raw.PlayerCoins, + ItemCount = raw.ItemCount, + TradingAvailable = (raw.Flags & 1u) != 0, + TradeInFlight = (raw.Flags & 2u) != 0, + }; + return true; + } + + /// The open vendor's items; empty if no vendor is open (or pre-v67 engine). + public VendorItem[] GetVendorItems() + { + if (_api.Version < 67 || _api.GetVendorItemsFn == IntPtr.Zero) + return Array.Empty(); + + var fn = (delegate* unmanaged[Cdecl])_api.GetVendorItemsFn; + for (int attempt = 0; attempt < 3; attempt++) + { + int total = fn(null, 0); + if (total <= 0) + return Array.Empty(); + + int capacity = total + 8; // headroom in case the list is re-sent between calls + IntPtr buf = Marshal.AllocHGlobal(capacity * sizeof(VendorItemNative)); + try + { + VendorItemNative* items = (VendorItemNative*)buf; + int now = fn(items, capacity); + if (now < 0) + return Array.Empty(); + if (now > capacity) + continue; // grew past the headroom; size again + + var result = new VendorItem[now]; + for (int i = 0; i < now; i++) + { + VendorItemNative* it = items + i; + result[i] = new VendorItem + { + ObjectId = it->ObjectId, + Wcid = it->Wcid, + Name = ReadAnsi(it->Name, 64), + ItemType = it->ItemType, + IconId = it->IconId, + Amount = it->Amount, + StackSize = it->StackSize, + MaxStackSize = it->MaxStackSize, + Value = it->Value, + UnitValue = it->UnitValue, + UnitPrice = it->UnitPrice, + Burden = it->Burden, + Unlimited = (it->Flags & 1u) != 0, + Stackable = (it->Flags & 2u) != 0, + NeedsContainerSlot = (it->Flags & 4u) != 0, + }; + } + return result; + } + finally + { + Marshal.FreeHGlobal(buf); + } + } + return Array.Empty(); + } + + /// + /// Buy from the open vendor (Decal VendorBuyAll). vendorId 0 = whichever vendor is + /// open; pass the id you read to make sure it's still that vendor. Returns the request + /// id, or 0 if refused (reason in ). + /// + public uint VendorBuy(uint vendorId, IReadOnlyList items) + { + if (_api.Version < 67 || _api.VendorBuyFn == IntPtr.Zero || items == null || items.Count == 0) + return 0; + + int n = items.Count; + IntPtr buf = Marshal.AllocHGlobal(n * sizeof(VendorTradeEntryNative)); + try + { + VendorTradeEntryNative* p = (VendorTradeEntryNative*)buf; + for (int i = 0; i < n; i++) + p[i] = items[i]; + return ((delegate* unmanaged[Cdecl])_api.VendorBuyFn)(vendorId, p, n); + } + finally + { + Marshal.FreeHGlobal(buf); + } + } + + /// Buy of one vendor item. + public uint VendorBuy(uint objectId, int amount, uint vendorId = 0) => + VendorBuy(vendorId, new[] { new VendorTradeEntryNative(objectId, amount) }); + + /// + /// Sell your own items (whole stacks) to the open vendor (Decal VendorSellAll). + /// Items must be in your packs, not equipped, and of a type the vendor buys. + /// Returns the request id, or 0 if refused. + /// + public uint VendorSell(uint vendorId, IReadOnlyList itemIds) + { + if (_api.Version < 67 || _api.VendorSellFn == IntPtr.Zero || itemIds == null || itemIds.Count == 0) + return 0; + + int n = itemIds.Count; + IntPtr buf = Marshal.AllocHGlobal(n * sizeof(uint)); + try + { + uint* p = (uint*)buf; + for (int i = 0; i < n; i++) + p[i] = itemIds[i]; + return ((delegate* unmanaged[Cdecl])_api.VendorSellFn)(vendorId, p, n); + } + finally + { + Marshal.FreeHGlobal(buf); + } + } + + /// Sell one of your items. + public uint VendorSell(uint itemId) => VendorSell(0, new[] { itemId }); + + /// State of the most recent buy/sell request (check RequestId is yours). + public bool TryGetVendorTradeStatus(out VendorTradeStatus status) + { + status = null!; + if (_api.Version < 67 || _api.GetVendorTradeStatusFn == IntPtr.Zero) + return false; + + VendorTradeStatusNative raw; + if (((delegate* unmanaged[Cdecl])_api.GetVendorTradeStatusFn)(&raw) == 0) + return false; + + status = new VendorTradeStatus + { + RequestId = raw.RequestId, + State = (VendorTradeState)raw.State, + Result = (VendorTradeResult)raw.Result, + IsBuy = raw.IsBuy != 0, + VendorId = raw.VendorId, + EntryCount = raw.EntryCount, + Estimate = raw.Estimate, + Message = ReadAnsi(raw.Message, 128), + }; + return true; + } + + private static string ReadAnsi(byte* p, int capacity) + { + int len = 0; + while (len < capacity && p[len] != 0) + len++; + if (len == 0) + return string.Empty; + var chars = new char[len]; + for (int i = 0; i < len; i++) + chars[i] = (char)p[i]; // Latin-1, the client's single-byte names + return new string(chars); + } } diff --git a/src/RynthCore.PluginSdk/VendorTypes.cs b/src/RynthCore.PluginSdk/VendorTypes.cs new file mode 100644 index 0000000..f0638d4 --- /dev/null +++ b/src/RynthCore.PluginSdk/VendorTypes.cs @@ -0,0 +1,238 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; + +namespace RynthCore.PluginSdk; + +// ─── Vendor trading ABI structs (engine API v67) ──────────────────────────── +// Must mirror RynthCore.Engine/Plugins/PluginContract.cs exactly (Pack=4, same +// field order, same fixed-buffer sizes). Plugins normally use the managed +// VendorInfo / VendorItem / VendorTradeStatus types below instead. + +[StructLayout(LayoutKind.Sequential, Pack = 4)] +public unsafe struct VendorInfoNative +{ + public uint VendorId; + public uint Generation; + public int ShopMode; + public uint ItemTypes; + public int MinValue; + public int MaxValue; + public int DealsMagic; + public float BuyRate; + public float SellRate; + public uint AltCurrencyWcid; + public int AltCurrencyServerCount; + public int AltCurrencyHave; + public int PlayerCoins; + public int ItemCount; + public uint Flags; + public uint Reserved0; + public fixed byte Name[64]; + public fixed byte AltCurrencyName[64]; +} + +[StructLayout(LayoutKind.Sequential, Pack = 4)] +public unsafe struct VendorItemNative +{ + public uint ObjectId; + public uint Wcid; + public uint ItemType; + public uint IconId; + public int Amount; + public int StackSize; + public int MaxStackSize; + public int Value; + public int UnitValue; + public int UnitPrice; + public int Burden; + public uint Flags; + public uint Reserved0; + public uint Reserved1; + public fixed byte Name[64]; +} + +[StructLayout(LayoutKind.Sequential, Pack = 4)] +public struct VendorTradeEntryNative +{ + public uint ObjectId; + public int Amount; + + public VendorTradeEntryNative(uint objectId, int amount) + { + ObjectId = objectId; + Amount = amount; + } +} + +[StructLayout(LayoutKind.Sequential, Pack = 4)] +public unsafe struct VendorTradeStatusNative +{ + public uint RequestId; + public int State; + public int Result; + public int IsBuy; + public uint VendorId; + public int EntryCount; + public int Estimate; + public uint Reserved0; + public fixed byte Message[128]; +} + +// ─── Managed views ────────────────────────────────────────────────────────── + +/// The vendor that is open right now (Decal: WorldFilter.OpenVendor). +public sealed class VendorInfo +{ + public uint VendorId { get; init; } + public string Name { get; init; } = string.Empty; + /// Bumps each time the server (re)sends the vendor list: on open and after every accepted buy/sell. + public uint Generation { get; init; } + public int ShopMode { get; init; } + /// ITEM_TYPE mask of what the vendor will buy from you. + public uint ItemTypes { get; init; } + public int MinValue { get; init; } + public int MaxValue { get; init; } + public bool DealsMagic { get; init; } + /// The vendor pays value x BuyRate when you sell (promissory notes at 1.0). + public float BuyRate { get; init; } + /// The vendor charges value x SellRate when you buy (promissory notes at 1.15). + public float SellRate { get; init; } + /// WCID of the currency this vendor takes; 0 = pyreals. + public uint AltCurrencyWcid { get; init; } + public string AltCurrencyName { get; init; } = string.Empty; + /// Alt currency count as the server put it in the vendor list (-1 if none). + public int AltCurrencyServerCount { get; init; } + /// Alt currency the engine counted in your packs (-1 = not counted yet / not an alt-currency vendor). + public int AltCurrencyHave { get; init; } + /// Your pyreals (CoinValue), refreshed on AC's main thread; -1 unknown. + public int PlayerCoins { get; init; } + public int ItemCount { get; init; } + /// The engine can trade with this vendor (client functions found, layout checked). + public bool TradingAvailable { get; init; } + /// A buy/sell is queued or waiting for the server. + public bool TradeInFlight { get; init; } + public bool UsesAltCurrency => AltCurrencyWcid != 0; + public bool Buys(uint itemType) => (ItemTypes & itemType) != 0; +} + +/// One item on the open vendor's list. +public sealed class VendorItem +{ + public uint ObjectId { get; init; } + public uint Wcid { get; init; } + public string Name { get; init; } = string.Empty; + public uint ItemType { get; init; } + public uint IconId { get; init; } + /// How many the vendor has; -1 = unlimited. + public int Amount { get; init; } + public int StackSize { get; init; } + public int MaxStackSize { get; init; } + /// Value of the listed stack. + public int Value { get; init; } + public int UnitValue { get; init; } + /// What one unit costs you at this vendor (server rounding). + public int UnitPrice { get; init; } + public int Burden { get; init; } + public bool Unlimited { get; init; } + public bool Stackable { get; init; } + /// Packs and foci need a container slot. + public bool NeedsContainerSlot { get; init; } +} + +/// Outcome of the most recent VendorBuy / VendorSell request. +public sealed class VendorTradeStatus +{ + public uint RequestId { get; init; } + public VendorTradeState State { get; init; } + public VendorTradeResult Result { get; init; } + public bool IsBuy { get; init; } + public uint VendorId { get; init; } + public int EntryCount { get; init; } + /// Buy: estimated cost (pyreals or alt currency). Sell: estimated payout in pyreals. + public int Estimate { get; init; } + public string Message { get; init; } = string.Empty; + /// Finished one way or the other (done or refused). + public bool IsFinished => State is VendorTradeState.Done or VendorTradeState.Refused; + public bool Succeeded => State == VendorTradeState.Done && Result == VendorTradeResult.Accepted; +} + +public enum VendorTradeState +{ + None = 0, + /// Passed the snapshot checks; waiting for AC's main thread. + Queued = 1, + /// Sent through the client; waiting for the server. + Sent = 2, + /// The server answered (see Result). + Done = 3, + /// Never sent: no vendor, unknown item, not enough money/space/burden, ... (see Message). + Refused = 4, +} + +public enum VendorTradeResult +{ + None = 0, + /// The server re-sent the vendor list: the trade went through. + Accepted = 1, + /// The server answered without re-sending the list: it refused (busy, funds, space...). + AnsweredNoRefresh = 2, + /// No answer within 10 s. + TimedOut = 3, +} + +/// +/// Decal-shaped buy/sell lists (Actions.VendorAddBuyList / VendorBuyAll / VendorClearBuyList +/// and the Sell equivalents) on top of the stateless engine calls. Plugin-local: each +/// plugin keeps its own cart. BuyAll/SellAll send the whole list as ONE transaction +/// (max 100 lines) and return the request id (0 = refused, see GetVendorTradeStatus); +/// the list is cleared only when the request is accepted for sending. +/// Wait for the status to finish (and the vendor Generation to bump) before the next batch. +/// +public sealed class VendorCart +{ + private readonly List _buy = new(); + private readonly List _sell = new(); + + public IReadOnlyList BuyList => _buy; + public IReadOnlyList SellList => _sell; + + /// Add (or top up) a vendor item on the buy list. + public void AddBuy(uint objectId, int amount) + { + if (objectId == 0 || amount <= 0) return; + for (int i = 0; i < _buy.Count; i++) + { + if (_buy[i].ObjectId == objectId) + { + _buy[i] = new VendorTradeEntryNative(objectId, _buy[i].Amount + amount); + return; + } + } + _buy.Add(new VendorTradeEntryNative(objectId, amount)); + } + + /// Add one of your own items (whole stack) to the sell list. + public void AddSell(uint objectId) + { + if (objectId != 0 && !_sell.Contains(objectId)) + _sell.Add(objectId); + } + + public void ClearBuy() => _buy.Clear(); + public void ClearSell() => _sell.Clear(); + + public uint BuyAll(RynthCoreHost host, uint vendorId = 0) + { + uint id = host.VendorBuy(vendorId, _buy); + if (id != 0) _buy.Clear(); + return id; + } + + public uint SellAll(RynthCoreHost host, uint vendorId = 0) + { + uint id = host.VendorSell(vendorId, _sell); + if (id != 0) _sell.Clear(); + return id; + } +} diff --git a/src/RynthCore.StatusAgent/AgentConfig.cs b/src/RynthCore.StatusAgent/AgentConfig.cs index faeb184..97b4b9d 100644 --- a/src/RynthCore.StatusAgent/AgentConfig.cs +++ b/src/RynthCore.StatusAgent/AgentConfig.cs @@ -58,9 +58,9 @@ internal sealed class AgentConfig /// netsh urlacl or running elevated). Must end in '/'. [JsonPropertyName("ServePrefix")] public string ServePrefix { get; set; } = "http://127.0.0.1:8740/"; - /// Optional shared secret. When set, GET /status requires - /// Authorization: Bearer <token> or ?token=. Empty = open - /// (fine for a 127.0.0.1 / private-tailnet bind). + /// Shared secret, required when is on: every route but + /// /healthz needs Authorization: Bearer <token> or ?token=. Empty = + /// the server stays off, on any bind (it can stream the screens and click in them). [JsonPropertyName("ServeToken")] public string ServeToken { get; set; } = ""; /// When true, also write the latest rollup to diff --git a/src/RynthCore.StatusAgent/LocalStatusServer.cs b/src/RynthCore.StatusAgent/LocalStatusServer.cs index c3dfeb5..746db68 100644 --- a/src/RynthCore.StatusAgent/LocalStatusServer.cs +++ b/src/RynthCore.StatusAgent/LocalStatusServer.cs @@ -1,6 +1,7 @@ using System.Collections.Concurrent; using System.Net; using System.Net.WebSockets; +using System.Security.Cryptography; using System.Text; using System.Text.Json; @@ -74,6 +75,14 @@ internal sealed class LocalStatusServer : IDisposable public bool TryStart(out string error) { + // Never serve without a token, loopback included: every route but /healthz is behind it. + if (_token == null) + { + error = "no ServeToken set"; + Running = false; + return false; + } + try { _listener.Start(); @@ -741,13 +750,17 @@ internal sealed class LocalStatusServer : IDisposable { string? header = req.Headers["Authorization"]; if (header != null && header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase) && - string.Equals(header.Substring("Bearer ".Length).Trim(), _token, StringComparison.Ordinal)) + TokenMatches(header.Substring("Bearer ".Length).Trim())) return true; string? q = req.QueryString["token"]; - return q != null && string.Equals(q, _token, StringComparison.Ordinal); + return q != null && TokenMatches(q); } + private bool TokenMatches(string candidate) + => _token != null && CryptographicOperations.FixedTimeEquals( + Encoding.UTF8.GetBytes(candidate), Encoding.UTF8.GetBytes(_token)); + private static void Write(HttpListenerResponse res, int status, string contentType, byte[] body) { try diff --git a/src/RynthCore.StatusAgent/Program.cs b/src/RynthCore.StatusAgent/Program.cs index d4427ca..3d43b25 100644 --- a/src/RynthCore.StatusAgent/Program.cs +++ b/src/RynthCore.StatusAgent/Program.cs @@ -57,7 +57,15 @@ else LocalStatusServer? server = null; WebRtcVideoService? video = null; // HD WebRTC video mode (opt-in); disposed in finally IconService? icons = null; // item-icon decoder (GET /icon); disposed in finally -if (cfg.ServeHttp) +if (cfg.ServeHttp && string.IsNullOrWhiteSpace(cfg.ServeToken)) +{ + // Same rule as DrakBot's remote: no token, no server, loopback included. The server can show + // the game screens, click in them and close clients. + AgentLog.Warn("ServeHttp is on but ServeToken is empty, so the status server stays off."); + AgentLog.Warn($"Set \"ServeToken\" in {configPath} and restart the agent. Use the same token as your"); + AgentLog.Warn("DrakBot remote and one DrakRemote entry shows both."); +} +else if (cfg.ServeHttp) { string? commandDir = cfg.EnableRemoteControl ? Path.Combine(cfg.StatusDirectory, "commands") : null; VideoSocketService? videoSocket = null; diff --git a/src/RynthCore.StatusAgent/RynthCore.StatusAgent.csproj b/src/RynthCore.StatusAgent/RynthCore.StatusAgent.csproj index 5497232..31cf6d9 100644 --- a/src/RynthCore.StatusAgent/RynthCore.StatusAgent.csproj +++ b/src/RynthCore.StatusAgent/RynthCore.StatusAgent.csproj @@ -25,8 +25,9 @@ - - + + diff --git a/tools/check_offthread_mutators.py b/tools/check_offthread_mutators.py index feab4c0..25d1136 100644 --- a/tools/check_offthread_mutators.py +++ b/tools/check_offthread_mutators.py @@ -56,6 +56,7 @@ MUTATOR_DELEGATES = { "_eventStackableMerge", "_addTextToScroll", "_setAutoRun", "_turnToHeading", "_stopCompletely", "_setMotion", "_changeCombatMode", + "_sendShopEvent", # VendorTrade: gmVendorUI::SendShopEvent (vendor buy/sell + busy count) } GATE = "MainThreadGuard.IsOnMainThread" ENQUEUE = "AcMainThreadQueue.Enqueue"