diff --git a/Changelog/2026-10-06-release-2026.10.5.14-heartbeat-always-logged.md b/Changelog/2026-10-06-release-2026.10.5.14-heartbeat-always-logged.md new file mode 100644 index 0000000..01080f3 --- /dev/null +++ b/Changelog/2026-10-06-release-2026.10.5.14-heartbeat-always-logged.md @@ -0,0 +1,45 @@ +# RynthCore 2026.10.5.14 — engine heartbeat is always logged + +**Date:** 2026-10-06 +**Branch:** `fix/heartbeat-always-logged` (from `main` 143eaa9); deployed build is the +same fix cherry-picked onto `fix/restore-sk-features` (the 2026.10.5.13 line) +**Previous release:** 2026.10.5.13 (895a63a) +**Component:** `RynthCore.Engine` only (no plugin API change) + +## Problem + +The launcher killed healthy, in-world clients and relaunched them every few minutes +(Silentkelpie and Silentstorm, 2026-10-06 14:46 to 15:13; launcher log lines +`WEDGE: PID … killed - engine heartbeat silent for >120s while process alive`). + +- The launcher's wedge watchdog treats `RynthCore..log` not being written for + 120 s as a dead engine and kills the process. +- The engine's once-a-second heartbeat line (`hb #N … fps= … login= …`) was written + through `RynthLog.Info`, which writes at the **General category's** level. +- With `LoggingLevel = Info` and `General = Trace` (launcher logging settings), the + heartbeat was emitted at Trace and filtered out by the global Info threshold, so the + log went quiet once a character was in-world and the watchdog fired. +- The launcher copies its own `LoggingLevel` into `engine.json` on every launch, so a + hand edit of `engine.json` only lasted until the next relaunch. +- Knock-on effect: relaunches landed while the killed character was still logged in on + the server, and the new client was booted to the end-of-session screen + (`LogOffCharacter(immediate=1)` from `gmEpilogueUI`) about 35 s after launch. + +## Fix + +- New `RynthLog.Heartbeat(string)`: writes unconditionally (every `LoggingLevel`, + including Off), tagged `[INF]`, like `RynthLog.Error` does for errors. +- `HeartbeatLogger` writes the `hb #` line through `RynthLog.Heartbeat`. +- No change to the line format, so every launcher's `WedgeHbRegex` still parses it. + +## Notes + +- The startup warning about categories above the global level stays; it still applies + to every other line. +- Workaround for older engines: set the launcher's global logging level to Trace, or + turn off auto-restart of wedged clients. + +## Files + +- `src/RynthCore.Engine/RynthLog.cs` — `Heartbeat` method. +- `src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs` — heartbeat uses it. diff --git a/Changelog/2026-10-06-upstream-snapshot-comparison.md b/Changelog/2026-10-06-upstream-snapshot-comparison.md new file mode 100644 index 0000000..c7696a1 --- /dev/null +++ b/Changelog/2026-10-06-upstream-snapshot-comparison.md @@ -0,0 +1,117 @@ +# Upstream snapshot comparison: rynth/RynthCore 2026.10.6.1 vs GitHub main + +Date: 2026-10-06 +Report only. Nothing has been merged or pushed. + +| Side | Ref | Commit | +|---|---|---| +| Upstream (aelrynth `rynth/RynthCore`) | `aelrynth/main` | `abf9146` Snapshot for release 2026.10.6.1 (internal 1cbe514) | +| GitHub (`BlankenshipG/RynthCore`) | `origin/main` | `143eaa9` feat(ui): nav route editing, progression, charms and chat presets | +| Common base | merge-base | `913a2a0` release 2026.10.5.20 | + +Upstream snapshot not on GitHub: `abf9146`, 93 files, +10168 / -597. + +GitHub commits not upstream. All three are in open rynth/RynthCore PR #2; PR #1 is superseded. +- `9709a39` install-aware paths, logging levels, item drag bridge +- `4be686e` plugin overlay windows and create-time identity seeds +- `143eaa9` nav route editing, progression, charms and chat presets + +## Policy for the next merge + +- **Keep everything we sent up:** + - logging levels and desktop log; + - item drag bridge; + - plugin overlay windows; + - progression, charms and chat presets; + - nav route editing; + - install-aware paths. +- **Bring down the new upstream items flagged below**, merge them in and test them. + +## FLAG: new upstream items to bring down, merge and test + +### New files (38): missing on GitHub +- **Flight recorder** (network capture ring): + - `Net/FlightCapture.cs`, `Net/FlightFormat.cs`, `Net/FlightRecorder.cs`, `Net/FlightRing.cs` + - `tools/FlightRecorderTests` +- **Video patch:** + - `D3D9/VideoPatch.cs`, `D3D9/VideoPatchPolicy.cs`, `ImGui/VideoPatchBanner.cs` + - `tools/VideoPatchTests` +- **Meta editor:** + - `ImGui/Panels/MetaFace.Editor.cs` + - `UI/Data/MetaEditing.cs`, `UI/Data/MetaLocation.cs`, `UI/Data/MetaRuleDto.cs` + - `tools/MetaEditTests` +- **Item count HUD:** + - `ImGui/Panels/ItemCountFace.cs` + - `UI/Data/ItemHudModel.cs`, `UI/Data/ItemHudStore.cs` + - `tools/ItemHudTests` +- **Mini remote:** `ImGui/Panels/MiniRemoteFace.cs`. +- **Engine settings:** + - `Plugins/EngineSettingsFile.cs`, `Plugins/PluginPathDedupe.cs` + - `tools/EngineSettingsTests` +- **Chat filters:** + - `UI/Data/ChatFilterPresets.cs`, `UI/Data/ChatRuleMatching.cs`, `UI/Data/ChatSettingsDto.cs` + - `tools/ChatFilterTests` +- **Panels:** `UI/PanelDestroyFallback.cs`, `tools/PanelWindowTests`. +- **Install paths:** `src/Shared/RynthInstallPaths.cs`, `tools/InstallPathsTests`. See the + overlaps below. + +### Upstream edits to files GitHub never changed (31): merge cleanly +- **Launcher:** `RynthUpdater.NavData`, `UsageStats`. +- **Compatibility:** + - `AcActionTrace`, `AcMainThreadQueue`, `BusyCountHooks`, `ClientActionGates` + - `GameTickHooks`, `HeartbeatLogger`, `InventoryModel`, `LoginLifecycleHooks` + - `RawPacketHooks`, `RynthCoreChatCommands`, `SmartBoxHooks` +- **D3D9:** `AcUiPassHook`, `Nav3DRenderInjector`. +- **ImGui:** + - `ImGuiBar`, `ImGuiPopOuts`, `MonsterHud` + - `MetaFace`, `MetaFace.Schedule`, `P1Faces`, `RynthNavFace` + - `UiDropTargets`, `RynthNavData` +- **Tools:** test project files, `PluginManifestTests/Program.cs`, `tools/pe_pattern.py`. + +### Edited on both sides (24): needs a hand merge (14 conflict in a trial merge) + +Conflicting: +- `RynthCore.App.Avalonia/LauncherDiag.cs`, `MainWindow.axaml.cs`, `RynthCore.App.Avalonia.csproj` +- `Engine/ImGui/EngineFrameController.cs` +- `Engine/ImGui/Panels/ChatFiltersFace.cs`, `Engine/ImGui/Panels/InventoryFace.cs` +- `Engine/LogPaths.cs`, `Engine/RynthCore.Engine.csproj` +- `Engine/UI/Data/ChatData.cs`, `Engine/UI/Data/MetaData.cs` +- `Injector/Program.cs`, `Loader/EntryPoint.cs` +- `StatusAgent/AgentConfig.cs`, `StatusAgent/RynthCore.StatusAgent.csproj` + +Auto-merged, but changed on both sides, so review them: +- `D3D9/EndSceneHook.cs`, `EngineLifecycle.cs`, `EntryPoint.cs` +- `ImGui/Win32Backend.cs` +- `Plugins/EngineSettings.cs`, `Plugins/PluginManager.cs` +- `UI/Data/SettingsData.cs`, `UI/LayeredWindow.cs` +- `Injector.csproj`, `Loader.csproj` + +## Overlaps to resolve when merging + +1. **Install paths: two copies of `RynthInstallPaths`.** GitHub has + `src/RynthCore.App/RynthInstallPaths.cs`; upstream has `src/Shared/RynthInstallPaths.cs`, + linked into several projects. The two differ by about 190 lines. Keep one and update the + links (App, Engine, Injector, Loader, StatusAgent, tests). +2. **Chat presets:** our `UI/Panels/RynthChatPresets.cs` against upstream's + `ChatFilterPresets` / `ChatRuleMatching` / `ChatSettingsDto`, which touch the same + `ChatData.cs` and `ChatFiltersFace.cs`. Review both side by side; don't keep two preset + systems. +3. **Panel destroy:** our posted-destroy fix (PR #2) against upstream's + `PanelDestroyFallback.cs`, both in `LayeredWindow.cs`. +4. **Logging:** our `LogSettings.cs` and logging levels against upstream's `LogPaths.cs` and + `EngineSettingsFile.cs` changes. + +## Suggested test pass after merging + +- New upstream tools: `ChatFilterTests`, `EngineSettingsTests`, `FlightRecorderTests`, + `InstallPathsTests`, `ItemHudTests`, `MetaEditTests`, `PanelWindowTests`, `VideoPatchTests`. +- Existing tools: `PluginManifestTests`, `StatusAgentTests`, `LauncherUpdateTests`, + `NavDataUpdateTests`, `UsageStatsTests`. +- NativeAOT Engine publish. +- In game: + - overlay windows and item drag; + - chat presets and filters; + - meta editor; + - item count HUD; + - video patch banner; + - logging level settings in the launcher. diff --git a/Changelog/2026-10-07-merge-main-into-QOL-items.md b/Changelog/2026-10-07-merge-main-into-QOL-items.md new file mode 100644 index 0000000..8e07510 --- /dev/null +++ b/Changelog/2026-10-07-merge-main-into-QOL-items.md @@ -0,0 +1,66 @@ +# QOL-items: main merged in, PR #10 conflicts resolved (plugin API 80) + +**Date:** 2026-10-07 +**Branch:** `QOL-items` ([PR #10](https://github.com/BlankenshipG/RynthCore/pull/10), into `main`) +**Merged:** `origin/main` 784ddf1 (engine 2026.10.5.16) into `QOL-items` f2bd3b2 +**Plugin API:** 80 (previous: 77 on `QOL-items`, 79 on `main`) + +## Why + +PR #10 could not merge: `main` took the 2026-10-05 evening upstream snapshot (913a2a0) and the +three commits that sent the SK features upstream (9709a39, 4be686e, 143eaa9), and both lines +edited the same 15 files. This merge brings `main` into `QOL-items` so the PR merges cleanly. +Nothing on `main` is rewritten. + +## Plugin API: GetMergeStackResult moves to v80 + +Both lines used API v77 for different table fields: +- `QOL-items`: v77 = `GetMergeStackResultFn`. +- `main` (upstream): v77 = `GetScreenModeFn`, `GetUiHookFlagsFn`; v78 = + `SetServerMessageInterestFn`; v79 = `GetTrainingInfoFn`, `RaiseFn`, `TrainSkillFn`. + +`main`'s numbering is the one upstream ships, so it stays. `GetMergeStackResultFn` is appended +after `TrainSkillFn` as v80, in both the engine's `RynthCoreAPI` and the SDK's +`RynthCoreApiNative`. `PluginContractVersion.Current`, `RynthCoreSdkApiVersion` (SDK targets) and +`RynthCoreHost.HasGetMergeStackResult` (now `Version >= 80`) follow. + +A plugin built against the old `QOL-items` SDK would read the wrong slot for +`GetMergeStackResult`. No RynthSuite plugin calls it, and RynthAi (RynthSuite `main` 272e9f5) +builds against the merged SDK, but rebuild plugins against this SDK before running them on this +engine. + +## Conflicts resolved + +`main`'s side already contains the `QOL-items` change plus upstream's additions in most files, so +those hunks take `main`: +- `ImGui/EngineFrameController.cs`: line endings only; `main` adds the Client::Cleanup guard. +- `ImGui/Panels/NavFace.cs`: header lists the route editor. +- `Plugins/EngineSettings.cs`: `DisabledUiHooks` read before `LoggingLevel`. +- `Plugins/LoadedPlugin.cs`: v77/v78 export pointers, `Manifest`, `NotStartedReason`. +- `RynthLog.cs`: `Heartbeat` (always written), the Move / UseDone traces, `Write` wrapper. +- `UI/Data/ChatData.cs`, `UI/Data/NavData.cs`: route editor fields and requests. +- `UI/Data/SettingsData.cs`, `ImGui/Panels/SettingsFace.cs`, `UI/Panels/SettingsPanel.cs`: the + TraceCategories row next to Button / Text / Status; the Diagnostics tab icon. +- `StatusAgent/AgentConfig.cs`: `CellDatPath` and `NavAtlasPath`. + +Merged by hand: +- `Plugins/PluginContract.cs`: header lists both `RynthPluginRenderOverlay` and + `RynthPluginOnServerMessage`; table as above; `PluginContractVersion` lives only in + `PluginContractVersion.cs`. +- `Plugins/PluginManager.cs`: `main` gathers the plugin list first and loads it afterwards, so + `QOL-items`' duplicate guard (same file name or same resolved path) now records each candidate + as it is accepted instead of after loading. +- `ImGui/Panels/SettingsFace.cs`: git kept two identical copies of `TextRow`, `StatusRow` and + `ButtonRow` (both lines added them); one copy removed. +- `tools/PluginManifestTests`: the table's tail is now the v79 slots then `GetMergeStackResultFn`. + +## Verification + +- `RynthCore.sln` (Release, x86): builds, no errors. +- PluginManifestTests 156/156, LauncherUpdateTests 134/134, TrainingCostTests 70/70, + ReloadDeferralTests 19/19, NetMessageTests 203/203. +- StatusAgentTests does not compile, the same as on `main` (its project compiles + `AgentConfig.cs` without `RynthInstallPaths`); not caused by this merge. +- RynthSuite `main` against this SDK: RynthAi builds; host tests 431 passed, 5 known failures, + 1 unrelated failure (map bake reads the real dats), the same as before. +- No release was built or deployed from this merge. diff --git a/Changelog/2026-10-07-release-2026.10.5.15-loot-add-t11-checkbox.md b/Changelog/2026-10-07-release-2026.10.5.15-loot-add-t11-checkbox.md new file mode 100644 index 0000000..1dcf913 --- /dev/null +++ b/Changelog/2026-10-07-release-2026.10.5.15-loot-add-t11-checkbox.md @@ -0,0 +1,32 @@ +# RynthCore 2026.10.5.15 — "Include T11 attributes" in the Add to loot profile popup + +**Date:** 2026-10-07 +**Branch:** `feat/loot-add-t11-checkbox` (from `fix/restore-sk-features` 5926a46) +**Previous release:** 2026.10.5.14 +**Pairs with:** RynthAi 0.5.21-legacy-ui (RynthSuite `feat/loot-add-t11-attributes`) + +## What's new + +The "Add to loot profile" popup has a new **Include T11 attributes** checkbox under Match. The +popup opens from the Inventory panel's right-click menu, or from "Add selected item" in the Loot +Editor. + +- When checked, RynthAi adds the item's T11 conditions to the rule: tier, weapon grade, + damage %, every modifier, slot special and Cast on Strike. Each must be at least as good as + the clicked item's. +- It works with every match mode, and the preview updates as soon as it is toggled. +- The tooltip lists what is added, and why Can Wield and Zone Locked are not: they depend on + the character and on where the item was assessed. +- "(not a T11 item)" shows next to the checkbox when the item isn't T11 gear. + +## Compatibility + +- `LootEditItemRequestDto.IncludeT11` is new; an older RynthAi ignores it. +- `LootEditItemDraftDto.IncludeT11` and `IsT11` are new; an older RynthAi never sends them, so + they read false. With an older RynthAi the checkbox has no effect, and "(not a T11 item)" + shows for every item. + +## Files + +- `src/RynthCore.Engine/ImGui/Panels/LootAddDialog.cs` +- `src/RynthCore.Engine/UI/Data/LootEditData.cs` diff --git a/Changelog/2026-10-07-release-2026.10.5.16-main-integration.md b/Changelog/2026-10-07-release-2026.10.5.16-main-integration.md new file mode 100644 index 0000000..0448368 --- /dev/null +++ b/Changelog/2026-10-07-release-2026.10.5.16-main-integration.md @@ -0,0 +1,51 @@ +# RynthCore engine 2026.10.5.16 — 2026-10-06/07 work brought onto main + +**Date:** 2026-10-07 +**Branch:** `integrate/main-2026-10-07` (from `main` 143eaa9), fast-forwarded into `main` +**Previous release:** 2026.10.5.15 (the T11 checkbox build on `fix/restore-sk-features`) + +## Why + +The night of 2026-10-06 left engine changes on three local branches, none of them on `main`. +This release puts the ones that apply to `main` on it in one line. It pairs with RynthAi +0.5.22-legacy-ui on RynthSuite `main`. + +## What's in it + +| Commit on main | From | Change | +|----------------|------|--------| +| b467573 | `fix/heartbeat-always-logged` 2c67875 | The heartbeat line is written at every logging level (2026.10.5.14) | +| b361152 | `SK-local` f2bd3b2 | Attribute raiser on the Skills face's Progression tab; text and status rows for Server Features | +| ead4828 | `feat/loot-add-t11-checkbox` ef0e6cf | "Include T11 attributes" checkbox in the Add to loot profile popup (2026.10.5.15) | +| (docs) | untracked in the main checkout | The upstream snapshot comparison report (`2026-10-06-upstream-snapshot-comparison.md`) | + +## Left out on purpose + +ab18df2 on `SK-local`, "log CoreCLR-hosted engine AVs immediately in the native crash logger", +patches the crash logger rewrite in `native/SehTrampoline/SehTrampoline.c` from a7cdbee. `main` +never got a7cdbee: its trampoline is the older 406-line version, against 674 lines on `SK-local`, +so the cherry-pick conflicted in four places. a7cdbee also changes create-time object seeding, +which overlaps `main`'s own identity seeds from 4be686e. Bringing the crash logger over is its own +port, and it only takes effect after `scripts/Build-SehTrampoline.ps1` rebuilds the native DLL. +ab18df2 stays on `SK-local` until then. + +5926a46 is the same heartbeat fix as 2c67875 on the `fix/restore-sk-features` line, so it was not +picked twice. + +## Conflicts resolved + +`main` added a TraceCategories settings row in the same places f2bd3b2 adds its Text and Status +rows. Both are kept: +- `UI/Data/SettingsData.cs`: `SettingKind` has `TraceCategories, Text, Status`, and + `TraceCategoryLevels` stays. +- `ImGui/Panels/SettingsFace.cs`: all three switch cases, then `TraceCategoriesRow` / + `SaveCategories`, then `TextRow` / `StatusRow`. +- `UI/Panels/SettingsPanel.cs` (the Avalonia face): all three cases. + +## Build + +- `scripts/Publish-EngineCoreClr.ps1 -EngineOnly -MsBuildArgs '-p:Version=2026.10.5.16'` to + `out/staged-2026.10.5.16`. It built with no errors, and every warning was already on `main`. +- `RynthCore.Engine.dll` FileVersion 2026.10.5.16. +- Not deployed. The live engine (2026.10.5.15) is built from the `fix/restore-sk-features` line, + not from `main`. diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md index 0c72283..64e5ea8 100644 --- a/THIRD-PARTY-NOTICES.md +++ b/THIRD-PARTY-NOTICES.md @@ -32,3 +32,34 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ``` + +## Chorizite DatReaderWriter (format reference for the dat readers) + +- What: the layout of Asheron's Call .dat files (header, block chains, the directory B-tree) and of the Texture and Palette files, used as the reference when RynthCore's own dat reader and icon decoder were written (2026-10-05). The code is RynthCore's own (MIT); this notice is kept because the library was the format reference. +- Where: `src/RynthCore.StatusAgent/Dat/DatDatabase.cs` and `Dat/IconDecoder.cs`, and `src/RynthCore.Engine/UI/ScriptWindows/AcIconDecoder.cs`. The notice is also in `DatDatabase.cs`'s header. The DXT decoder (`Dat/DxtUtil.cs`) was written from the public S3TC block-compression format. +- Source: https://github.com/Chorizite/DatReaderWriter (ACClientLib) +- Licence: MIT, reproduced below. + +``` +MIT License + +Copyright 2024 ACClientLib + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` diff --git a/docs/STATUS_AGENT.md b/docs/STATUS_AGENT.md index 8e6adfe..cb7f552 100644 --- a/docs/STATUS_AGENT.md +++ b/docs/STATUS_AGENT.md @@ -205,6 +205,24 @@ A simple phone view: green if every client is `healthy`, red if any is --- +## Raising from the phone (`raiseXp`) + +With the RynthRemote plugin 0.4 on an engine with plugin API v79, DrakRemote's Skills tab can spend +unassigned XP (and skill credits) the way the character window's "+" does: + +- The plugin's character sheet (`GET /character`, passed through as the plugin wrote it) carries + `ranks`, `xpSpent`, `cost1`, `cost10`, `affordable` (and `trainCredits` on skills) per row and a + `raise` block (`available`, `reason`, `busy`, `last` = the last result). Its status file says + `"raiseXp": true` when the client can. +- The agent sends `capabilities.raiseXp` (remote control on, character sheets, and a client that + can) and `clients[].raiseXp`. +- `POST /command` `{"pid":N,"action":"raise","value":"{\"kind\":\"attribute|vital|skill|train\",\"id\":..,\"count\":1..100,\"cost\":N,\"nonce\":..}"}` + needs the token like every command, and is accepted only for a pid the last cycle read whose + plugin reports `raiseXp` (404 unknown client, 409 not available). The value is checked and + rewritten in that fixed shape (`RemoteParity.CheckRaise`); `cost` is the cost the user confirmed + and is required. The plugin refuses commands over 30 s old and repeated nonces; the engine works + the cost out again from fresh numbers and refuses when it differs. + ## Removing the feature entirely Everything is tagged `[status-export]` in the engine — `grep -r "[status-export]" diff --git a/installer/PluginManifest.ps1 b/installer/PluginManifest.ps1 new file mode 100644 index 0000000..f183ef5 --- /dev/null +++ b/installer/PluginManifest.ps1 @@ -0,0 +1,86 @@ +#Requires -Version 7 +<# +.SYNOPSIS + Reads RynthCore plugin manifests and the engine's plugin API version, for Publish-Update.ps1. + +.DESCRIPTION + Dot-source it: . (Join-Path $PSScriptRoot "PluginManifest.ps1") + + Get-RynthPluginManifest the manifest embedded in a plugin DLL (RCDATA resource + RYNTH_PLUGIN_MANIFEST, written by the SDK's build targets) + as an object, or $null when the DLL has none. The DLL is + mapped as a data file only (LOAD_LIBRARY_AS_DATAFILE): none + of its code runs. + Get-RynthEngineApi PluginContractVersion.Current from the engine's source. + + Read-only; safe to run on its own (tools\PluginManifestTests\Test-PluginManifestPs.ps1 does). +#> + +if (-not ('RynthCore.Publish.PeResource' -as [type])) { + Add-Type -Language CSharp -TypeDefinition @' +using System; +using System.Runtime.InteropServices; + +namespace RynthCore.Publish +{ + public static class PeResource + { + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern IntPtr LoadLibraryExW(string path, IntPtr file, uint flags); + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool FreeLibrary(IntPtr module); + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern IntPtr FindResourceW(IntPtr module, string name, IntPtr type); + [DllImport("kernel32.dll", SetLastError = true)] + private static extern IntPtr LoadResource(IntPtr module, IntPtr res); + [DllImport("kernel32.dll", SetLastError = true)] + private static extern IntPtr LockResource(IntPtr data); + [DllImport("kernel32.dll", SetLastError = true)] + private static extern uint SizeofResource(IntPtr module, IntPtr res); + + private const uint LOAD_LIBRARY_AS_DATAFILE = 0x2; + private const uint LOAD_LIBRARY_AS_IMAGE_RESOURCE = 0x20; + + /// RCDATA resource of a PE file, or null if it has none. + public static byte[] ReadRcData(string path, string name) + { + IntPtr module = LoadLibraryExW(path, IntPtr.Zero, LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_IMAGE_RESOURCE); + if (module == IntPtr.Zero) + throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error(), "can't map " + path); + try + { + IntPtr res = FindResourceW(module, name, (IntPtr)10); // RT_RCDATA + if (res == IntPtr.Zero) return null; + uint size = SizeofResource(module, res); + IntPtr data = LockResource(LoadResource(module, res)); + if (data == IntPtr.Zero) return null; + byte[] bytes = new byte[size]; + Marshal.Copy(data, bytes, 0, (int)size); + return bytes; + } + finally + { + FreeLibrary(module); + } + } + } +} +'@ +} + +function Get-RynthPluginManifest([Parameter(Mandatory)][string]$Path) { + $bytes = [RynthCore.Publish.PeResource]::ReadRcData((Resolve-Path $Path).Path, "RYNTH_PLUGIN_MANIFEST") + if ($null -eq $bytes) { return $null } + $json = [Text.Encoding]::UTF8.GetString($bytes).TrimStart([char]0xFEFF).TrimEnd([char]0) + $m = $json | ConvertFrom-Json + if (-not $m.name) { throw "$Path has a plugin manifest without a name" } + if ($null -ne $m.minEngineApi -and -not ("$($m.minEngineApi)" -match '^\d+$')) { throw "$Path has a plugin manifest with a bad minEngineApi '$($m.minEngineApi)'" } + return $m +} + +function Get-RynthEngineApi([Parameter(Mandatory)][string]$RepoRoot) { + $file = Join-Path $RepoRoot "src\RynthCore.Engine\Plugins\PluginContractVersion.cs" + $m = [regex]::Match((Get-Content $file -Raw), 'const\s+uint\s+Current\s*=\s*(\d+)') + if (-not $m.Success) { throw "No PluginContractVersion.Current in $file" } + return [int]$m.Groups[1].Value +} diff --git a/installer/Publish-Update.ps1 b/installer/Publish-Update.ps1 index a3f1e72..2008b62 100644 --- a/installer/Publish-Update.ps1 +++ b/installer/Publish-Update.ps1 @@ -271,6 +271,13 @@ $pluginDescriptions = @{ RynthOracle = "Quests, character, titles and leaderboards." RynthInventory = "Search every character's items." } +# Plugin manifests (embedded in each DLL by the SDK's build targets): each plugin's minEngineApi +# goes into its feed entry, and the core entry says its engine's API ("engineApi"), so launchers +# (from plugin manifests on) don't install a plugin build the installed engine would refuse; they +# say "needs RynthCore " instead. Older launchers ignore both fields. +. (Join-Path $ScriptDir "PluginManifest.ps1") +$engineApi = Get-RynthEngineApi $RepoRoot +Write-Host " engine plugin API: $engineApi" $plugins = foreach ($dll in Get-ChildItem "$rel\plugins\*.dll" | Sort-Object Name) { $pluginName = $dll.BaseName -replace '^RynthCore\.Plugin\.', '' $entry = [ordered]@{ @@ -282,6 +289,17 @@ $plugins = foreach ($dll in Get-ChildItem "$rel\plugins\*.dll" | Sort-Object Nam } if ($pluginDescriptions[$pluginName]) { $entry.description = $pluginDescriptions[$pluginName] } else { Write-Warning "No description for $pluginName - the launcher shows its own (or none). Add one to `$pluginDescriptions." } + $pm = Get-RynthPluginManifest $dll.FullName + if ($pm) { + if ($pm.name -ne $pluginName) { throw "$($dll.Name): its manifest says '$($pm.name)', the feed would say '$pluginName'." } + if ($pm.version -and $pm.version -ne $Version) { throw "$($dll.Name): its manifest is version $($pm.version), not $Version (stale build?)." } + $min = [int]$pm.minEngineApi + if ($min -gt $engineApi) { throw "$($dll.Name) needs engine API $min but this release's engine is $engineApi - it would never load." } + if ($min -gt 0) { $entry.minEngineApi = $min } + Write-Host " $pluginName $($pm.version): engine API $min+" + } else { + Write-Warning "$($dll.Name) has no plugin manifest - launchers install it on any engine." + } $entry } $manifest = [ordered]@{ @@ -299,6 +317,8 @@ $manifest = [ordered]@{ url = "$BaseUrl/releases/$release/RynthCore-Setup.exe" size = $setup.Length sha256 = Sha256 $setup.FullName + # The plugin API of the engine in this installer (see the plugins' minEngineApi above). + engineApi = $engineApi } plugins = @($plugins) } diff --git a/src/RynthCore.App.Avalonia/MainWindow.axaml.cs b/src/RynthCore.App.Avalonia/MainWindow.axaml.cs index 9ed873d..cecd02d 100644 --- a/src/RynthCore.App.Avalonia/MainWindow.axaml.cs +++ b/src/RynthCore.App.Avalonia/MainWindow.axaml.cs @@ -463,15 +463,34 @@ internal partial class MainWindow : Window Foreground = Brush.Parse("#6F7F8A"), }); - var install = new Button + Control install; + if (!a.CanInstall) { - Content = "Install", - VerticalAlignment = VerticalAlignment.Center, - Margin = new Thickness(12, 0, 0, 0), - IsEnabled = !_updateBusy, - }; - ToolTip.SetTip(install, $"Download {a.Entry.Name} (checked against the signed update feed) into {Path.GetDirectoryName(a.Path)} and add it to your plugins."); - install.Click += async (_, _) => await InstallAvailablePluginAsync(a); + // Its manifest needs a newer engine than this RynthCore: say so instead of offering it. + install = new TextBlock + { + Text = a.Blocker, + VerticalAlignment = VerticalAlignment.Center, + Margin = new Thickness(12, 0, 0, 0), + Foreground = Brush.Parse("#F2C14E"), + TextWrapping = TextWrapping.Wrap, + MaxWidth = 200, + }; + ToolTip.SetTip(install, $"This {a.Entry.Name} build needs a newer RynthCore than the one installed. Update RynthCore, then install it."); + } + else + { + var button = new Button + { + Content = "Install", + VerticalAlignment = VerticalAlignment.Center, + Margin = new Thickness(12, 0, 0, 0), + IsEnabled = !_updateBusy, + }; + ToolTip.SetTip(button, $"Download {a.Entry.Name} (checked against the signed update feed) into {Path.GetDirectoryName(a.Path)} and add it to your plugins."); + button.Click += async (_, _) => await InstallAvailablePluginAsync(a); + install = button; + } var row = new Grid { ColumnDefinitions = new ColumnDefinitions("*, Auto") }; Grid.SetColumn(stack, 0); @@ -2357,6 +2376,8 @@ internal partial class MainWindow : Window lines.Add($"Updated this session: {string.Join(", ", _pluginsUpdatedThisSession)}. Loads the next time AC starts."); var local = c?.Plugins.Where(p => p.State == RynthUpdater.PluginState.LocalBuild).Select(p => p.Entry.Name).Distinct().ToList(); if (local is { Count: > 0 }) lines.Add($"Left alone (newer local builds): {string.Join(", ", local)}."); + var waiting = c?.PluginsWaitingForCore.GroupBy(p => p.Entry.Name).Select(g => $"{g.Key} ({g.First().Blocker})").ToList(); + if (waiting is { Count: > 0 }) lines.Add($"Waiting for a RynthCore update: {string.Join(", ", waiting)}."); UpdateStatusText.Text = string.Join("\n", lines); PluginsTabProgressBar.IsVisible = card.ShowProgress; PluginsTabProgressBar.IsIndeterminate = card.ShowProgress && card.ProgressPercent == null; diff --git a/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj b/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj index e4e75f5..32276bc 100644 --- a/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj +++ b/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj @@ -61,6 +61,8 @@ + + diff --git a/src/RynthCore.App.Avalonia/RynthUpdater.Available.cs b/src/RynthCore.App.Avalonia/RynthUpdater.Available.cs index 57478fa..5109422 100644 --- a/src/RynthCore.App.Avalonia/RynthUpdater.Available.cs +++ b/src/RynthCore.App.Avalonia/RynthUpdater.Available.cs @@ -37,7 +37,15 @@ internal sealed partial class RynthUpdater private static readonly Regex SafeFolderName = new(@"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$", RegexOptions.CultureInvariant); /// A feed plugin the player can install: where it would go, what it is, and whether it's new. - public sealed record AvailablePlugin(PluginEntry Entry, string Path, string Description, string Version, bool IsNew); + public sealed record AvailablePlugin(PluginEntry Entry, string Path, string Description, string Version, bool IsNew) + { + /// + /// Empty when it can be installed; otherwise shown instead of the Install button: the feed's + /// build needs a newer engine than the one installed ("needs RynthCore 2026.10.6.1"). + /// + public string Blocker { get; init; } = ""; + public bool CanInstall => Blocker.Length == 0; + } /// What did: Downloaded is false when a good copy was already there. public sealed record PluginInstall(PluginEntry Entry, string Path, string Description, bool Downloaded); @@ -119,7 +127,7 @@ internal sealed partial class RynthUpdater if (listed.Contains(e.File) || skip.Contains(e.File)) continue; if (TargetPath(e, suite) is not { } target) continue; bool isNew = seen.TryGetValue(e.Name, out DateTime first) && now - first < NewBadgeFor; - result.Add(new AvailablePlugin(e, target, DescribePlugin(e), manifest.Version, isNew)); + result.Add(new AvailablePlugin(e, target, DescribePlugin(e), manifest.Version, isNew) { Blocker = EngineBlocker(e, manifest) }); } // New ones first, then by name. return result.OrderByDescending(a => a.IsNew).ThenBy(a => a.Entry.Name, StringComparer.OrdinalIgnoreCase).ToList(); @@ -145,6 +153,9 @@ internal sealed partial class RynthUpdater throw new InvalidOperationException($"{e.Name} is already in your plugin list"); string target = TargetPath(e, SuiteDir(check.Manifest, paths)) ?? throw new InvalidDataException($"bad plugin name '{e.Name}' in the feed"); + // A build the installed engine would refuse (its manifest's minEngineApi) isn't installed. + if (EngineBlocker(e, check.Manifest) is { Length: > 0 } blocker) + throw new InvalidOperationException($"{e.Name} {blocker}"); if (File.Exists(target)) { @@ -181,6 +192,17 @@ internal sealed partial class RynthUpdater return OneLine(d.GetString(), MaxDescriptionLength); } + /// + /// An optional engine API number ("minEngineApi" on a plugin, "engineApi" on the core; written + /// since plugin manifests). Missing or unreadable: 0, no limit, as with older feeds. + /// + private static uint ReadApi(JsonElement o, string name) + { + if (!o.TryGetProperty(name, out JsonElement v)) return 0; + if (v.ValueKind == JsonValueKind.Number && v.TryGetUInt32(out uint n)) return n; + return 0; + } + /// The manifest's optional "changes": up to 20 lines. private static IReadOnlyList ReadChanges(JsonElement r) { diff --git a/src/RynthCore.App.Avalonia/RynthUpdater.cs b/src/RynthCore.App.Avalonia/RynthUpdater.cs index 7a4d0c4..e13899b 100644 --- a/src/RynthCore.App.Avalonia/RynthUpdater.cs +++ b/src/RynthCore.App.Avalonia/RynthUpdater.cs @@ -42,9 +42,14 @@ internal sealed partial class RynthUpdater /// One plugin in the feed. is the optional one-line "description" /// (written since 2026.10.5); older feeds have none and the launcher's own table fills in /// (). Launchers before it ignore the field. + /// is the optional "minEngineApi", from the plugin's embedded + /// manifest (Publish-Update.ps1 copies it): the oldest engine plugin API the build runs on. + /// 0 (older feeds, plugins without a manifest) means no limit. See . /// - public sealed record PluginEntry(string Name, string File, string Url, long Size, string Sha256, string Description = ""); - public sealed record InstallerEntry(int Release, string Version, string Url, long Size, string Sha256); + public sealed record PluginEntry(string Name, string File, string Url, long Size, string Sha256, string Description = "", + uint MinEngineApi = 0); + /// The core release. : the optional "engineApi", its engine's plugin API (0 = not said). + public sealed record InstallerEntry(int Release, string Version, string Url, long Size, string Sha256, uint EngineApi = 0); public sealed record Manifest(int Release, string Version, DateTime PublishedUtc, string Notes, InstallerEntry Core, IReadOnlyList Plugins, NavDataEntry? NavData = null) { @@ -56,8 +61,17 @@ internal sealed partial class RynthUpdater } /// One installed copy of a plugin the feed knows. - public sealed record PluginStatus(PluginEntry Entry, string Path, PluginState State); - public enum PluginState { UpToDate, NeedsUpdate, LocalBuild } + public sealed record PluginStatus(PluginEntry Entry, string Path, PluginState State) + { + /// For : "needs RynthCore 2026.10.6.1". + public string Blocker { get; init; } = ""; + } + /// + /// NeedsNewerEngine: the feed's build needs a newer engine plugin API than the RynthCore installed + /// here, so the installed copy is kept until RynthCore itself is updated (the engine would refuse + /// the new build and the player would lose the plugin meanwhile). + /// + public enum PluginState { UpToDate, NeedsUpdate, LocalBuild, NeedsNewerEngine } /// A plugin split out of one the player has, to be installed beside it (see ). public sealed record CompanionInstall(PluginEntry Entry, string Path, string Reason); @@ -66,6 +80,8 @@ internal sealed partial class RynthUpdater { public bool CoreUpdateAvailable => Manifest.Core.Release > InstalledCoreRelease; public IEnumerable PluginsToUpdate => Plugins.Where(p => p.State == PluginState.NeedsUpdate); + /// Plugin updates held back until RynthCore is updated (). + public IEnumerable PluginsWaitingForCore => Plugins.Where(p => p.State == PluginState.NeedsNewerEngine); /// New plugins that came out of an installed one; installed with the plugin updates. public IReadOnlyList Companions { get; init; } = Array.Empty(); /// Feed plugins not in the plugin list, for the player to install or not (see ). @@ -113,6 +129,26 @@ internal sealed partial class RynthUpdater _appDir = appDir ?? AppContext.BaseDirectory; } + /// + /// The plugin API of the engine installed with this launcher. The installer ships the launcher and + /// the engine together (a core update replaces both), so it is the engine's own constant, + /// compiled in from PluginContractVersion.cs. Tests set it. + /// + internal uint InstalledEngineApi { get; set; } = RynthCore.Engine.Plugins.PluginContractVersion.Current; + + /// + /// Empty when the installed engine runs ; otherwise what the player needs, shown + /// in place of the Install button: "needs RynthCore 2026.10.6.1" when the feed's own core release + /// brings a new enough engine, else "needs a newer RynthCore (API 77)". + /// + public string EngineBlocker(PluginEntry e, Manifest manifest) + { + if (e.MinEngineApi == 0 || e.MinEngineApi <= InstalledEngineApi) return ""; + InstallerEntry core = manifest.Core; + bool coreBringsIt = core.EngineApi >= e.MinEngineApi && core.Release > InstalledCoreRelease && core.Version.Length > 0; + return coreBringsIt ? $"needs RynthCore {core.Version}" : $"needs a newer RynthCore (API {e.MinEngineApi})"; + } + /// False until the signing keys exist: with no trusted key nothing can verify. public bool IsConfigured => _trustedKeys.Count > 0; @@ -158,13 +194,16 @@ internal sealed partial class RynthUpdater continue; // not a plugin this feed ships (a private or third-party one): never touched PluginState state; + string blocker = ""; if (string.Equals(Sha256File(path), entry.Sha256, StringComparison.OrdinalIgnoreCase)) state = PluginState.UpToDate; else if (File.GetLastWriteTimeUtc(path) > manifest.PublishedUtc.AddMinutes(1)) state = PluginState.LocalBuild; // newer than the release: someone's own build, leave it + else if ((blocker = EngineBlocker(entry, manifest)).Length > 0) + state = PluginState.NeedsNewerEngine; // keep the copy that runs until RynthCore catches up else state = PluginState.NeedsUpdate; - statuses.Add(new PluginStatus(entry, path, state)); + statuses.Add(new PluginStatus(entry, path, state) { Blocker = blocker }); } List companions = FindCompanions(manifest, pluginPaths); @@ -191,6 +230,7 @@ internal sealed partial class RynthUpdater string.Equals(Path.GetFileName(p), parentFile, StringComparison.OrdinalIgnoreCase) && File.Exists(p)); PluginEntry? child = manifest.Plugins.FirstOrDefault(e => string.Equals(e.Name, childName, StringComparison.OrdinalIgnoreCase)); if (parent == null || child == null) continue; + if (EngineBlocker(child, manifest).Length > 0) continue; // not yet: offered once RynthCore is updated if (paths.Any(p => string.Equals(Path.GetFileName(p), child.File, StringComparison.OrdinalIgnoreCase))) { MarkCompanionOffered(childName); // already there: nothing to do, ever @@ -336,7 +376,8 @@ internal sealed partial class RynthUpdater JsonElement c = r.GetProperty("core"); var core = new InstallerEntry(c.GetProperty("release").GetInt32(), c.GetProperty("version").GetString() ?? "", - CheckUrl(c.GetProperty("url").GetString()), c.GetProperty("size").GetInt64(), c.GetProperty("sha256").GetString() ?? ""); + CheckUrl(c.GetProperty("url").GetString()), c.GetProperty("size").GetInt64(), c.GetProperty("sha256").GetString() ?? "", + ReadApi(c, "engineApi")); var plugins = new List(); foreach (JsonElement p in r.GetProperty("plugins").EnumerateArray()) @@ -346,7 +387,7 @@ internal sealed partial class RynthUpdater throw new InvalidDataException($"bad plugin file name '{file}'"); plugins.Add(new PluginEntry(p.GetProperty("name").GetString() ?? file, file, CheckUrl(p.GetProperty("url").GetString()), p.GetProperty("size").GetInt64(), p.GetProperty("sha256").GetString() ?? "", - ReadDescription(p))); + ReadDescription(p), ReadApi(p, "minEngineApi"))); } return new Manifest(r.GetProperty("release").GetInt32(), r.GetProperty("version").GetString() ?? "", diff --git a/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs b/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs index 0b445d6..6df75e7 100644 --- a/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs +++ b/src/RynthCore.Engine/Compatibility/AcMainThreadQueue.cs @@ -419,6 +419,9 @@ internal static class AcMainThreadQueue // writes its own lines, so the chat window keeps the order lines arrived in. try { ChatCallbackHooks.OnMainThreadDrain(disarmed: false); } catch { } + // Keep the off-thread combat-mode cache true to the client (stale after a hot reload). + CombatModeHooks.MainThreadRefresh(); + // Deep-audit finding #22 (2026-06-18): these three queues are // documented as deliberately separate from the gesture-gated action // ring below specifically so appraisals/chat "can never get diff --git a/src/RynthCore.Engine/Compatibility/CharacterManagementHooks.cs b/src/RynthCore.Engine/Compatibility/CharacterManagementHooks.cs index 0ecb841..02ad215 100644 --- a/src/RynthCore.Engine/Compatibility/CharacterManagementHooks.cs +++ b/src/RynthCore.Engine/Compatibility/CharacterManagementHooks.cs @@ -144,6 +144,8 @@ internal static class CharacterManagementHooks { Volatile.Write(ref _publishedMode, mode); Volatile.Write(ref _modePublished, 1); + // Seeds UiFlowHooks' mode; drives its screen events when the UseNewMode hook isn't live. + UiFlowHooks.OnModePolled(mode); } else { diff --git a/src/RynthCore.Engine/Compatibility/ClientActionHooks.cs b/src/RynthCore.Engine/Compatibility/ClientActionHooks.cs index e8d2546..faee794 100644 --- a/src/RynthCore.Engine/Compatibility/ClientActionHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ClientActionHooks.cs @@ -106,19 +106,30 @@ internal static class ClientActionHooks return CombatActionHooks.CastSpell(targetId, spellId); } + // Movement calls below are the plugin API's only way in (PluginManager's callbacks), so each + // one is traced here with the calling plugin: RynthLog.Move, behind RynthLog.MoveTraceEnabled. + private static string MoveArg(System.FormattableString s) => + RynthLog.MoveTraceEnabled ? System.FormattableString.Invariant(s) : ""; + public static bool DoMovement(uint motion, float speed = 1.0f, int holdKey = MovementActionHooks.HoldKeyRun) { - return MovementActionHooks.DoMovement(motion, speed, holdKey); + bool ok = MovementActionHooks.DoMovement(motion, speed, holdKey); + RynthLog.Move("DoMovement", MoveArg($"0x{motion:X8}, {speed:0.##}, {holdKey}"), ok, a: motion, b: (uint)holdKey); + return ok; } public static bool StopMovement(uint motion, int holdKey = MovementActionHooks.HoldKeyRun) { - return MovementActionHooks.StopMovement(motion, holdKey); + bool ok = MovementActionHooks.StopMovement(motion, holdKey); + RynthLog.Move("StopMovement", MoveArg($"0x{motion:X8}, {holdKey}"), ok, a: motion, b: (uint)holdKey); + return ok; } public static bool JumpNonAutonomous(float extent) { - return MovementActionHooks.JumpNonAutonomous(extent); + bool ok = MovementActionHooks.JumpNonAutonomous(extent); + RynthLog.Move("JumpNonAutonomous", MoveArg($"{extent:0.##}"), ok); + return ok; } public static bool SetAutonomyLevel(uint level) @@ -128,37 +139,51 @@ internal static class ClientActionHooks public static bool SetAutoRun(bool enabled) { - return CommandInterpreterHooks.SetAutoRun(enabled); + bool ok = CommandInterpreterHooks.SetAutoRun(enabled); + RynthLog.Move("SetAutoRun", enabled ? "True" : "False", ok, a: enabled ? 1u : 0u); + return ok; } public static bool TapJump() { - return CommandInterpreterHooks.TapJump(); + bool ok = CommandInterpreterHooks.TapJump(); + RynthLog.Move("TapJump", "", ok); + return ok; } public static bool CommenceJump() { - return CommandInterpreterHooks.CommenceJump(); + bool ok = CommandInterpreterHooks.CommenceJump(); + RynthLog.Move("CommenceJump", "", ok); + return ok; } public static bool DoJump(bool autonomous) { - return CommandInterpreterHooks.DoJump(autonomous); + bool ok = CommandInterpreterHooks.DoJump(autonomous); + RynthLog.Move("DoJump", autonomous ? "True" : "False", ok); + return ok; } public static bool LaunchJumpWithMotion(bool shift, bool holdW, bool holdX, bool holdZ, bool holdC) { - return PlayerPhysicsHooks.LaunchJumpWithMotion(shift, holdW, holdX, holdZ, holdC); + bool ok = PlayerPhysicsHooks.LaunchJumpWithMotion(shift, holdW, holdX, holdZ, holdC); + RynthLog.Move("LaunchJumpWithMotion", MoveArg($"shift={shift}, w={holdW}, x={holdX}, z={holdZ}, c={holdC}"), ok); + return ok; } public static bool SetMotion(uint motion, bool enabled) { - return CommandInterpreterHooks.SetMotion(motion, enabled); + bool ok = CommandInterpreterHooks.SetMotion(motion, enabled); + RynthLog.Move("SetMotion", MoveArg($"0x{motion:X8}, {enabled}"), ok, a: motion, b: enabled ? 1u : 0u); + return ok; } public static bool StopCompletely() { - return CommandInterpreterHooks.StopCompletely(); + bool ok = CommandInterpreterHooks.StopCompletely(); + RynthLog.Move("StopCompletely", "", ok); + return ok; } public static bool TurnToHeading(float headingDegrees) @@ -168,11 +193,12 @@ internal static class ClientActionHooks // Off AC's main thread (plugin pump) SetPlayerHeadingDirect only parks the // heading in AcMainThreadQueue's coalesced slot and returns true; the snap // (and the no-player CommandInterpreter fallback below) run in Drain. - if (PlayerPhysicsHooks.SetPlayerHeadingDirect(headingDegrees)) - return true; - - // Fallback: command interpreter gradual turn - return CommandInterpreterHooks.TurnToHeading(headingDegrees); + bool ok = PlayerPhysicsHooks.SetPlayerHeadingDirect(headingDegrees) + // Fallback: command interpreter gradual turn + || CommandInterpreterHooks.TurnToHeading(headingDegrees); + // Successive turns from one caller collapse into one line whatever the angle (nav steers every tick). + RynthLog.Move("TurnToHeading", MoveArg($"{headingDegrees:0.0}"), ok, collapseByKind: true); + return ok; } public static bool TryGetPlayerHeading(out float headingDegrees) diff --git a/src/RynthCore.Engine/Compatibility/CombatModeHooks.cs b/src/RynthCore.Engine/Compatibility/CombatModeHooks.cs index ecd7efc..94cf993 100644 --- a/src/RynthCore.Engine/Compatibility/CombatModeHooks.cs +++ b/src/RynthCore.Engine/Compatibility/CombatModeHooks.cs @@ -301,6 +301,44 @@ internal static class CombatModeHooks PluginManager.QueueCombatModeChange(currentCombatMode, previousCombatMode); } + // Main-thread refresh of the off-thread cache (2026-10-05). After the engine hot reload at + // 13:42:55 Drakkon was in Magic (he had just cast Heal Self), but _lastObservedCombatMode + // starts at NonCombat in a new engine and only the SetCombatMode detour (a mode CHANGE) or a + // main-thread ReadCurrentCombatMode moved it. The plugin pump reads off the main thread, so + // the engine synced "combat mode 1" to the plugins at 13:43:03 and RynthAi's heal at 13:43:12 + // asked for a Magic stance the client already had (RequestCombatMode req=8 clientField=8), + // then waited out the stance settle. Drain calls this every frame; it reads the client's field + // at most every MainThreadRefreshMs and, when the cache was wrong, heals it and tells the + // plugins the way the detour does. + private static long _lastMainThreadRefreshMs; + private const long MainThreadRefreshMs = 250; + + /// AC's main thread only (AcMainThreadQueue.Drain). + internal static unsafe void MainThreadRefresh() + { + if (!IsInstalled) return; + long now = Environment.TickCount64; + if (now - _lastMainThreadRefreshMs < MainThreadRefreshMs) return; + _lastMainThreadRefreshMs = now; + try + { + IntPtr slot = (IntPtr)_combatSystemPtrAddr; + if (!ClientObjectHooks.IsReadablePointer(slot)) return; + IntPtr combatSystem = *(IntPtr*)slot; + if (combatSystem == IntPtr.Zero || !ClientObjectHooks.IsReadablePointer(combatSystem + CombatModeOffset)) return; + int raw = NormalizeCombatMode(*(int*)(combatSystem + CombatModeOffset)); + if (raw is not (CombatActionHooks.CombatModeNonCombat or CombatActionHooks.CombatModeMelee + or CombatActionHooks.CombatModeMissile or CombatActionHooks.CombatModeMagic)) + return; // not a mode (a singleton being torn down): leave the cache alone + int previous = Interlocked.Exchange(ref _lastObservedCombatMode, raw); + if (raw == previous) return; + RynthLog.Compat($"CombatModeHooks: the cached combat mode was {previous} but the client reads {raw} " + + "(no SetCombatMode seen since this engine started, e.g. after a hot reload): cache healed, plugins told."); + PluginManager.QueueCombatModeChange(raw, previous); + } + catch { } + } + private static int NormalizeCombatMode(int combatMode) { return combatMode switch diff --git a/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs b/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs index 5a37c15..ba24a13 100644 --- a/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs +++ b/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs @@ -162,7 +162,8 @@ internal static class HeartbeatLogger // every use/move/equip meanwhile); atk=1 = its attacking flag is set. Both // omitted while open, so a long run of req= in a log is the item-action lock. string gateField = ClientActionGates.HeartbeatField(); - RynthLog.Info($"hb #{tick} up={(nowMs - startMs) / 1000}s fps={fps} draw={draw} plug={pps}/s ws={wsMb}MB login={login} qdrop={dropped} rec={rec} fcl={fcl}{idleField}{uiField}{vaField}{gateField}"); + // Unfiltered on purpose: it is the launcher's liveness signal (see RynthLog.Heartbeat). + RynthLog.Heartbeat($"hb #{tick} up={(nowMs - startMs) / 1000}s fps={fps} draw={draw} plug={pps}/s ws={wsMb}MB login={login} qdrop={dropped} rec={rec} fcl={fcl}{idleField}{uiField}{vaField}{gateField}"); // Every 60 s: garbage collections and the time they paused the process. // Under the CoreCLR host the engine and managed plugins share one GC, so a diff --git a/src/RynthCore.Engine/Compatibility/PlayerProgressHooks.cs b/src/RynthCore.Engine/Compatibility/PlayerProgressHooks.cs index f12edb9..2cb6531 100644 --- a/src/RynthCore.Engine/Compatibility/PlayerProgressHooks.cs +++ b/src/RynthCore.Engine/Compatibility/PlayerProgressHooks.cs @@ -12,7 +12,8 @@ // Want / Current / RefreshSoon any thread (the panel: AC's render thread). // // Demand-driven: nothing is read unless a reader called Want in the last 2 s, -// then at most every 500 ms. Reads go into one preallocated work buffer; a new +// then at most every 500 ms (WantSlow, the plugin API's GetTrainingInfo: in the +// last 5 s, then at most every 2 s). Reads go into one preallocated work buffer; a new // snapshot object is published (and allocated) only when something changed, // so an idle open panel costs a compare every half second. // ============================================================================ @@ -173,6 +174,8 @@ internal static class PlayerProgressHooks { private const int RefreshMs = 500; private const int WantWindowMs = 2000; + private const int SlowRefreshMs = 2000; + private const int SlowWantWindowMs = 5000; // StatMod type flags (ACE EnchantmentTypeFlags) that mark a buff on a stat. internal const uint ModAttribute = 0x1, ModSecondAttribute = 0x2, ModSkill = 0x10; @@ -180,7 +183,9 @@ internal static class PlayerProgressHooks private const uint ModAnyStat = ModAttribute | ModSecondAttribute | ModSkill; private static long _wantedUntilMs; + private static long _slowWantedUntilMs; private static long _nextReadMs; + private static long _lastReadMs; private static int _version; private static PlayerProgress? _published; @@ -198,9 +203,23 @@ internal static class PlayerProgressHooks public static void Want() => Volatile.Write(ref _wantedUntilMs, Environment.TickCount64 + WantWindowMs); + /// + /// A background reader (the plugin API, TrainingApi) wants data for the next 5 s, read at + /// most every 2 s, so a plugin polling every few seconds doesn't keep the 2 Hz panel rate up. + /// Any thread. + /// + public static void WantSlow() => + Volatile.Write(ref _slowWantedUntilMs, Environment.TickCount64 + SlowWantWindowMs); + /// Read again at the next main-thread tick (after a raise). Any thread. public static void RefreshSoon() => Volatile.Write(ref _nextReadMs, 0); + /// + /// Environment.TickCount64 of the last successful read, changed or not (0 = never), so a + /// reader can tell how old 's numbers are. Any thread. + /// + public static long LastReadMs => Volatile.Read(ref _lastReadMs); + /// The last published read, or null. Never written again once published. Any thread. public static PlayerProgress? Current => Volatile.Read(ref _published); @@ -213,21 +232,25 @@ internal static class PlayerProgressHooks if (!MainThreadGuard.IsOnMainThread()) return; long now = Environment.TickCount64; - if (now > Volatile.Read(ref _wantedUntilMs) || now < Volatile.Read(ref _nextReadMs)) + bool panel = now <= Volatile.Read(ref _wantedUntilMs); + if ((!panel && now > Volatile.Read(ref _slowWantedUntilMs)) || now < Volatile.Read(ref _nextReadMs)) return; - Volatile.Write(ref _nextReadMs, now + RefreshMs); + Volatile.Write(ref _nextReadMs, now + (panel ? RefreshMs : SlowRefreshMs)); if (!ClientObjectHooks.ReadPlayerProgressLive(Work)) return; CopyStatBuffs(Work); PlayerProgress? current = Volatile.Read(ref _published); - if (current != null && current.SameAs(Work)) - return; - var snapshot = new PlayerProgress(); - snapshot.CopyFrom(Work); - snapshot.Version = ++_version; - Volatile.Write(ref _published, snapshot); + if (current == null || !current.SameAs(Work)) + { + var snapshot = new PlayerProgress(); + snapshot.CopyFrom(Work); + snapshot.Version = ++_version; + Volatile.Write(ref _published, snapshot); + } + // After publishing: a reader that sees this time sees this read's numbers. + Volatile.Write(ref _lastReadMs, Environment.TickCount64); } /// The player's enchantments that change a skill, attribute or vital (not vitae). diff --git a/src/RynthCore.Engine/Compatibility/PlayerTraining.cs b/src/RynthCore.Engine/Compatibility/PlayerTraining.cs index 947c260..bce841f 100644 --- a/src/RynthCore.Engine/Compatibility/PlayerTraining.cs +++ b/src/RynthCore.Engine/Compatibility/PlayerTraining.cs @@ -31,6 +31,10 @@ // // Every call runs on AC's main thread: off it (or with defer) the request goes // through AcMainThreadQueue (ActionKind.Train) and the drain calls back in. +// Only in the world (TrainingApi.InWorld), checked again when the drain sends: +// a raise queued just before a logout is dropped, not sent to the next screen. +// The plugin API (v79) reaches these through TrainingApi, which also works the +// XP out and checks it (TrainingCosts). // ============================================================================ using System; @@ -112,6 +116,11 @@ internal static unsafe class PlayerTraining { if (!Bound(kind) || !ValidTarget(kind, stype) || xp == 0) return false; + if (!TrainingApi.InWorld) + { + RynthLog.Compat($"PlayerTraining: {kind} {stype} not sent - not in the world"); + return false; + } if (defer || !MainThreadGuard.IsOnMainThread()) return AcMainThreadQueue.EnqueueTrain((uint)kind, stype, xp); diff --git a/src/RynthCore.Engine/Compatibility/RadarHooks.cs b/src/RynthCore.Engine/Compatibility/RadarHooks.cs index 33cc458..4641de1 100644 --- a/src/RynthCore.Engine/Compatibility/RadarHooks.cs +++ b/src/RynthCore.Engine/Compatibility/RadarHooks.cs @@ -320,6 +320,9 @@ internal static class RadarHooks IntPtr inst = _gmRadarUIInstance; if (inst == IntPtr.Zero) return false; + // Outside the world AC has freed the radar panel this points at (UiFlowHooks). + if (!UiFlowHooks.InWorldOrUnknown || UiFlowHooks.ClientCleanupStarted) + return false; if (_uiElementGetSurfaceBoxAddress == IntPtr.Zero) return false; diff --git a/src/RynthCore.Engine/Compatibility/RawPacketHooks.cs b/src/RynthCore.Engine/Compatibility/RawPacketHooks.cs index bc8acd7..37260df 100644 --- a/src/RynthCore.Engine/Compatibility/RawPacketHooks.cs +++ b/src/RynthCore.Engine/Compatibility/RawPacketHooks.cs @@ -15,6 +15,8 @@ namespace RynthCore.Engine.Compatibility; /// We read the function address, install a MinHook detour, call through to the /// original on every receive, then hand the buffer to RawPacketParser for /// opcode extraction. The hook is purely read-only and never modifies traffic. +/// It also feeds Net.ServerMessageStream (API v78), which copies fragment datagrams +/// for reassembly on the plugin pump while a plugin wants server messages. /// internal static class RawPacketHooks { @@ -82,6 +84,11 @@ internal static class RawPacketHooks // This guard prevents any parser bug from crashing the client. try { + // v78 server-message stream: a volatile check, and while a plugin wants + // messages, one copy into a ring for the pump (never blocks, never allocates). + // A MSG_PEEK (0x2) read leaves the datagram queued; the real read copies it. + if ((flags & 0x2) == 0) + Net.ServerMessageStream.OnDatagram((byte*)buf, bytesRead); RawPacketParser.Parse((byte*)buf, bytesRead); } catch diff --git a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs index 125d05f..e7cc57a 100644 --- a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs +++ b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs @@ -43,12 +43,20 @@ namespace RynthCore.Engine.Compatibility; /// never sees it; every other "/rv" line still goes to the plugin. /// /rc server [auto|aelrynth|other] — which server the engine detects /// () and why; aelrynth/other force it for this session. +/// /rc hooks [on|off <name>] (alias /rc uihooks) — the UI hooks +/// (screen mode, client cleanup, tooltip, drag/drop; ): +/// status, or switch one off/on (now and in engine.json). /// /rc mastery — the Aelrynth mastery feed's state (), /// and ask the server for /mastery-data again. /// /rc worldlayer [auto|uipass|transition|endscene] — where the world overlays /// (nameplates, combat text, Nav3D markers) draw in AC's frame /// (): alone it reports the path and counters; /// a mode forces it for this session (A/B checks). Auto at every start; not saved. +/// /rc netmsg [status|on|off|log on|off|capture on|off] - the reassembled +/// server-message stream for plugins (, API v78): +/// counters; on/off for this session (engine.json "ServerMessageStream": false is the +/// kill switch); log = the SDK parsers run on live messages, results to the log; +/// capture = raw datagrams to a .rnc file for tools/NetMessageTests. /// /// internal static class RynthCoreChatCommands @@ -153,6 +161,26 @@ internal static class RynthCoreChatCommands return true; } + // /rc hooks [on|off ] : the UI hooks (screen mode, client cleanup, tooltip, drag/drop) + if (IsVerb(sub, "hooks", out string hooksArgs) || IsVerb(sub, "uihooks", out hooksArgs)) + { + try { HandleHooksCommand(hooksArgs); } + catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc hooks failed - {ex.GetType().Name}: {ex.Message}"); } + return true; + } + + // /rc netmsg [status|on|off|log on|off|capture on|off] : the v78 server message stream + if (IsVerb(sub, "netmsg", out string netArgs)) + { + try + { + foreach (string l in Net.ServerMessageStream.HandleCommand(netArgs)) + Reply(l); + } + catch (Exception ex) { RynthLog.Compat($"RynthCoreChatCommands: /rc netmsg failed - {ex.GetType().Name}: {ex.Message}"); } + return true; + } + // /rc vtank [clear] : what the engine knows about VTank's macro (Decal bridge only); // clear = VTank was stopped with its own button, which the engine can't see. if (IsVerb(sub, "vtank", out string vtankArgs)) @@ -660,6 +688,30 @@ internal static class RynthCoreChatCommands return s != null && float.TryParse(s, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out v); } + /// + /// /rc hooks: one line per UI hook (UiHookRegistry: UseNewMode, ClientCleanup, + /// StartTooltip, ResetTooltip, CheckTooltip, StartDragandDrop, CatchDroppedItem) with + /// its address, how it was found, on/off and how often it fired, then the screen and + /// tooltip/drag state. "/rc hooks off <name>" makes that hook pass straight to AC + /// now and leaves it out at the next start (engine.json DisabledUiHooks); "on" undoes it. + /// + private static void HandleHooksCommand(string args) + { + string[] parts = args.Split(' ', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + if (parts.Length == 2 && (parts[0].Equals("on", StringComparison.OrdinalIgnoreCase) || parts[0].Equals("off", StringComparison.OrdinalIgnoreCase))) + { + Reply(UiHookRegistry.SetEnabled(parts[1], parts[0].Equals("on", StringComparison.OrdinalIgnoreCase))); + return; + } + if (parts.Length != 0 && !(parts.Length == 1 && parts[0].Equals("status", StringComparison.OrdinalIgnoreCase))) + { + Reply("Usage: /rc hooks [status] | /rc hooks on|off "); + return; + } + foreach (string line in UiHookRegistry.DescribeLines()) + Reply(line); + } + /// "on"/"off" sets; anything else (or nothing) toggles. private static bool Flag(string? value, bool current) => value?.ToLowerInvariant() switch { "on" or "1" or "true" => true, "off" or "0" or "false" => false, _ => !current }; diff --git a/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs b/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs index 210d35f..db2f302 100644 --- a/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs +++ b/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs @@ -347,10 +347,12 @@ internal static class SmartBoxHooks // v70: the sequence and its error code as one 64-bit value, so a reader // on the plugin pump never pairs one UseDone's number with another's code. System.Threading.Interlocked.Exchange(ref _useDoneLast, ((long)(uint)seq << 32) | err); - if (_useDoneLogCount < 25) + // Every one while RynthLog.ActionDoneTraceEnabled (the default; 2026-10-05: the + // first 25 of a session couldn't show which completion a held cast was waiting on). + if (RynthLog.ActionDoneTraceEnabled || _useDoneLogCount < 25) { _useDoneLogCount++; - RynthLog.Compat($"UseDone seq={seq} err=0x{err:X}"); + RynthLog.Compat($"UseDone seq={seq} err=0x{err:X}{(err == 0x1D ? " (too busy)" : err == 0 ? " (done)" : "")}"); } break; } diff --git a/src/RynthCore.Engine/Compatibility/TrainingApi.cs b/src/RynthCore.Engine/Compatibility/TrainingApi.cs new file mode 100644 index 0000000..c79a3cd --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/TrainingApi.cs @@ -0,0 +1,278 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/TrainingApi.cs +// +// Plugin API v79: spending experience the way the retail character window's +// "+" does (docs/IMGUI_SKILLS.md "Raising"), for plugins (the RynthRemote +// plugin, so the DrakRemote phone app can raise from the Skills tab). +// +// GetTrainingInfo the numbers a raise needs and what it costs: unassigned XP, +// skill credits, and per attribute / vital / skill the ranks, +// XP spent, base and buffed value, the XP for +1 and +10, how +// many ranks the unassigned XP buys, the credits to train. +// Raise n ranks of one attribute, vital or trained skill. The engine +// works the XP out from the same numbers (portal XpTable) and +// refuses unless it equals what the caller confirmed. +// TrainSkill an untrained skill -> trained, for exactly the SkillTable's +// credit price. +// +// Sources: PlayerProgressHooks (the player's qualities, read on AC's main thread; +// WantSlow keeps them coming every 2 s while a plugin asks) and SkillDat (the +// portal SkillTable and XpTable, read once in the background). The sends are +// PlayerTraining's: the client's own CM_Train senders, on AC's main thread +// (queued in AcMainThreadQueue from any other thread). +// +// Guards: in the world only (login complete, the world screen, no logout, no +// teardown, the snapshot is this character's); numbers at most 3 s old (else +// a read is asked for and Stale comes back: try again a moment later); one +// raise at a time (Busy until the unassigned XP or the credits change, or 5 s). +// Any thread. +// ============================================================================ + +using System; +using RynthCore.Engine.ImGuiBackend.Panels; +using RynthCore.Engine.Plugins; + +namespace RynthCore.Engine.Compatibility; + +internal static unsafe class TrainingApi +{ + /// Numbers older than this are not raised against. + internal const int StaleAfterMs = 3000; + private const int BusyMs = 5000; + + public const uint KindAttribute = 1, KindVital = 2, KindSkill = 3; + + private static readonly object Gate = new(); + private static long _busyUntilMs; + private static long _busyUnassigned; + private static int _busyCredits; + + /// The player is in the world and its objects are live (same test as the + /// main-thread snapshots, plus the world screen and no client cleanup). Any thread. + public static bool InWorld => + LoginLifecycleHooks.HasObservedLoginComplete + && UiFlowHooks.InWorldOrUnknown + && !UiFlowHooks.ClientCleanupStarted + && !LogoutLifecycleHooks.HasObservedLogout + && !DbCacheTeardownHooks.TeardownActive + && ClientHelperHooks.GetPlayerId() != 0; + + /// v79 GetTrainingInfo. Returns the number of entries there are (entries may be null to + /// ask; at most maxEntries are written). 0 while there is nothing to report. + public static int GetInfo(TrainingInfoNative* info, TrainingEntryNative* entries, int maxEntries) + { + PlayerProgressHooks.WantSlow(); + SkillDat.EnsureLoadQueued(); + + bool inWorld = InWorld; + uint playerId = inWorld ? ClientHelperHooks.GetPlayerId() : 0; + PlayerProgress? s = PlayerProgressHooks.Current; + if (s != null && (s.PlayerId != playerId || !inWorld)) s = null; + SkillDatTables? dat = SkillDat.Tables; + long now = Environment.TickCount64; + long readAt = PlayerProgressHooks.LastReadMs; + + int count = 0; + if (s != null && dat != null) + { + count = 6 + 3; + for (uint id = 1; id <= PlayerProgress.MaxSkill; id++) + if (dat.Skills.ContainsKey(id)) count++; + } + + if (info != null && info->Size >= 8) + { + TrainingInfoNative o = default; + uint flags = 0; + if (inWorld) flags |= TrainingInfoFlags.InWorld; + if (PlayerTraining.Available) flags |= TrainingInfoFlags.RaiseBound; + if (PlayerTraining.TrainAvailable) flags |= TrainingInfoFlags.TrainBound; + if (s != null) flags |= TrainingInfoFlags.HaveNumbers; + if (dat != null) flags |= TrainingInfoFlags.HaveTables; + if (IsBusy(s, now)) flags |= TrainingInfoFlags.Busy; + o.Flags = flags; + o.SnapshotVersion = s != null ? (uint)s.Version : 0; + o.AgeMs = s != null && readAt > 0 ? (uint)Math.Clamp(now - readAt, 0, uint.MaxValue - 1) : uint.MaxValue; + o.UnassignedXp = s?.UnassignedXp ?? -1; + o.TotalXp = s?.TotalXp ?? -1; + o.Level = s?.Level ?? 0; + o.SkillCredits = s?.SkillCredits ?? -1; + o.EntryCount = count; + o.StaleAfterMs = StaleAfterMs; + uint n = Math.Min(info->Size, (uint)sizeof(TrainingInfoNative)); + Buffer.MemoryCopy(&o, info, n, n); + info->Size = n; + } + + if (entries == null || maxEntries <= 0 || s == null || dat == null) + return count; + + int w = 0; + for (uint a = 1; a <= 6 && w < maxEntries; a++) + entries[w++] = Entry(KindAttribute, a, 0, s.AttrRanks[a], s.AttrXpSpent[a], s.AttrInit[a], + (int)s.AttrBase[a], (int)s.AttrBuffed[a], dat.Xp.AttributeXp, s.UnassignedXp); + for (uint v = 1; v <= 3 && w < maxEntries; v++) + entries[w++] = Entry(KindVital, v * 2 - 1, 0, s.VitalRanks[v], s.VitalXpSpent[v], s.VitalInit[v], + (int)s.VitalBase[v], (int)s.VitalBuffed[v], dat.Xp.VitalXp, s.UnassignedXp); + for (uint id = 1; id <= PlayerProgress.MaxSkill && w < maxEntries; id++) + { + if (!dat.Skills.TryGetValue(id, out SkillDatEntry? e)) continue; + uint cls = s.SkillClass[id]; + TrainingEntryNative x = Entry(KindSkill, id, cls, s.SkillRanks[id], s.SkillXpSpent[id], s.SkillInit[id], + s.SkillBase[id], s.SkillBuffed[id], TrainingCosts.TableFor(dat.Xp, KindSkill, cls), s.UnassignedXp); + if (e.UsableUntrained) x.Flags |= TrainingEntryFlags.UsableUntrained; + if (cls < 2) + { + x.TrainCredits = Math.Max(0, e.TrainedCost); + if (x.TrainCredits > 0) x.Flags |= TrainingEntryFlags.Trainable; + } + entries[w++] = x; + } + return count; + } + + private static TrainingEntryNative Entry(uint kind, uint stype, uint cls, uint ranks, uint spent, uint init, + int baseValue, int buffed, uint[]? table, long unassigned) + { + var x = new TrainingEntryNative + { + Kind = kind, Stype = stype, Class = cls, Ranks = ranks, XpSpent = spent, Innate = init, + Base = baseValue, Buffed = buffed, CostOne = -1, CostTen = -1, + }; + if (table != null && table.Length > 0) + { + x.RanksLeft = TrainingCosts.RanksLeft(table, ranks); + if (x.RanksLeft == 0) x.Flags |= TrainingEntryFlags.AtTop; + else x.Flags |= TrainingEntryFlags.Raisable; + x.CostOne = TrainingCosts.CostOf(table, ranks, spent, 1); + x.CostTen = TrainingCosts.CostOf(table, ranks, spent, 10); + x.Affordable = TrainingCosts.Affordable(table, ranks, spent, Math.Max(0, unassigned)); + } + return x; + } + + private static bool IsBusy(PlayerProgress? s, long now) + { + lock (Gate) + { + if (now >= _busyUntilMs) return false; + // The server answered: the unassigned XP or the credits moved. + if (s != null && (s.UnassignedXp != _busyUnassigned || s.SkillCredits != _busyCredits)) + { + _busyUntilMs = 0; + return false; + } + return true; + } + } + + /// The snapshot to act on, or why not. + private static RaiseStatus Ready(out PlayerProgress? s, out SkillDatTables? dat) + { + PlayerProgressHooks.WantSlow(); + SkillDat.EnsureLoadQueued(); + s = null; + dat = SkillDat.Tables; + if (!InWorld) return RaiseStatus.NotInWorld; + uint playerId = ClientHelperHooks.GetPlayerId(); + s = PlayerProgressHooks.Current; + if (s == null || s.PlayerId != playerId || dat == null || !s.AttributeCacheRead || !s.SkillTableRead) + { + PlayerProgressHooks.RefreshSoon(); + return RaiseStatus.NotReady; + } + long read = PlayerProgressHooks.LastReadMs; + if (read <= 0 || Environment.TickCount64 - read > StaleAfterMs) + { + PlayerProgressHooks.RefreshSoon(); + return RaiseStatus.Stale; + } + if (IsBusy(s, Environment.TickCount64)) return RaiseStatus.Busy; + return RaiseStatus.Sent; + } + + /// v79 Raise: ranks of one attribute (1..6), vital (1 health, + /// 3 stamina, 5 mana) or trained/specialized skill. = the XP sent. + public static RaiseStatus Raise(uint kind, uint stype, uint ranks, long expectedXp, out long xpSent) + { + xpSent = 0; + if (kind is < KindAttribute or > KindSkill || ranks < 1 || ranks > TrainingCosts.MaxRanksPerRaise || expectedXp < 0 + || !ValidTarget(kind, stype)) + return RaiseStatus.BadArguments; + if (!PlayerTraining.Available) return RaiseStatus.Unavailable; + + RaiseStatus ready = Ready(out PlayerProgress? s, out SkillDatTables? dat); + if (ready != RaiseStatus.Sent) return ready; + + uint[]? table; + uint have, spent; + switch (kind) + { + case KindAttribute: + table = dat!.Xp.AttributeXp; have = s!.AttrRanks[stype]; spent = s.AttrXpSpent[stype]; + break; + case KindVital: + uint v = (stype + 1) / 2; + table = dat!.Xp.VitalXp; have = s!.VitalRanks[v]; spent = s.VitalXpSpent[v]; + break; + default: + table = TrainingCosts.TableFor(dat!.Xp, KindSkill, s!.SkillClass[stype]); have = s.SkillRanks[stype]; spent = s.SkillXpSpent[stype]; + break; + } + + RaiseStatus check = TrainingCosts.CheckRaise(table, have, spent, s.UnassignedXp, (int)ranks, expectedXp, out long cost); + if (check != RaiseStatus.Sent) return check; + + var trainKind = kind switch + { + KindAttribute => PlayerTraining.TrainKind.Attribute, + KindVital => PlayerTraining.TrainKind.Vital, + _ => PlayerTraining.TrainKind.Skill, + }; + AcActionTrace.Record("Raise", kind << 16 | stype, (uint)cost); + if (!PlayerTraining.Raise(trainKind, stype, (uint)cost)) return RaiseStatus.SendFailed; + MarkBusy(s); + xpSent = cost; + RynthLog.Compat($"TrainingApi: raise {trainKind} {stype} +{ranks} for {cost:N0} XP (plugin)"); + return RaiseStatus.Sent; + } + + /// v79 TrainSkill: untrained -> trained for exactly the SkillTable's credit price. + public static RaiseStatus TrainSkill(uint stype, int expectedCredits) + { + if (stype < 1 || stype > PlayerProgress.MaxSkill || expectedCredits < 0) return RaiseStatus.BadArguments; + if (!PlayerTraining.TrainAvailable) return RaiseStatus.Unavailable; + + RaiseStatus ready = Ready(out PlayerProgress? s, out SkillDatTables? dat); + if (ready != RaiseStatus.Sent) return ready; + if (!dat!.Skills.TryGetValue(stype, out SkillDatEntry? e)) return RaiseStatus.NotRaisable; + + RaiseStatus check = TrainingCosts.CheckTrain(s!.SkillClass[stype], e.TrainedCost, s.SkillCredits, expectedCredits); + if (check != RaiseStatus.Sent) return check; + + AcActionTrace.Record("TrainSkill", stype, (uint)e.TrainedCost); + if (!PlayerTraining.TrainSkill(stype, (uint)e.TrainedCost)) return RaiseStatus.SendFailed; + MarkBusy(s); + RynthLog.Compat($"TrainingApi: train skill {stype} for {e.TrainedCost} credits (plugin)"); + return RaiseStatus.Sent; + } + + private static bool ValidTarget(uint kind, uint stype) => kind switch + { + KindAttribute => stype >= 1 && stype <= 6, + KindVital => stype is 1 or 3 or 5, + KindSkill => stype >= 1 && stype <= PlayerProgress.MaxSkill, + _ => false, + }; + + private static void MarkBusy(PlayerProgress s) + { + lock (Gate) + { + _busyUntilMs = Environment.TickCount64 + BusyMs; + _busyUnassigned = s.UnassignedXp; + _busyCredits = s.SkillCredits; + } + PlayerProgressHooks.RefreshSoon(); + } +} diff --git a/src/RynthCore.Engine/Compatibility/TrainingCosts.cs b/src/RynthCore.Engine/Compatibility/TrainingCosts.cs new file mode 100644 index 0000000..ea2fe8b --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/TrainingCosts.cs @@ -0,0 +1,191 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/TrainingCosts.cs +// +// The XP arithmetic behind raising an attribute, a vital or a skill, and the +// checks a raise from the plugin API passes before anything is sent. Pure code +// (no AC memory, no engine state), so tools/TrainingCostTests compiles it in and +// runs it against the XpTable of a real client_portal.dat. +// +// XpTable 0x0E000018 (ACE.DatLoader XpTable; the server raises against the same +// table): file id u32; counts i32 for attributes, vitals, trained skills, +// specialized skills, then the level count u32; then count+1 u32 each for +// attributes, vitals, trained and specialized skills, count+1 u64 levels and +// count+1 u32 skill credits per level. Entry n is the total XP spent at rank n. +// +// Cost of n raises: table[ranks + n] - xpSpent (ACE Player.SpendAttributeXp / +// SpendSkillXp take an XP amount and raise as many ranks as it covers; the retail +// character window sends exactly this for "+1" and "+10": gmAttributeUI / +// gmSkillUI GetCostToRaise / GetCostToRaise10 -> CM_Train::Event_Train*). +// ============================================================================ + +using System; +using System.Buffers.Binary; + +namespace RynthCore.Engine.Compatibility; + +/// The four raise tables of the portal XpTable (index = rank, value = total XP at that rank). +internal sealed class XpTableData +{ + public uint[] AttributeXp = Array.Empty(); + public uint[] VitalXp = Array.Empty(); + public uint[] TrainedXp = Array.Empty(); + public uint[] SpecializedXp = Array.Empty(); + public ulong[] LevelXp = Array.Empty(); +} + +/// The plugin API's raise and train results (RynthCoreAPI.RaiseFn / TrainSkillFn, v79). +internal enum RaiseStatus +{ + Sent = 1, + /// The client's raise senders aren't bound on this build. + Unavailable = 0, + NotInWorld = -1, + BadArguments = -2, + /// No player snapshot or no XP table yet (both are being fetched; try again in a second). + NotReady = -3, + /// The numbers are older than the freshness limit; a new read was asked for. Try again in a second. + Stale = -4, + /// The cost the caller expected isn't the cost now (something changed: refresh and ask again). + CostChanged = -5, + /// Not enough unassigned XP (or skill credits for a train). + NotEnough = -6, + /// Can't be raised: at or past the top rank, an untrained skill, or a skill that can't be trained. + NotRaisable = -7, + /// An earlier raise or train hasn't shown up in the numbers yet (5 s at most). + Busy = -8, + /// The send failed or the action queue was full. + SendFailed = -9, +} + +internal static class TrainingCosts +{ + /// Most ranks one API raise may buy (the retail window offers 1 and 10). + public const int MaxRanksPerRaise = 100; + + // ── the XpTable ────────────────────────────────────────────────────── + + /// Reads the portal XpTable file (0x0E000018). False when it is short or the counts are absurd. + public static bool TryParseXpTable(ReadOnlySpan raw, out XpTableData table) + { + table = new XpTableData(); + int p = 0; + if (!U32(raw, ref p, out _)) return false; // file id + if (!U32(raw, ref p, out uint attrs) || !U32(raw, ref p, out uint vitals) + || !U32(raw, ref p, out uint trained) || !U32(raw, ref p, out uint spec) + || !U32(raw, ref p, out uint levels)) + return false; + if (attrs > 10000 || vitals > 10000 || trained > 10000 || spec > 10000 || levels > 10000) + return false; + if (!U32s(raw, ref p, (int)attrs + 1, out table.AttributeXp) + || !U32s(raw, ref p, (int)vitals + 1, out table.VitalXp) + || !U32s(raw, ref p, (int)trained + 1, out table.TrainedXp) + || !U32s(raw, ref p, (int)spec + 1, out table.SpecializedXp)) + return false; + var lv = new ulong[levels + 1]; + for (int i = 0; i <= levels; i++) + { + if (p + 8 > raw.Length) return false; + lv[i] = BinaryPrimitives.ReadUInt64LittleEndian(raw.Slice(p, 8)); + p += 8; + } + table.LevelXp = lv; + return true; + } + + private static bool U32(ReadOnlySpan b, ref int p, out uint v) + { + v = 0; + if (p + 4 > b.Length) return false; + v = BinaryPrimitives.ReadUInt32LittleEndian(b.Slice(p, 4)); + p += 4; + return true; + } + + private static bool U32s(ReadOnlySpan b, ref int p, int n, out uint[] a) + { + a = Array.Empty(); + if (n < 0 || p + (long)n * 4 > b.Length) return false; + a = new uint[n]; + for (int i = 0; i < n; i++) { a[i] = BinaryPrimitives.ReadUInt32LittleEndian(b.Slice(p, 4)); p += 4; } + return true; + } + + // ── arithmetic (the server's: Player.SpendAttributeXp / SpendSkillXp) ── + + /// The table a stat raises against: attributes, vitals, trained (2) or specialized (3+) skills; + /// null for an untrained or unknown skill (those aren't raised with XP). + public static uint[]? TableFor(XpTableData t, uint kind, uint skillClass) => kind switch + { + 1 => t.AttributeXp, + 2 => t.VitalXp, + 3 => skillClass >= 3 ? t.SpecializedXp : skillClass == 2 ? t.TrainedXp : null, + _ => null, + }; + + /// True when is the table's top rank (nothing left to buy). + public static bool IsMax(uint[] table, uint ranks) => table.Length == 0 || ranks + 1L >= table.Length; + + /// Ranks left to the top of the table. + public static int RanksLeft(uint[] table, uint ranks) => (int)Math.Max(0L, table.Length - 1L - ranks); + + /// XP to buy more ranks from with + /// already spent; -1 past the top; 0 for n < 1. + public static long CostOf(uint[] table, uint ranks, uint spent, int n) + { + if (n < 1) return 0; + long target = (long)ranks + n; + if (target >= table.Length) return -1; + return Math.Max(0L, (long)table[target] - spent); + } + + /// How many ranks in a row XP buys (0 when not even one), up to the top. + public static int Affordable(uint[] table, uint ranks, uint spent, long available) + { + int lo = 0, hi = RanksLeft(table, ranks); + while (lo < hi) + { + int mid = (lo + hi + 1) / 2; + long c = CostOf(table, ranks, spent, mid); + if (c >= 0 && c <= available) lo = mid; else hi = mid - 1; + } + return lo; + } + + // ── the checks before a raise is sent ────────────────────────────────── + + /// + /// Everything a raise of ranks must pass, given the numbers now: + /// a table (null = untrained/unknown skill), not past the top, a cost that equals what the + /// caller confirmed ( > 0; 0 = don't compare), enough + /// unassigned XP, and an amount the 32-bit game action can carry. + /// is the XP to send when the result is . + /// + public static RaiseStatus CheckRaise(uint[]? table, uint ranks, uint spent, long unassignedXp, + int count, long expectedXp, out long cost) + { + cost = -1; + if (count < 1 || count > MaxRanksPerRaise || expectedXp < 0) return RaiseStatus.BadArguments; + if (table == null || table.Length == 0) return RaiseStatus.NotRaisable; + cost = CostOf(table, ranks, spent, count); + if (cost <= 0) return RaiseStatus.NotRaisable; // past the top (-1) or nothing to buy (0) + if (expectedXp != 0 && expectedXp != cost) return RaiseStatus.CostChanged; + if (cost > unassignedXp) return RaiseStatus.NotEnough; + if (cost > uint.MaxValue) return RaiseStatus.NotRaisable; // more than one game action can carry + return RaiseStatus.Sent; + } + + /// + /// The checks for training an untrained skill with credits: the skill must be untrained + /// (class 1, or 0 = not in the table), the dat must price it (> 0), the price must be what + /// the caller confirmed ( > 0; 0 = don't compare) and + /// the player must have the credits. + /// + public static RaiseStatus CheckTrain(uint skillClass, int trainedCost, int credits, int expectedCredits) + { + if (expectedCredits < 0) return RaiseStatus.BadArguments; + if (skillClass >= 2 || trainedCost <= 0) return RaiseStatus.NotRaisable; + if (expectedCredits != 0 && expectedCredits != trainedCost) return RaiseStatus.CostChanged; + if (trainedCost > credits) return RaiseStatus.NotEnough; + return RaiseStatus.Sent; + } +} diff --git a/src/RynthCore.Engine/Compatibility/UiElementHooks.cs b/src/RynthCore.Engine/Compatibility/UiElementHooks.cs new file mode 100644 index 0000000..1c9e883 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/UiElementHooks.cs @@ -0,0 +1,480 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/UiElementHooks.cs +// +// Tooltip and drag/drop hooks on AC's own UI (Chorizite comparison gap #5, +// 2026-10-05). Every address and offset below was checked offline against our +// client (tools/ui_hooks_check.py; report in ops/overnight/2026-10-05-ui-hooks.md): +// +// UIElementManager (the UI singleton; `this` of the first four): +// StartTooltip(StringInfo*, UIElement* owner, uint, uint, uint) 0x0045DF70, ret 14h +// stores the owner at +0x2F4, builds the tooltip element into +0x2F8. +// ResetTooltip() 0x0045C440 frees +0x2F8, then tail-jumps into CheckTooltip. +// CheckTooltip() 0x0045B7C0 per-frame tooltip timer (+0x325, +0x2D4, +0x24C). +// StartDragandDrop(UIElement*, int x, int y) -> bool 0x0045E120, ret 0Ch +// on success the drag icon is at +0x31C and its owner at +0x320; it calls +// itself once for a drag proxy (we report only the outermost call). +// UIElement::CatchDroppedItem(DragDropInfo*) -> bool 0x00461860, ret 4 +// the catcher's virtual (vtable +0xD8), called from StopDragandDrop +// (0x00459880). All 113 UIElement vtables in the client route it here: +// 36 directly, 77 through UIElement_Field::CatchDroppedItem, which calls +// it. It broadcasts element message 0x15 (drop release) to the catcher; +// that message is what drops an item on the ground (SmartBoxWrapper), +// moves it into a pack (ItemList) and so on. DragDropInfo: +0x08 the +// drag icon, +0x0C its owner, +0x10 the catcher, +0x14 success. +// Not hooked, called: UIElement_ItemList::InqDropIconInfo(UIElement*, uint* item, +// uint* spell, uint* flags), cdecl, 0x004E3380: AC's own "which object or +// spell is this icon" (13 callers in the client; reads element properties +// only, null-safe). +// UIElement offsets: +0x2E4 element id (GetAncestorByID compares it), vtable +// +0xA0 GetParent, +0x98 GetUIElementType (UIElement_ItemList: 0x10000031). +// +// Events, on AC's main thread, queued to plugins (API v77): +// tooltip shown (object id or spell id of the hovered icon), tooltip hidden, +// drag started (object/spell id, icon), item dropped (object/spell id, the +// catcher's element id). +// Drop claims: an item dragged out of an AC item list and let go over an engine +// panel that takes drops (ImGui/UiDropTargets: the Loot Editor) never reaches +// AC: CatchDroppedItem answers false without running, which is AC's own +// "not caught" path (StopDragandDrop then tells the source list the drop +// failed; ItemList::HandleDropRelease ignores a failed drop whose catcher isn't +// inside it). Not claimed when the catcher is inside the source list itself. +// +// Not done (needs in-game checks): adding lines to AC's own tooltip text. That +// means building an AC StringInfo/PStringBase and editing the tooltip element +// AC just made, inside its allocator - see the report. +// ============================================================================ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; + +namespace RynthCore.Engine.Compatibility; + +internal static unsafe class UiElementHooks +{ + // Fallback VAs (4,841,472-byte client). Pattern-scan is the source of truth. + private const int StartTooltipFallbackVa = 0x0045DF70; + private const int ResetTooltipFallbackVa = 0x0045C440; + private const int CheckTooltipFallbackVa = 0x0045B7C0; + private const int StartDragandDropFallbackVa = 0x0045E120; + private const int CatchDroppedItemFallbackVa = 0x00461860; + private const int InqDropIconInfoFallbackVa = 0x004E3380; + + private const int MgrTooltipOwner = 0x2F4; + private const int MgrTooltipElement = 0x2F8; + private const int MgrDragIcon = 0x31C; + private const int MgrDragOwner = 0x320; + private const int ElementId = 0x2E4; + private const int VtGetUIElementType = 0x98; + private const int VtGetParent = 0xA0; + private const int DdiElement = 0x08; + private const int DdiOwner = 0x0C; + private const int UIElementTypeItemList = 0x10000031; + + // StartTooltip: sub esp,10h / push ebp / push esi / mov esi,ecx / mov ecx,[esi+2F8h] / + // xor ebp,ebp / cmp ecx,ebp / push edi / mov [esp+18h],esi / jz +0Bh / call rel32 / + // mov [esi+2F8h],ebp - frees an old tooltip element first. Unique, lands at 0x0045DF70. + private static readonly byte?[] StartTooltipPattern = + [ + 0x83, 0xEC, 0x10, 0x55, 0x56, 0x8B, 0xF1, 0x8B, 0x8E, 0xF8, 0x02, 0x00, 0x00, + 0x33, 0xED, 0x3B, 0xCD, 0x57, 0x89, 0x74, 0x24, 0x18, 0x74, 0x0B, + 0xE8, null, null, null, null, 0x89, 0xAE, 0xF8, 0x02, 0x00, 0x00 + ]; + + // ResetTooltip: push esi / mov esi,ecx / mov ecx,[esi+2F8h] / test ecx,ecx / jz +0Fh / + // call rel32 / mov dword [esi+2F8h],0 / mov al,[esi+325h]. Unique, lands at 0x0045C440. + private static readonly byte?[] ResetTooltipPattern = + [ + 0x56, 0x8B, 0xF1, 0x8B, 0x8E, 0xF8, 0x02, 0x00, 0x00, 0x85, 0xC9, 0x74, 0x0F, + 0xE8, null, null, null, null, 0xC7, 0x86, 0xF8, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x8A, 0x86, 0x25, 0x03, 0x00, 0x00 + ]; + + // CheckTooltip: sub esp,0Ch / mov eax,[imm32] / push esi / mov esi,ecx / mov ecx,[imm32] / + // mov [esp+8],eax / mov al,[esi+325h] / test al,al / mov [esp+0Ch],ecx / jnz +79h / + // mov al,[esi+2D4h]. The two timer globals wildcarded. Unique, lands at 0x0045B7C0. + private static readonly byte?[] CheckTooltipPattern = + [ + 0x83, 0xEC, 0x0C, 0xA1, null, null, null, null, 0x56, 0x8B, 0xF1, 0x8B, 0x0D, null, null, null, null, + 0x89, 0x44, 0x24, 0x08, 0x8A, 0x86, 0x25, 0x03, 0x00, 0x00, 0x84, 0xC0, 0x89, 0x4C, 0x24, 0x0C, + 0x75, 0x79, 0x8A, 0x86, 0xD4, 0x02, 0x00, 0x00 + ]; + + // StartDragandDrop: sub esp,34h / push ebx,ebp,esi,edi / mov edi,[esp+48h] / test edi,edi / + // mov esi,ecx / jz rel32 / mov eax,[imm32] / test eax,eax / jz rel32 / mov ebx,[imm32] / + // test ebx,ebx. Unique, lands at 0x0045E120. + private static readonly byte?[] StartDragandDropPattern = + [ + 0x83, 0xEC, 0x34, 0x53, 0x55, 0x56, 0x57, 0x8B, 0x7C, 0x24, 0x48, 0x85, 0xFF, 0x8B, 0xF1, + 0x0F, 0x84, null, null, null, null, 0xA1, null, null, null, null, 0x85, 0xC0, + 0x0F, 0x84, null, null, null, null, 0x8B, 0x1D, null, null, null, null, 0x85, 0xDB + ]; + + // UIElement::CatchDroppedItem, the whole function: mov eax,[esp+4] / push 0 / push eax / + // push 15h / call BroadcastElementMessage / mov al,1 / ret 4. Unique, lands at 0x00461860. + private static readonly byte?[] CatchDroppedItemPattern = + [ + 0x8B, 0x44, 0x24, 0x04, 0x6A, 0x00, 0x50, 0x6A, 0x15, 0xE8, null, null, null, null, + 0xB0, 0x01, 0xC2, 0x04, 0x00 + ]; + + // UIElement_ItemList::InqDropIconInfo: mov eax,[esp+10h] / sub esp,3Ch / push ebx / push ebp / + // mov ebp,[esp+50h] / push esi / mov esi,[esp+4Ch] / xor ebx,ebx / cmp esi,ebx / push edi / + // mov edi,[esp+54h] / mov [edi],ebx / mov [ebp],ebx / mov [eax],ebx. Unique, lands at 0x004E3380. + private static readonly byte?[] InqDropIconInfoPattern = + [ + 0x8B, 0x44, 0x24, 0x10, 0x83, 0xEC, 0x3C, 0x53, 0x55, 0x8B, 0x6C, 0x24, 0x50, 0x56, + 0x8B, 0x74, 0x24, 0x4C, 0x33, 0xDB, 0x3B, 0xF3, 0x57, 0x8B, 0x7C, 0x24, 0x54, + 0x89, 0x1F, 0x89, 0x5D, 0x00, 0x89, 0x18 + ]; + + private static readonly UiHookSlot StartTooltipSlot = + UiHookRegistry.Register("StartTooltip", "UIElementManager::StartTooltip - tooltip shown", StartTooltipFallbackVa); + private static readonly UiHookSlot ResetTooltipSlot = + UiHookRegistry.Register("ResetTooltip", "UIElementManager::ResetTooltip - tooltip reset", ResetTooltipFallbackVa); + private static readonly UiHookSlot CheckTooltipSlot = + UiHookRegistry.Register("CheckTooltip", "UIElementManager::CheckTooltip - tooltip expired", CheckTooltipFallbackVa); + private static readonly UiHookSlot StartDragSlot = + UiHookRegistry.Register("StartDragandDrop", "UIElementManager::StartDragandDrop - drag started", StartDragandDropFallbackVa); + private static readonly UiHookSlot CatchDropSlot = + UiHookRegistry.Register("CatchDroppedItem", "UIElement::CatchDroppedItem - item dropped", CatchDroppedItemFallbackVa); + + private static IntPtr _origStartTooltip, _origResetTooltip, _origCheckTooltip, _origStartDrag, _origCatchDrop; + private static IntPtr _inqDropIconInfo; + private static int _initialized; + + // AC's main thread only (every detour runs there; faces draw there). + private static IntPtr _mgr; + private static bool _dead; // Client::Cleanup started: touch nothing of AC's UI + private static bool _tooltipShown; + private static IntPtr _tooltipOwner; + private static uint _tooltipObject, _tooltipSpell; + private static int _dragDepth; + private static uint _dragObject, _dragSpell; + private static int _claimed; + + public static void Initialize() + { + if (Interlocked.CompareExchange(ref _initialized, 1, 0) != 0) + return; + + if (!AcClientModule.TryReadTextSection(out AcClientTextSection text)) + { + foreach (UiHookSlot s in new[] { StartTooltipSlot, ResetTooltipSlot, CheckTooltipSlot, StartDragSlot, CatchDropSlot }) + s.Reason = "acclient.exe not available"; + RynthLog.Compat("UiElementHooks: acclient.exe not available - tooltip and drag/drop hooks left out."); + return; + } + + // Every event names its object through InqDropIconInfo: without it, none goes in. + HookResolver.ResolveResult inq = HookResolver.Resolve(text, "UiElement.InqDropIconInfo", InqDropIconInfoPattern, InqDropIconInfoFallbackVa); + if (!inq.Success) + { + foreach (UiHookSlot s in new[] { StartTooltipSlot, ResetTooltipSlot, CheckTooltipSlot, StartDragSlot, CatchDropSlot }) + s.Reason = "UIElement_ItemList::InqDropIconInfo not found (names the objects)"; + RynthLog.Compat("UiElementHooks: InqDropIconInfo not found - tooltip and drag/drop hooks left out."); + return; + } + _inqDropIconInfo = inq.Address; + + if (UiHookRegistry.SwitchedOn(StartTooltipSlot)) + { + HookResolver.ResolveResult r = HookResolver.Resolve(text, "UiElement.StartTooltip", StartTooltipPattern, StartTooltipFallbackVa); + delegate* unmanaged[Thiscall] d = &StartTooltipDetour; + if (UiHookRegistry.TryInstall(StartTooltipSlot, r, (IntPtr)d, out IntPtr t)) { _origStartTooltip = t; Thread.MemoryBarrier(); UiHookRegistry.Enable(StartTooltipSlot); } + } + if (UiHookRegistry.SwitchedOn(ResetTooltipSlot)) + { + HookResolver.ResolveResult r = HookResolver.Resolve(text, "UiElement.ResetTooltip", ResetTooltipPattern, ResetTooltipFallbackVa); + delegate* unmanaged[Thiscall] d = &ResetTooltipDetour; + if (UiHookRegistry.TryInstall(ResetTooltipSlot, r, (IntPtr)d, out IntPtr t)) { _origResetTooltip = t; Thread.MemoryBarrier(); UiHookRegistry.Enable(ResetTooltipSlot); } + } + if (UiHookRegistry.SwitchedOn(CheckTooltipSlot)) + { + HookResolver.ResolveResult r = HookResolver.Resolve(text, "UiElement.CheckTooltip", CheckTooltipPattern, CheckTooltipFallbackVa); + delegate* unmanaged[Thiscall] d = &CheckTooltipDetour; + if (UiHookRegistry.TryInstall(CheckTooltipSlot, r, (IntPtr)d, out IntPtr t)) { _origCheckTooltip = t; Thread.MemoryBarrier(); UiHookRegistry.Enable(CheckTooltipSlot); } + } + if (UiHookRegistry.SwitchedOn(StartDragSlot)) + { + HookResolver.ResolveResult r = HookResolver.Resolve(text, "UiElement.StartDragandDrop", StartDragandDropPattern, StartDragandDropFallbackVa); + delegate* unmanaged[Thiscall] d = &StartDragandDropDetour; + if (UiHookRegistry.TryInstall(StartDragSlot, r, (IntPtr)d, out IntPtr t)) { _origStartDrag = t; Thread.MemoryBarrier(); UiHookRegistry.Enable(StartDragSlot); } + } + if (UiHookRegistry.SwitchedOn(CatchDropSlot)) + { + HookResolver.ResolveResult r = HookResolver.Resolve(text, "UiElement.CatchDroppedItem", CatchDroppedItemPattern, CatchDroppedItemFallbackVa); + delegate* unmanaged[Thiscall] d = &CatchDroppedItemDetour; + if (UiHookRegistry.TryInstall(CatchDropSlot, r, (IntPtr)d, out IntPtr t)) { _origCatchDrop = t; Thread.MemoryBarrier(); UiHookRegistry.Enable(CatchDropSlot); } + } + + RynthLog.Compat($"UiElementHooks: tooltip {On(StartTooltipSlot)}/{On(ResetTooltipSlot)}/{On(CheckTooltipSlot)}, " + + $"drag {On(StartDragSlot)}, drop {On(CatchDropSlot)} (InqDropIconInfo @ 0x{_inqDropIconInfo.ToInt32():X8})."); + } + + private static string On(UiHookSlot s) => s.Installed ? "hooked" : "out"; + + // ── What plugins and faces read ───────────────────────────────────── + + /// Tooltip/drag/drop hooks a plugin can rely on (GetUiHookFlags bits 3-6). + public static bool TooltipShowLive => StartTooltipSlot.Live; + public static bool TooltipHideLive => ResetTooltipSlot.Live || CheckTooltipSlot.Live; + public static bool DragStartLive => StartDragSlot.Live; + public static bool DropLive => CatchDropSlot.Live; + + /// + /// AC's main thread: the object being dragged out of AC's UI right now, or 0. Checks + /// the UI manager's drag icon (+0x31C) so a drag that ended without a catch (let go + /// outside every element) clears too. + /// + public static uint CurrentDragObject + { + get + { + if (_dragObject == 0) + return 0; + if (_dead || _mgr == IntPtr.Zero || !MainThreadGuard.IsOnMainThread()) + return _dead ? 0 : _dragObject; + if (*(IntPtr*)(_mgr + MgrDragIcon) == IntPtr.Zero) + { + _dragObject = _dragSpell = 0; + return 0; + } + return _dragObject; + } + } + + /// The object whose tooltip AC shows, or 0 (any thread; a plain field). + public static uint CurrentTooltipObject => _tooltipShown ? _tooltipObject : 0; + + /// UiFlowHooks, leaving the world (main thread): forget tooltip/drag state; no events. + public static void OnScreenLeaving() + { + _tooltipShown = false; + _tooltipOwner = IntPtr.Zero; + _tooltipObject = _tooltipSpell = 0; + _dragObject = _dragSpell = 0; + } + + /// UiFlowHooks, Client::Cleanup (main thread): AC's UI is about to go; never touch it again. + public static void OnClientCleanup() + { + _dead = true; + _mgr = IntPtr.Zero; + OnScreenLeaving(); + } + + // ── Detours ────────────────────────────────────────────────────────── + + [UnmanagedCallersOnly(CallConvs = [typeof(CallConvThiscall)])] + private static void StartTooltipDetour(IntPtr mgr, IntPtr stringInfo, IntPtr owner, uint idTooltip, uint idLayout, uint idText) + { + ((delegate* unmanaged[Thiscall])_origStartTooltip)(mgr, stringInfo, owner, idTooltip, idLayout, idText); + if (!StartTooltipSlot.Enabled || _dead || mgr == IntPtr.Zero) + return; + try + { + _mgr = mgr; + if (*(IntPtr*)(mgr + MgrTooltipElement) == IntPtr.Zero) + return; // AC decided not to show one + IntPtr shownOwner = *(IntPtr*)(mgr + MgrTooltipOwner); + if (shownOwner == IntPtr.Zero) shownOwner = owner; + Identify(shownOwner, 2, out uint obj, out uint spell); + bool same = _tooltipShown && shownOwner == _tooltipOwner && obj == _tooltipObject && spell == _tooltipSpell; + _tooltipShown = true; + _tooltipOwner = shownOwner; + _tooltipObject = obj; + _tooltipSpell = spell; + if (same) + return; + StartTooltipSlot.Note(obj != 0 ? $"object 0x{obj:X8}" : spell != 0 ? $"spell {spell}" : "a non-item element"); + Plugins.PluginManager.QueueTooltipShown(obj, spell); + } + catch (Exception ex) + { + LogOnce("StartTooltip", ex); + } + } + + [UnmanagedCallersOnly(CallConvs = [typeof(CallConvThiscall)])] + private static void ResetTooltipDetour(IntPtr mgr) + { + ((delegate* unmanaged[Thiscall])_origResetTooltip)(mgr); + if (ResetTooltipSlot.Enabled) + AfterTooltipCheck(mgr, ResetTooltipSlot); + } + + [UnmanagedCallersOnly(CallConvs = [typeof(CallConvThiscall)])] + private static void CheckTooltipDetour(IntPtr mgr) + { + ((delegate* unmanaged[Thiscall])_origCheckTooltip)(mgr); + if (CheckTooltipSlot.Enabled) + AfterTooltipCheck(mgr, CheckTooltipSlot); + } + + // A tooltip we reported is gone when AC's tooltip element pointer is clear again. + private static void AfterTooltipCheck(IntPtr mgr, UiHookSlot slot) + { + if (!_tooltipShown || _dead || mgr == IntPtr.Zero) + return; + try + { + if (*(IntPtr*)(mgr + MgrTooltipElement) != IntPtr.Zero) + return; + uint obj = _tooltipObject; + _tooltipShown = false; + _tooltipOwner = IntPtr.Zero; + _tooltipObject = _tooltipSpell = 0; + slot.Note(obj != 0 ? $"hid object 0x{obj:X8}" : "hid"); + Plugins.PluginManager.QueueTooltipHidden(); + } + catch (Exception ex) + { + LogOnce(slot.Name, ex); + } + } + + [UnmanagedCallersOnly(CallConvs = [typeof(CallConvThiscall)])] + private static byte StartDragandDropDetour(IntPtr mgr, IntPtr element, int x, int y) + { + var original = (delegate* unmanaged[Thiscall])_origStartDrag; + byte result; + _dragDepth++; + try { result = original(mgr, element, x, y); } + finally { _dragDepth--; } + + // The original calls itself once for a drag proxy: report the outermost call only. + if (result == 0 || _dragDepth > 0 || !StartDragSlot.Enabled || _dead || mgr == IntPtr.Zero) + return result; + try + { + _mgr = mgr; + IntPtr icon = *(IntPtr*)(mgr + MgrDragIcon); + if (icon == IntPtr.Zero) + return result; + Identify(icon, 0, out uint obj, out uint spell); + if (obj == 0 && spell == 0) + Identify(element, 2, out obj, out spell); + _dragObject = obj; + _dragSpell = spell; + uint iconId = 0; + if (obj != 0) + ClientObjectHooks.TryGetObjectDataIdProperty(obj, 8 /* Icon */, out iconId); + StartDragSlot.Note(obj != 0 ? $"object 0x{obj:X8}" : spell != 0 ? $"spell {spell}" : "a non-item element"); + Plugins.PluginManager.QueueDragStarted(obj, spell, iconId); + } + catch (Exception ex) + { + LogOnce("StartDragandDrop", ex); + } + return result; + } + + [UnmanagedCallersOnly(CallConvs = [typeof(CallConvThiscall)])] + private static byte CatchDroppedItemDetour(IntPtr catcher, IntPtr dragDropInfo) + { + var original = (delegate* unmanaged[Thiscall])_origCatchDrop; + if (!CatchDropSlot.Enabled || _dead || dragDropInfo == IntPtr.Zero) + return original(catcher, dragDropInfo); + + uint obj = 0, spell = 0; + try + { + IntPtr dragged = *(IntPtr*)(dragDropInfo + DdiElement); + IntPtr owner = *(IntPtr*)(dragDropInfo + DdiOwner); + if (dragged != IntPtr.Zero) + Identify(dragged, 0, out obj, out spell); + + // An item out of an AC item list, let go over an engine panel that takes it. + if (obj != 0 && IsItemList(owner) && !IsWithin(catcher, owner) + && ImGuiBackend.UiDropTargets.TryClaim(obj, spell, out string target)) + { + Interlocked.Increment(ref _claimed); + _dragObject = _dragSpell = 0; + CatchDropSlot.Note($"object 0x{obj:X8} -> RynthCore {target} (kept from AC)"); + RynthLog.Compat($"UiElementHooks: object 0x{obj:X8} dropped on RynthCore {target}; AC's drop skipped (not caught)."); + return 0; + } + } + catch (Exception ex) + { + LogOnce("CatchDroppedItem", ex); + } + + byte result = original(catcher, dragDropInfo); + try + { + _dragObject = _dragSpell = 0; + uint targetId = catcher != IntPtr.Zero ? *(uint*)(catcher + ElementId) : 0; + CatchDropSlot.Note($"{(obj != 0 ? $"object 0x{obj:X8}" : spell != 0 ? $"spell {spell}" : "no object")} on element 0x{targetId:X8}"); + if (obj != 0 || spell != 0) + Plugins.PluginManager.QueueItemDropped(obj, spell, targetId); + } + catch (Exception ex) + { + LogOnce("CatchDroppedItem", ex); + } + return result; + } + + // ── AC UI helpers (main thread) ────────────────────────────────────── + + /// AC's InqDropIconInfo on , then up to parents. + private static void Identify(IntPtr element, int parents, out uint objectId, out uint spellId) + { + objectId = spellId = 0; + var inq = (delegate* unmanaged[Cdecl])_inqDropIconInfo; + for (int i = 0; i <= parents && element != IntPtr.Zero; i++) + { + uint item = 0, spell = 0, flags = 0; + inq(element, &item, &spell, &flags); + if (item != 0 || spell != 0) + { + objectId = item; + spellId = spell; + return; + } + element = Parent(element); + } + } + + private static IntPtr Parent(IntPtr element) + { + IntPtr vtable = *(IntPtr*)element; + var getParent = (delegate* unmanaged[Thiscall])(*(IntPtr*)(vtable + VtGetParent)); + return getParent(element); + } + + private static bool IsItemList(IntPtr element) + { + if (element == IntPtr.Zero) + return false; + IntPtr vtable = *(IntPtr*)element; + var getType = (delegate* unmanaged[Thiscall])(*(IntPtr*)(vtable + VtGetUIElementType)); + return getType(element) == UIElementTypeItemList; + } + + private static bool IsWithin(IntPtr element, IntPtr ancestor) + { + for (int i = 0; i < 32 && element != IntPtr.Zero; i++) + { + if (element == ancestor) + return true; + element = Parent(element); + } + return false; + } + + private static int _loggedErrors; + + private static void LogOnce(string where, Exception ex) + { + if (Interlocked.Increment(ref _loggedErrors) <= 5) + try { RynthLog.Compat($"UiElementHooks: {where} threw {ex.GetType().Name}: {ex.Message}"); } catch { } + } + + public static string DescribeState() + => $"UI elements: tooltip {(_tooltipShown ? (_tooltipObject != 0 ? $"on object 0x{_tooltipObject:X8}" : "shown") : "none")}, " + + $"drag {(_dragObject != 0 ? $"object 0x{_dragObject:X8}" : "none")}, {Volatile.Read(ref _claimed)} drop(s) kept for RynthCore. " + + ImGuiBackend.UiDropTargets.Describe(); +} diff --git a/src/RynthCore.Engine/Compatibility/UiFlowHooks.cs b/src/RynthCore.Engine/Compatibility/UiFlowHooks.cs new file mode 100644 index 0000000..ffebc1f --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/UiFlowHooks.cs @@ -0,0 +1,334 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/UiFlowHooks.cs +// +// Screen-mode and teardown hooks (Chorizite comparison gap #4, 2026-10-05): +// +// UIFlow::UseNewMode (fallback 0x00479AA0) void __thiscall(UIFlow*) +// AC switches screens here: intro, character select, the world, char gen, +// disconnected... It copies the pending mode (+0x90) into the current mode +// (+0x8C), destroys the old screen's UI object (+0x94) and builds the new +// one. Read offline from our client: 0x00479B13..0x00479B35 (mov [esi+8C],ecx +// from [esi+90]; old UI at +94 released with vfunc +0x24/+0x00). +// Client::Cleanup (fallback 0x004118D0) void __thiscall(Client*) +// The client's shutdown: tears down UI, net, database and preferences +// (virtual calls at its top). Called once, from gmClient::Cleanup. +// +// Events (all raised on AC's main thread): +// ScreenLeaving(old, new) - inside UseNewMode, BEFORE AC destroys the old +// screen's UI. Leaving the world, the engine drops +// every cached gameplay-UI pointer right here. +// ScreenChanged(old, new) - after AC built the new screen (plugins get +// RynthPluginOnScreenChanged on the next pump frame). +// ClientCleanup - before AC tears anything down; plugins get +// RynthPluginOnClientCleanup (bounded wait), then the +// plugin pump stops ticking and the panels stop drawing. +// +// Fallback: until the hook is live (failed to resolve, switched off), the UIFlow +// mode the engine already polls at +0x8C (CharacterManagementHooks.MainThreadTick) +// drives the same events, one tick late and without the "before" guarantee. +// ============================================================================ +using System; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading; + +namespace RynthCore.Engine.Compatibility; + +internal static unsafe class UiFlowHooks +{ + // UIFlow modes (UIFlow+0x8C), the client's own data ids. + public const int ModeNone = 0; + public const int ModeIntro = 0x10000001; + public const int ModeDisconnected = 0x10000002; + public const int ModeDataPatch = 0x10000003; + public const int ModeCredits = 0x10000005; + public const int ModeGamePlay = 0x10000008; + public const int ModeEpilogue = 0x10000009; + public const int ModeCharacterManagement = 0x1000000A; + public const int ModeCharGen = 0x1000000B; + + private const int UIFlowCurModeOffset = 0x8C; + private const int UIFlowNewModeOffset = 0x90; + + // Fallback VAs (4,841,472-byte client). Pattern-scan is the source of truth. + private const int UseNewModeFallbackVa = 0x00479AA0; + private const int ClientCleanupFallbackVa = 0x004118D0; + + // UIFlow::UseNewMode: sub esp,0x90 / push esi / mov esi,ecx / mov eax,[esi+0x90] / + // test eax,eax / jz rel32 / mov ecx,eax / xor edx,edx / div [imm32] / mov eax,[imm32]. + // The +0x90 pending-mode read and the hash-bucket div are the anchor. Unique, lands + // at 0x00479AA0 (tools/pe_pattern.py CHECK, tools/ui_hooks_check.py). + private static readonly byte?[] UseNewModePattern = + [ + 0x81, 0xEC, 0x90, 0x00, 0x00, 0x00, 0x56, 0x8B, 0xF1, 0x8B, 0x86, 0x90, 0x00, 0x00, 0x00, + 0x85, 0xC0, 0x0F, 0x84, null, null, null, null, + 0x8B, 0xC8, 0x33, 0xD2, 0xF7, 0x35, null, null, null, null, + 0xA1, null, null, null, null + ]; + + // Client::Cleanup: push esi / mov esi,ecx / mov eax,[esi] / call [eax+0x28] / call rel32 / + // mov edx,[esi] / mov ecx,esi / call [edx+0x8C] / call rel32 / mov eax,[esi] / mov ecx,esi / + // call [eax+0x84]: its run of virtual cleanups. Unique, lands at 0x004118D0. + private static readonly byte?[] ClientCleanupPattern = + [ + 0x56, 0x8B, 0xF1, 0x8B, 0x06, 0xFF, 0x50, 0x28, 0xE8, null, null, null, null, + 0x8B, 0x16, 0x8B, 0xCE, 0xFF, 0x92, 0x8C, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, + 0x8B, 0x06, 0x8B, 0xCE, 0xFF, 0x90, 0x84, 0x00, 0x00, 0x00 + ]; + + private static readonly UiHookSlot UseNewModeSlot = + UiHookRegistry.Register("UseNewMode", "UIFlow::UseNewMode - screen changes", UseNewModeFallbackVa); + private static readonly UiHookSlot CleanupSlot = + UiHookRegistry.Register("ClientCleanup", "Client::Cleanup - client teardown", ClientCleanupFallbackVa); + + private static IntPtr _originalUseNewMode; + private static IntPtr _originalCleanup; + private static int _initialized; + + private static int _mode; // current UIFlow mode as last observed (0 = not known yet) + private static int _previousMode; + private static int _changes; + private static string _lastSource = "none"; + private static int _cleanupStarted; + private static int _useNewModeDepth; + + /// AC's main thread, inside UseNewMode before the old screen's UI is destroyed (hook only). + public static event Action? ScreenLeaving; + /// AC's main thread, after the new screen was built (hook) or on the next tick (poll fallback). + public static event Action? ScreenChanged; + /// AC's main thread, before Client::Cleanup runs. Once. + public static event Action? ClientCleanup; + + /// The UIFlow mode as last observed; 0 until the first observation. + public static int CurrentMode => Volatile.Read(ref _mode); + public static int PreviousMode => Volatile.Read(ref _previousMode); + + /// True while AC shows the world, or while the mode isn't known yet (no change + /// from the old behaviour then). Gate cached-AC-UI-pointer use on this. + public static bool InWorldOrUnknown + { + get + { + int m = Volatile.Read(ref _mode); + return m == ModeNone || m == ModeGamePlay; + } + } + + /// Client::Cleanup has started: AC is tearing its UI down. Never cleared. + public static bool ClientCleanupStarted => Volatile.Read(ref _cleanupStarted) != 0; + + /// The UseNewMode detour is installed and switched on (else the poll drives the events). + public static bool ScreenHookLive => UseNewModeSlot.Live; + public static bool CleanupHookLive => CleanupSlot.Live; + + public static void Initialize() + { + if (Interlocked.CompareExchange(ref _initialized, 1, 0) != 0) + return; + + if (!AcClientModule.TryReadTextSection(out AcClientTextSection text)) + { + UseNewModeSlot.Reason = CleanupSlot.Reason = "acclient.exe not available"; + RynthLog.Compat("UiFlowHooks: acclient.exe not available - screen-mode and cleanup hooks left out (the mode poll stays)."); + return; + } + + if (UiHookRegistry.SwitchedOn(UseNewModeSlot)) + { + HookResolver.ResolveResult r = HookResolver.Resolve(text, "UiFlow.UseNewMode", UseNewModePattern, UseNewModeFallbackVa); + delegate* unmanaged[Thiscall] detour = &UseNewModeDetour; + if (UiHookRegistry.TryInstall(UseNewModeSlot, r, (IntPtr)detour, out IntPtr tramp)) + { + _originalUseNewMode = tramp; + Thread.MemoryBarrier(); + UiHookRegistry.Enable(UseNewModeSlot); + } + } + + if (UiHookRegistry.SwitchedOn(CleanupSlot)) + { + HookResolver.ResolveResult r = HookResolver.Resolve(text, "UiFlow.ClientCleanup", ClientCleanupPattern, ClientCleanupFallbackVa); + delegate* unmanaged[Thiscall] detour = &ClientCleanupDetour; + if (UiHookRegistry.TryInstall(CleanupSlot, r, (IntPtr)detour, out IntPtr tramp)) + { + _originalCleanup = tramp; + Thread.MemoryBarrier(); + UiHookRegistry.Enable(CleanupSlot); + } + } + + RynthLog.Compat($"UiFlowHooks: UseNewMode {(UseNewModeSlot.Installed ? "hooked" : "not hooked (" + UseNewModeSlot.Reason + ") - the +0x8C poll drives screen events")}, " + + $"Client::Cleanup {(CleanupSlot.Installed ? "hooked" : "not hooked (" + CleanupSlot.Reason + ")")}."); + } + + // ── Detours ────────────────────────────────────────────────────────── + + [UnmanagedCallersOnly(CallConvs = [typeof(CallConvThiscall)])] + private static void UseNewModeDetour(IntPtr uiFlow) + { + var original = (delegate* unmanaged[Thiscall])_originalUseNewMode; + if (!UseNewModeSlot.Enabled || uiFlow == IntPtr.Zero || _useNewModeDepth > 0) + { + original(uiFlow); + return; + } + + int oldMode = 0, pending = 0; + bool read = false; + try + { + MainThreadGuard.RecordIfFirst(); + oldMode = *(int*)(uiFlow + UIFlowCurModeOffset); + pending = *(int*)(uiFlow + UIFlowNewModeOffset); + read = true; + // AC destroys the old screen's UI inside the original: drop what points into it first. + if (pending != 0 && pending != oldMode) + RaiseLeaving(oldMode, pending, "hook"); + } + catch (Exception ex) + { + try { RynthLog.Compat($"UiFlowHooks: UseNewMode pre-step threw {ex.GetType().Name}: {ex.Message}"); } catch { } + } + + _useNewModeDepth++; + try { original(uiFlow); } + finally { _useNewModeDepth--; } + + if (!read) + return; + try + { + int newMode = *(int*)(uiFlow + UIFlowCurModeOffset); + if (newMode != oldMode) + Observe(oldMode, newMode, "hook"); + else if (Volatile.Read(ref _mode) == ModeNone && newMode != ModeNone) + Volatile.Write(ref _mode, newMode); + } + catch (Exception ex) + { + try { RynthLog.Compat($"UiFlowHooks: UseNewMode post-step threw {ex.GetType().Name}: {ex.Message}"); } catch { } + } + } + + [UnmanagedCallersOnly(CallConvs = [typeof(CallConvThiscall)])] + private static void ClientCleanupDetour(IntPtr client) + { + var original = (delegate* unmanaged[Thiscall])_originalCleanup; + if (CleanupSlot.Enabled) + { + try { RaiseCleanup(); } + catch (Exception ex) + { + try { RynthLog.Compat($"UiFlowHooks: Client::Cleanup pre-step threw {ex.GetType().Name}: {ex.Message}"); } catch { } + } + } + original(client); + } + + // ── Poll fallback ──────────────────────────────────────────────────── + + /// + /// AC's main thread (CharacterManagementHooks.MainThreadTick): the UIFlow mode it just + /// read at +0x8C. Seeds the mode; when the UseNewMode hook isn't live, a change here + /// raises the screen events instead (after the fact: the old screen is already gone). + /// + public static void OnModePolled(int mode) + { + int known = Volatile.Read(ref _mode); + if (mode == known) + return; + if (known == ModeNone || UseNewModeSlot.Live) + { + // Seed (late attach, hot reload). With the hook live a difference here means the + // hook missed a change (it was switched off for a while): correct it quietly. + Volatile.Write(ref _mode, mode); + return; + } + try + { + RaiseLeaving(known, mode, "poll"); + Observe(known, mode, "poll"); + } + catch (Exception ex) + { + RynthLog.Compat($"UiFlowHooks: poll fallback threw {ex.GetType().Name}: {ex.Message}"); + } + } + + // ── Raising ────────────────────────────────────────────────────────── + + private static void RaiseLeaving(int oldMode, int newMode, string source) + { + if (oldMode == ModeGamePlay) + OnLeavingWorld(); + try { ScreenLeaving?.Invoke(oldMode, newMode); } + catch (Exception ex) { RynthLog.Compat($"UiFlowHooks: ScreenLeaving handler threw {ex.GetType().Name}: {ex.Message}"); } + } + + /// + /// Leaving the world: AC is about to free gmGamePlayUI and every panel in it. The + /// engine's per-frame users of cached panel pointers (EndScene TickHide for chat, + /// radar, powerbar, retail vitals) run on this same thread, so clearing them here + /// closes the window the pump-thread logout dispatch left open (it clears them a + /// frame or more later). Idempotent: the logout dispatch clears them again. + /// + private static void OnLeavingWorld() + { + try { ChatHooks.ResetCachedInstance(); } catch { } + try { RadarHooks.ResetCachedInstance(); } catch { } + try { PowerbarHooks.ResetCachedInstance(); } catch { } + try { RetailVitalsHooks.ResetCachedInstance(); } catch { } + try { UiElementHooks.OnScreenLeaving(); } catch { } + } + + private static void Observe(int oldMode, int newMode, string source) + { + Volatile.Write(ref _previousMode, oldMode); + Volatile.Write(ref _mode, newMode); + Interlocked.Increment(ref _changes); + _lastSource = source; + string note = $"{ModeName(oldMode)} -> {ModeName(newMode)} ({source})"; + UseNewModeSlot.LastNote = note; + if (source == "hook") Interlocked.Increment(ref UseNewModeSlot.Fired); + RynthLog.Compat($"UiFlowHooks: screen {note}."); + + try { ScreenChanged?.Invoke(oldMode, newMode); } + catch (Exception ex) { RynthLog.Compat($"UiFlowHooks: ScreenChanged handler threw {ex.GetType().Name}: {ex.Message}"); } + try { Plugins.PluginManager.QueueScreenChanged(oldMode, newMode); } + catch (Exception ex) { RynthLog.Compat($"UiFlowHooks: queueing OnScreenChanged threw {ex.GetType().Name}: {ex.Message}"); } + } + + private static void RaiseCleanup() + { + if (Interlocked.Exchange(ref _cleanupStarted, 1) != 0) + return; + CleanupSlot.Note("Client::Cleanup entered"); + RynthLog.Compat("UiFlowHooks: Client::Cleanup - the client is tearing down; telling plugins, then stopping plugin ticks and panels."); + try { UiElementHooks.OnClientCleanup(); } catch { } + try { ClientCleanup?.Invoke(); } + catch (Exception ex) { RynthLog.Compat($"UiFlowHooks: ClientCleanup handler threw {ex.GetType().Name}: {ex.Message}"); } + try { Plugins.PluginManager.DispatchClientCleanup(500); } + catch (Exception ex) { RynthLog.Compat($"UiFlowHooks: plugin cleanup dispatch threw {ex.GetType().Name}: {ex.Message}"); } + } + + // ── Status ─────────────────────────────────────────────────────────── + + public static string ModeName(int mode) => mode switch + { + ModeNone => "unknown", + ModeIntro => "Intro", + ModeDisconnected => "Disconnected", + ModeDataPatch => "DataPatch", + ModeCredits => "Credits", + ModeGamePlay => "World", + ModeEpilogue => "Epilogue", + ModeCharacterManagement => "CharacterSelect", + ModeCharGen => "CharGen", + _ => $"0x{mode:X8}", + }; + + public static string DescribeState() + => $"Screen: {ModeName(CurrentMode)} (before: {ModeName(PreviousMode)}), {Volatile.Read(ref _changes)} change(s), last via {_lastSource}; " + + $"driven by {(UseNewModeSlot.Live ? "the UseNewMode hook" : "the +0x8C poll (fallback)")}; " + + $"client cleanup {(ClientCleanupStarted ? "STARTED" : "not started")}."; +} diff --git a/src/RynthCore.Engine/Compatibility/UiHookRegistry.cs b/src/RynthCore.Engine/Compatibility/UiHookRegistry.cs new file mode 100644 index 0000000..83e75f7 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/UiHookRegistry.cs @@ -0,0 +1,215 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/UiHookRegistry.cs +// +// Status and kill switches for the UI hooks of 2026-10-05 (Chorizite gaps #4 +// and #5): UiFlowHooks (UIFlow::UseNewMode, Client::Cleanup) and UiElementHooks +// (tooltip start/reset/check, drag start, item drop). +// +// Every hook has its own switch, two ways: +// - engine.json "DisabledUiHooks": ["StartTooltip", ...] - not installed at +// the next start (EngineSettings.IsUiHookEnabled); +// - /rc hooks off - the detour turns into a plain pass-through at +// once (it still calls AC's original), and the name is saved to +// engine.json for the next start. /rc hooks on undoes both. +// /rc hooks (alone) lists every hook: address, how it was found, on/off, +// how many times it fired and the last thing it saw. +// +// A hook that fails to resolve or install logs once (HookResolver / +// TryInstall) and stays out: its slot says why, and nothing else changes. +// ============================================================================ +using System; +using System.Collections.Generic; +using System.Threading; +using RynthCore.Engine.Plugins; + +namespace RynthCore.Engine.Compatibility; + +internal sealed class UiHookSlot +{ + public UiHookSlot(string name, string what, int fallbackVa) + { + Name = name; + What = what; + FallbackVa = fallbackVa; + } + + /// The switch name (engine.json DisabledUiHooks, /rc hooks on|off). + public string Name { get; } + /// The AC function, for people. + public string What { get; } + public int FallbackVa { get; } + + public IntPtr Address; + /// "pattern", "fallback", or empty when not installed. + public string Source = string.Empty; + public bool Installed; + /// Why it isn't installed ("off in engine.json", "pattern and fallback both failed", ...). + public string Reason = "not probed yet"; + public int Fired; + public string LastNote = string.Empty; + + private int _enabled = 1; + /// Runtime switch: false = the detour only calls AC's original. + public bool Enabled + { + get => Volatile.Read(ref _enabled) != 0; + set => Volatile.Write(ref _enabled, value ? 1 : 0); + } + + /// Installed and switched on: the detour does its work. + public bool Live => Installed && Enabled; + + public void Note(string note) + { + Interlocked.Increment(ref Fired); + LastNote = note; + } + + public string Describe() + { + string state = Installed + ? (Enabled ? "on" : "OFF (pass-through)") + : "not installed: " + Reason; + string addr = Installed ? $"0x{Address.ToInt32():X8} via {Source}" : $"(fallback 0x{FallbackVa:X8})"; + string last = LastNote.Length > 0 ? $" last: {LastNote}" : string.Empty; + return $"{Name} [{What}] {addr} - {state}; fired {Fired}x.{last}"; + } +} + +internal static class UiHookRegistry +{ + private static readonly List Slots = new(); + private static readonly object Sync = new(); + + public static UiHookSlot Register(string name, string what, int fallbackVa) + { + lock (Sync) + { + foreach (UiHookSlot s in Slots) + if (string.Equals(s.Name, name, StringComparison.OrdinalIgnoreCase)) + return s; + var slot = new UiHookSlot(name, what, fallbackVa); + Slots.Add(slot); + return slot; + } + } + + public static UiHookSlot? Find(string name) + { + lock (Sync) + { + foreach (UiHookSlot s in Slots) + if (string.Equals(s.Name, name, StringComparison.OrdinalIgnoreCase)) + return s; + } + return null; + } + + public static List All() + { + lock (Sync) return new List(Slots); + } + + /// + /// The engine.json switch, checked before resolving (so a switched-off hook leaves + /// no HookResolver line): false = leave the hook out; the slot says why. + /// + public static bool SwitchedOn(UiHookSlot slot) + { + if (EngineSettings.IsUiHookEnabled(slot.Name)) + return true; + slot.Reason = "off in engine.json (DisabledUiHooks)"; + slot.Enabled = false; + RynthLog.Compat($"UiHooks: {slot.Name} switched off in engine.json - not installed."); + return false; + } + + /// + /// Installs one UI hook from its HookResolver result: the Decal guard, then MinHook + /// (created, not yet enabled: the caller stores the trampoline, then calls Enable). + /// Never throws; on any failure the slot says why and the caller leaves the hook out. + /// is AC's original. + /// + public static bool TryInstall(UiHookSlot slot, HookResolver.ResolveResult resolved, IntPtr detour, out IntPtr trampoline) + { + trampoline = IntPtr.Zero; + try + { + if (!resolved.Success) + { + slot.Reason = "pattern and fallback address both failed (see the HookResolver line)"; + return false; + } + + // A Decal client on its first engine load: a pattern miss there means someone + // else (Decal, a Decal plugin) already patched the prologue. Don't stack on it. + // (A hot reload misses the pattern too, on our own stub, and installs as usual.) + if (resolved.Source == HookResolver.ResolveSource.FallbackVa + && DecalBridgeHost.Active && EntryPoint.InitCount < 2) + { + slot.Reason = "pattern missed in a Decal client (prologue already patched?) - left out"; + RynthLog.Compat($"UiHooks: {slot.Name} - pattern missed with Decal in the process; not hooking over someone else's patch."); + return false; + } + + trampoline = Hooking.MinHook.HookCreate(resolved.Address, detour); + Thread.MemoryBarrier(); + slot.Address = resolved.Address; + slot.Source = resolved.Source == HookResolver.ResolveSource.PatternScan ? "pattern" : "fallback"; + slot.Installed = true; + slot.Reason = string.Empty; + return true; + } + catch (Exception ex) + { + trampoline = IntPtr.Zero; + slot.Installed = false; + slot.Reason = $"install threw {ex.GetType().Name}: {ex.Message}"; + RynthLog.Compat($"UiHooks: {slot.Name} install threw {ex.GetType().Name}: {ex.Message} - left out."); + return false; + } + } + + /// Enables a hook TryInstall created (after the caller stored the trampoline). + public static bool Enable(UiHookSlot slot) + { + try + { + Hooking.MinHook.Enable(slot.Address); + RynthLog.Compat($"UiHooks: {slot.Name} ready @ 0x{slot.Address.ToInt32():X8} ({slot.Source})."); + return true; + } + catch (Exception ex) + { + slot.Installed = false; + slot.Reason = $"enable threw {ex.GetType().Name}: {ex.Message}"; + RynthLog.Compat($"UiHooks: {slot.Name} enable threw {ex.GetType().Name}: {ex.Message} - left out."); + return false; + } + } + + /// /rc hooks on|off <name>: runtime pass-through plus engine.json for the next start. + public static string SetEnabled(string name, bool enabled) + { + UiHookSlot? slot = Find(name); + if (slot == null) + return $"No UI hook called '{name}'. Names: {string.Join(", ", All().ConvertAll(s => s.Name))}."; + EngineSettings.SetUiHookEnabled(slot.Name, enabled); + slot.Enabled = enabled; + if (enabled && !slot.Installed) + return $"{slot.Name}: switched on in engine.json; it installs at the next client start."; + return enabled + ? $"{slot.Name}: on (now, and at the next start)." + : $"{slot.Name}: off - passes straight to AC now, and isn't installed at the next start."; + } + + public static List DescribeLines() + { + var lines = new List(); + foreach (UiHookSlot s in All()) + lines.Add(s.Describe()); + lines.Add(UiFlowHooks.DescribeState()); + lines.Add(UiElementHooks.DescribeState()); + return lines; + } +} diff --git a/src/RynthCore.Engine/D3D9/EndSceneHook.cs b/src/RynthCore.Engine/D3D9/EndSceneHook.cs index 4f40c7a..e572bdf 100644 --- a/src/RynthCore.Engine/D3D9/EndSceneHook.cs +++ b/src/RynthCore.Engine/D3D9/EndSceneHook.cs @@ -327,14 +327,21 @@ internal static class EndSceneHook _renderCount++; _frameCount++; - // Per-frame chatbox visibility assertion (no-op unless plugin enables suppression). - try { ChatHooks.TickHide(); } catch { /* never let this bring down EndScene */ } - // Per-frame retail-radar visibility assertion (no-op unless plugin enables suppression). - try { RadarHooks.TickHide(); } catch { /* never let this bring down EndScene */ } - // Per-frame retail-powerbar visibility assertion (no-op unless plugin enables suppression). - try { PowerbarHooks.TickHide(); } catch { /* never let this bring down EndScene */ } - // Per-frame retail health/stamina/mana bars visibility ("Hide retail vitals"). - try { RetailVitalsHooks.TickHide(); } catch { /* never let this bring down EndScene */ } + // These four call into gameplay-UI panels they cached (gmMainChatUI, the radar, the + // powerbar, the vitals bars). AC frees those when it leaves the world; outside the + // world (UiFlowHooks: a screen change seen by the UseNewMode hook or the mode poll) + // they don't run. Mode not known yet = as before. + if (UiFlowHooks.InWorldOrUnknown && !UiFlowHooks.ClientCleanupStarted) + { + // Per-frame chatbox visibility assertion (no-op unless plugin enables suppression). + try { ChatHooks.TickHide(); } catch { /* never let this bring down EndScene */ } + // Per-frame retail-radar visibility assertion (no-op unless plugin enables suppression). + try { RadarHooks.TickHide(); } catch { /* never let this bring down EndScene */ } + // Per-frame retail-powerbar visibility assertion (no-op unless plugin enables suppression). + try { PowerbarHooks.TickHide(); } catch { /* never let this bring down EndScene */ } + // Per-frame retail health/stamina/mana bars visibility ("Hide retail vitals"). + try { RetailVitalsHooks.TickHide(); } catch { /* never let this bring down EndScene */ } + } if (_renderCount == 1 && _offscreenFilterDisabled && _skipCount > 0) { diff --git a/src/RynthCore.Engine/EngineLifecycle.cs b/src/RynthCore.Engine/EngineLifecycle.cs index 0d1ac0d..1f619e2 100644 --- a/src/RynthCore.Engine/EngineLifecycle.cs +++ b/src/RynthCore.Engine/EngineLifecycle.cs @@ -173,6 +173,7 @@ internal static class EngineLifecycle // The chat log is written on the tick pump (UiDataHub), now stopped. Left open, // it outlived this generation and locked the next one out of the file. Step("ChatModel.CloseLog", () => UI.Data.ChatModel.CloseLog()); + Step("ServerMessageStream.Shutdown", () => Net.ServerMessageStream.Shutdown()); Step("PluginManager.ShutdownAll (defensive)", () => PluginManager.ShutdownAll()); diff --git a/src/RynthCore.Engine/EntryPoint.cs b/src/RynthCore.Engine/EntryPoint.cs index 1939e93..6c56e0e 100644 --- a/src/RynthCore.Engine/EntryPoint.cs +++ b/src/RynthCore.Engine/EntryPoint.cs @@ -102,6 +102,10 @@ public static class EntryPoint [UnmanagedCallersOnly(EntryPoint = "RynthCoreShutdown")] public static uint Shutdown(IntPtr lpParam) { + // Only the loader's hot reload calls this export (process exit and the engine's own + // teardowns call EngineLifecycle.Shutdown directly), on its reload thread: wait here, + // with the game running on this engine, while a plugin says a reload now would hurt. + try { DeferReloadWhilePluginsObject(); } catch { } try { EngineLifecycle.Shutdown(); @@ -117,6 +121,39 @@ public static class EntryPoint } } + // The shell's ERl button: a reload asked for by hand isn't held for the plugins. Only the + // reload that follows within ManualReloadWindowMs counts (a refused or coalesced signal + // must not exempt the next file-watcher reload). + private static long _manualReloadAtMs; + private const long ManualReloadWindowMs = 10_000; + internal static void NoteManualReload() => Interlocked.Exchange(ref _manualReloadAtMs, Environment.TickCount64); + + /// + /// Reload deferral (2026-10-05, see ReloadDeferral.cs): asks the plugins + /// (RynthPluginReloadBlocker) and waits up to ReloadDeferral.DefaultCap while one objects, + /// e.g. "engine reload waiting: RynthAi in combat (a monster engaged, ...)". Says so in chat + /// once. Never throws; a query that fails counts as "nothing objects". + /// + private static void DeferReloadWhilePluginsObject() + { + long manualAt = Interlocked.Exchange(ref _manualReloadAtMs, 0); + if (manualAt != 0 && Environment.TickCount64 - manualAt < ManualReloadWindowMs) + { + RynthLog.Info("engine reload: asked for by hand (ERl), so it isn't deferred for the plugins."); + return; + } + var deferral = new ReloadDeferral + { + Query = PluginManager.QueryReloadBlockers, + Log = msg => RynthLog.Info(msg), + Notify = why => Compatibility.AcMainThreadQueue.EnqueueWriteToChat( + $"[RynthCore] A new RynthCore build is ready. It loads when this is clear: {why} (at most {ReloadDeferral.DefaultCap.TotalMinutes:0} minutes).", 1), + }; + ReloadDeferral.Outcome outcome = deferral.Run(out TimeSpan waited); + if (outcome != ReloadDeferral.Outcome.Clear) + RynthLog.Info($"engine reload: deferral {outcome} after {waited.TotalSeconds:0.0} s."); + } + private static uint InitializeCore(IntPtr lpParam) { if (Interlocked.CompareExchange(ref _initialized, 1, 0) != 0) @@ -716,6 +753,12 @@ public static class EntryPoint Step("raw packet hooks", RawPacketHooks.Initialize); Step("property-update hooks", PropertyUpdateHooks.Initialize); Step("auto-id service", AutoIdService.Start); + // Screen-mode + client-teardown hooks (UIFlow::UseNewMode, Client::Cleanup) and + // AC's tooltip / drag / drop (2026-10-05, Chorizite gaps #4-#5). Each hook has its + // own switch (engine.json DisabledUiHooks, /rc hooks); one that doesn't resolve + // stays out and says why in /rc hooks. + Step("UI flow hooks", UiFlowHooks.Initialize); + Step("UI element hooks", UiElementHooks.Initialize); // Bridge mode: wait (bounded) for the bridge's hello. In Auto mode a bridge that // never shows up means the old coexistence mode: install what was skipped. if (bridgeSkipped != null && !DecalBridgeHost.WaitForBridge(InitAborted)) diff --git a/src/RynthCore.Engine/ImGui/EngineFrameController.cs b/src/RynthCore.Engine/ImGui/EngineFrameController.cs index 9461e55..50cafa3 100644 --- a/src/RynthCore.Engine/ImGui/EngineFrameController.cs +++ b/src/RynthCore.Engine/ImGui/EngineFrameController.cs @@ -521,6 +521,10 @@ internal static class EngineFrameController if (Compatibility.DecalBridgeHost.Active) Compatibility.DecalBridgeHost.Drain(); PluginManager.ProcessPendingActions(pluginContext, device, _gameHwnd); + // Client::Cleanup started (UiFlowHooks): the call above told the plugins; from + // here on no plugin tick and no plugin export for the panels' data. + if (Compatibility.UiFlowHooks.ClientCleanupStarted) + return; PluginManager.FlushPendingDeletes(); // closes the create→delete race window PluginManager.TickAll(); // Panel data: plugin exports for the UI are called here, on the same @@ -537,6 +541,21 @@ internal static class EngineFrameController } } + /// + /// Runs on the calling thread while no plugin pump frame runs, + /// holding the pump's frame guard so it can't start one meanwhile. False (not run) when a + /// frame is running. For Client::Cleanup (UiFlowHooks): AC's main thread tells the + /// plugins itself when the pump is idle or no longer running frames. + /// + internal static bool TryRunOutsidePumpFrame(Action action) + { + if (System.Threading.Interlocked.CompareExchange(ref _pluginPumpInFrame, 1, 0) != 0) + return false; + try { action(); } + finally { System.Threading.Interlocked.Exchange(ref _pluginPumpInFrame, 0); } + return true; + } + /// True when anything ImGui should be drawn this frame. private static bool HasImGuiContent() { @@ -556,9 +575,13 @@ internal static class EngineFrameController /// /// Panel faces show only in the world, like the Avalonia overlay (hidden - /// between characters, not closed). + /// between characters, not closed). Also off as soon as AC leaves the world screen + /// (UiFlowHooks, before the logout dispatch catches up) and for good once + /// Client::Cleanup starts. /// - private static bool PanelsLive => Compatibility.LoginLifecycleHooks.HasObservedLoginComplete; + private static bool PanelsLive => Compatibility.LoginLifecycleHooks.HasObservedLoginComplete + && Compatibility.UiFlowHooks.InWorldOrUnknown + && !Compatibility.UiFlowHooks.ClientCleanupStarted; /// DPI scale the fonts and style were built for (see Init). private static float _uiScale = 1f; diff --git a/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs b/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs index feceed4..a0a83d6 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiPopOuts.cs @@ -123,6 +123,17 @@ internal static unsafe class ImGuiPopOuts /// The pop-out typing into a text box, or null (for the input log). AC thread. public static string? TextFocusTitle => _keyboard is { WantTextInput: true } k ? k.Title : null; + /// + /// True when the cursor is over 's pop-out window right now + /// (UiDropTargets: an AC item released over a popped-out panel). AC thread. + /// + public static bool IsCursorOver(string title) + { + if (!Pops.TryGetValue(title, out PopOut? pop) || pop.Window == null || pop.Window.Hwnd == IntPtr.Zero) + return false; + return GetCursorPos(out POINT cursor) && WindowFromPoint(cursor) == pop.Window.Hwnd; + } + /// The screen position of the game window's client origin (to place a pop-out where the docked panel was). public static Vector2 ClientOriginOnScreen() { diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHud.cs b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHud.cs index 5a077ee..326ba6f 100644 --- a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHud.cs +++ b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHud.cs @@ -858,9 +858,12 @@ internal static class MonsterHud const float margin = 60f; if (MonsterHudSettings.KeepOnScreen) { - // Pinned to the edge: room above the anchor for the name, bar and debuff row (a label: the name). - Vector2 c = ClampToScreen(ref f, sx, sy, (label ? 50f : 70f) * f.UiScale * userScale, - (label ? 22f : 56f) * f.UiScale * userScale); + // Pinned to the edge: room above the anchor for the name, bar and debuff row (a label: the name), + // grown with the plate type's bar / text size. + float sideMul = label ? LabelTextSize(p.Kind) : MathF.Max(MonsterHudSettings.MonsterBarWidth, MonsterHudSettings.MonsterTextSize); + float topMul = label ? LabelTextSize(p.Kind) : MathF.Max(MonsterHudSettings.MonsterBarHeight, MonsterHudSettings.MonsterTextSize); + Vector2 c = ClampToScreen(ref f, sx, sy, (label ? 50f : 70f) * f.UiScale * userScale * sideMul, + (label ? 22f : 56f) * f.UiScale * userScale * topMul); p.Anchor = new Vector2(MathF.Round(c.X), MathF.Round(c.Y)); p.OnScreen = true; } @@ -1004,7 +1007,7 @@ internal static class MonsterHud if (p.IsLabel) { // Name only: the same bold bake as a monster's name, no bar, badge or icons. - p.NameSize = MathF.Round(ImGuiFonts.Get(UiFont.UiBold11).FontSize * s); + p.NameSize = MathF.Round(ImGuiFonts.Get(UiFont.UiBold11).FontSize * s * LabelTextSize(p.Kind)); p.NameFont = ImGuiFonts.Sharp(p.NameSize, bold: true); p.NameW = TextWidth(p.NameFont, p.NameSize, p.Name); p.BadgeW = 0f; @@ -1016,14 +1019,17 @@ internal static class MonsterHud return; } - p.BarW = MathF.Round(112f * k); - p.BarH = MathF.Round((MonsterHudSettings.ShowHpNumbers ? 12f : 7f) * k); + // Bar width / height and text size each have their own multiplier (1 = the default look). + float text = MonsterHudSettings.MonsterTextSize; + p.BarW = MathF.Round(112f * k * MonsterHudSettings.MonsterBarWidth); + p.BarH = MathF.Round((MonsterHudSettings.ShowHpNumbers ? 12f : 7f) * k * MonsterHudSettings.MonsterBarHeight); // Sizes follow the 11 px bold / 9 px regular bakes; the font drawn is the smallest bake at // least that big, so a scaled-up plate shrinks a bigger bake instead of stretching (blur). - p.NameSize = MathF.Round(ImGuiFonts.Get(UiFont.UiBold11).FontSize * s); + // Picking a baked font per size: nothing is re-baked when a text size changes. + p.NameSize = MathF.Round(ImGuiFonts.Get(UiFont.UiBold11).FontSize * s * text); p.NameFont = ImGuiFonts.Sharp(p.NameSize, bold: true); - p.SmallSize = MathF.Round(ImGuiFonts.Get(UiFont.Ui9).FontSize * s); + p.SmallSize = MathF.Round(ImGuiFonts.Get(UiFont.Ui9).FontSize * s * text); p.SmallFont = ImGuiFonts.Sharp(p.SmallSize, bold: false); p.NameW = MonsterHudSettings.ShowNames && p.Name.Length > 0 ? TextWidth(p.NameFont, p.NameSize, p.Name) : 0f; @@ -1039,11 +1045,15 @@ internal static class MonsterHud float nameH = (p.NameW > 0 || p.BadgeW > 0) ? p.NameSize + 2f * k : 0f; // The weak pill (left) and distance (right) hang off the bar's ends: keep them // inside the crowd-avoidance box, symmetric so the plate stays centred. - float side = (p.Weak != null || MonsterHudSettings.ShowDistance) ? 2f * 30f * k : 0f; + float side = (p.Weak != null || MonsterHudSettings.ShowDistance) ? 2f * 30f * k * text : 0f; p.Width = MathF.Max(p.BarW + side, nameLine) + 8f * k; p.Height = nameH + p.BarH + p.BelowBar; } + /// A name label's text size: players' or NPCs' (vendors count as NPCs). + private static float LabelTextSize(byte kind) => + kind == RadarKind.Player ? MonsterHudSettings.PlayerTextSize : MonsterHudSettings.NpcTextSize; + /// Screen rect of a plate at a given upward nudge: (x0, y0, x1, y1). private static Vector4 RectAt(Plate p, float nudge, float uiScale) { diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettings.cs b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettings.cs index 0777b5e..9c599f3 100644 --- a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettings.cs +++ b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettings.cs @@ -102,6 +102,21 @@ internal static class MonsterHudSettings public static bool GainLum = true; public static bool GainRadiance = true; + // Per-plate-type sizing (2026-10-05), multipliers on today's look (1 = unchanged), applied on + // top of Scale. Bar width / height and the text drawn in or over the plate, each on its own. + // NPC and player names are name-only labels (no bar), so they only have a text size. + /// Monster plates: the health bar's width and height, and their text (name, level, HP, weak-to, distance). + public static float MonsterBarWidth = 1.0f, MonsterBarHeight = 1.0f, MonsterTextSize = 1.0f; + /// Name labels over NPCs and vendors. + public static float NpcTextSize = 1.0f; + /// Name labels over other players. + public static float PlayerTextSize = 1.0f; + /// Your own plate: the three bars' width and height, and their text (cur / max numbers, your name). + public static float SelfBarWidth = 1.0f, SelfBarHeight = 1.0f, SelfTextSize = 1.0f; + public const float MinBarWidth = 0.5f, MaxBarWidth = 2.5f; + public const float MinBarHeight = 0.5f, MaxBarHeight = 3.0f; + public const float MinTextSize = 0.5f, MaxTextSize = 2.0f; + // ── Ranges (shared by the Settings face, the command and Load) ────── public const float MinDistance = 5f, MaxDistanceLimit = 120f; public const int MinPlates = 1, MaxPlatesLimit = 60; @@ -137,74 +152,88 @@ internal static class MonsterHudSettings { string path = FilePath; if (!File.Exists(path)) return; - foreach (string raw in File.ReadAllLines(path)) - { - string line = raw.Trim(); - if (line.Length == 0 || line.StartsWith('#')) continue; - int eq = line.IndexOf('='); - if (eq <= 0) continue; - string key = line[..eq].Trim(); - string val = line[(eq + 1)..].Trim(); - switch (key) - { - case "enabled": Enabled = val == "1"; break; - case "maxDistance": if (TryF(val, out float d)) MaxDistance = Math.Clamp(d, MinDistance, MaxDistanceLimit); break; - case "maxPlates": - if (int.TryParse(val, NumberStyles.Integer, CultureInfo.InvariantCulture, out int n)) - MaxPlates = Math.Clamp(n, MinPlates, MaxPlatesLimit); - break; - case "filter": Filter = val.Equals("engaged", StringComparison.OrdinalIgnoreCase) ? PlateFilter.Engaged : PlateFilter.All; break; - case "showNames": ShowNames = val == "1"; break; - case "showHp": ShowHpNumbers = val == "1"; break; - case "showDistance": ShowDistance = val == "1"; break; - case "showLevel": ShowLevel = val == "1"; break; - case "showWeakness": ShowWeakness = val == "1"; break; - case "fade": FadeWithDistance = val == "1"; break; - case "scale": if (TryF(val, out float s)) Scale = Math.Clamp(s, MinScale, MaxScale); break; - case "opacity": if (TryF(val, out float o)) Opacity = Math.Clamp(o, MinOpacity, MaxOpacity); break; - case "clickSelect": ClickToSelect = val == "1"; break; - case "heightLift": if (TryF(val, out float h)) HeightLift = Math.Clamp(h, MinLift, MaxLift); break; - case "npcNames": NpcNames = val == "1"; break; - case "npcDistance": if (TryF(val, out float nd)) NpcMaxDistance = Math.Clamp(nd, MinNpcDistance, MaxNpcDistanceLimit); break; - case "npcMax": - if (int.TryParse(val, NumberStyles.Integer, CultureInfo.InvariantCulture, out int nm)) - MaxNpcLabels = Math.Clamp(nm, MinNpcLabels, MaxNpcLabelsLimit); - break; - case "playerNames": PlayerNames = val == "1"; break; - case "showDebuffs": ShowDebuffs = val == "1"; break; - case "showOthersDebuff": ShowOthersDebuff = val == "1"; break; - case "selfPlate": SelfPlate = val == "1"; break; - case "selfNumbers": SelfNumbers = val == "1"; break; - case "selfName": SelfName = val == "1"; break; - case "selfHideFirstPerson": SelfHideFirstPerson = val == "1"; break; - case "selfPlacement": SelfPlacement = val.Equals("follow", StringComparison.OrdinalIgnoreCase) ? SelfPlacement.Follow : SelfPlacement.Fixed; break; - case "selfLocked": SelfLocked = val == "1"; break; - case "selfFixedX": if (TryF(val, out float fx)) SelfFixedX = Math.Clamp(fx, 0f, 1f); break; - case "selfFixedY": if (TryF(val, out float fy)) SelfFixedY = Math.Clamp(fy, 0f, 1f); break; - case "numbers": Numbers = val == "1"; break; - case "numDealt": NumDealt = val == "1"; break; - case "numTaken": NumTaken = val == "1"; break; - case "numHeals": NumHeals = val == "1"; break; - case "numKills": NumKills = val == "1"; break; - case "keepOnScreen": KeepOnScreen = val == "1"; break; - case "numRestores": NumRestores = val == "1"; break; - case "numSize": if (TryF(val, out float ns)) NumSize = Math.Clamp(ns, MinNumSize, MaxNumSize); break; - case "numTime": if (TryF(val, out float nt)) NumTime = Math.Clamp(nt, MinNumTime, MaxNumTime); break; - case "selfPosition": if (Enum.TryParse(val, true, out SelfPlatePosition sp)) SelfPosition = sp; break; - case "gainSize": if (TryF(val, out float gs)) GainSize = Math.Clamp(gs, MinNumSize, MaxNumSize); break; - case "gainTime": if (TryF(val, out float gt)) GainTime = Math.Clamp(gt, MinNumTime, MaxNumTime); break; - case "gains": Gains = val == "1"; break; - case "gainXp": GainXp = val == "1"; break; - case "gainLum": GainLum = val == "1"; break; - case "gainRadiance": GainRadiance = val == "1"; break; - } - } + ApplyLines(File.ReadAllLines(path)); } catch { /* best-effort: defaults stay */ } finally { _loaded = true; } } } + /// Applies the file's key=value lines (unknown keys and bad values are skipped). Also the tests' entry. + internal static void ApplyLines(string[] lines) + { + foreach (string raw in lines) + { + string line = raw.Trim(); + if (line.Length == 0 || line.StartsWith('#')) continue; + int eq = line.IndexOf('='); + if (eq <= 0) continue; + string key = line[..eq].Trim(); + string val = line[(eq + 1)..].Trim(); + switch (key) + { + case "enabled": Enabled = val == "1"; break; + case "maxDistance": if (TryF(val, out float d)) MaxDistance = Math.Clamp(d, MinDistance, MaxDistanceLimit); break; + case "maxPlates": + if (int.TryParse(val, NumberStyles.Integer, CultureInfo.InvariantCulture, out int n)) + MaxPlates = Math.Clamp(n, MinPlates, MaxPlatesLimit); + break; + case "filter": Filter = val.Equals("engaged", StringComparison.OrdinalIgnoreCase) ? PlateFilter.Engaged : PlateFilter.All; break; + case "showNames": ShowNames = val == "1"; break; + case "showHp": ShowHpNumbers = val == "1"; break; + case "showDistance": ShowDistance = val == "1"; break; + case "showLevel": ShowLevel = val == "1"; break; + case "showWeakness": ShowWeakness = val == "1"; break; + case "fade": FadeWithDistance = val == "1"; break; + case "scale": if (TryF(val, out float s)) Scale = Math.Clamp(s, MinScale, MaxScale); break; + case "opacity": if (TryF(val, out float o)) Opacity = Math.Clamp(o, MinOpacity, MaxOpacity); break; + case "clickSelect": ClickToSelect = val == "1"; break; + case "heightLift": if (TryF(val, out float h)) HeightLift = Math.Clamp(h, MinLift, MaxLift); break; + case "npcNames": NpcNames = val == "1"; break; + case "npcDistance": if (TryF(val, out float nd)) NpcMaxDistance = Math.Clamp(nd, MinNpcDistance, MaxNpcDistanceLimit); break; + case "npcMax": + if (int.TryParse(val, NumberStyles.Integer, CultureInfo.InvariantCulture, out int nm)) + MaxNpcLabels = Math.Clamp(nm, MinNpcLabels, MaxNpcLabelsLimit); + break; + case "playerNames": PlayerNames = val == "1"; break; + case "showDebuffs": ShowDebuffs = val == "1"; break; + case "showOthersDebuff": ShowOthersDebuff = val == "1"; break; + case "selfPlate": SelfPlate = val == "1"; break; + case "selfNumbers": SelfNumbers = val == "1"; break; + case "selfName": SelfName = val == "1"; break; + case "selfHideFirstPerson": SelfHideFirstPerson = val == "1"; break; + case "selfPlacement": SelfPlacement = val.Equals("follow", StringComparison.OrdinalIgnoreCase) ? SelfPlacement.Follow : SelfPlacement.Fixed; break; + case "selfLocked": SelfLocked = val == "1"; break; + case "selfFixedX": if (TryF(val, out float fx)) SelfFixedX = Math.Clamp(fx, 0f, 1f); break; + case "selfFixedY": if (TryF(val, out float fy)) SelfFixedY = Math.Clamp(fy, 0f, 1f); break; + case "numbers": Numbers = val == "1"; break; + case "numDealt": NumDealt = val == "1"; break; + case "numTaken": NumTaken = val == "1"; break; + case "numHeals": NumHeals = val == "1"; break; + case "numKills": NumKills = val == "1"; break; + case "keepOnScreen": KeepOnScreen = val == "1"; break; + case "numRestores": NumRestores = val == "1"; break; + case "numSize": if (TryF(val, out float ns)) NumSize = Math.Clamp(ns, MinNumSize, MaxNumSize); break; + case "numTime": if (TryF(val, out float nt)) NumTime = Math.Clamp(nt, MinNumTime, MaxNumTime); break; + case "selfPosition": if (Enum.TryParse(val, true, out SelfPlatePosition sp)) SelfPosition = sp; break; + case "gainSize": if (TryF(val, out float gs)) GainSize = Math.Clamp(gs, MinNumSize, MaxNumSize); break; + case "gainTime": if (TryF(val, out float gt)) GainTime = Math.Clamp(gt, MinNumTime, MaxNumTime); break; + case "gains": Gains = val == "1"; break; + case "gainXp": GainXp = val == "1"; break; + case "gainLum": GainLum = val == "1"; break; + case "gainRadiance": GainRadiance = val == "1"; break; + case "monsterBarWidth": if (TryF(val, out float mbw)) MonsterBarWidth = Math.Clamp(mbw, MinBarWidth, MaxBarWidth); break; + case "monsterBarHeight": if (TryF(val, out float mbh)) MonsterBarHeight = Math.Clamp(mbh, MinBarHeight, MaxBarHeight); break; + case "monsterTextSize": if (TryF(val, out float mts)) MonsterTextSize = Math.Clamp(mts, MinTextSize, MaxTextSize); break; + case "npcTextSize": if (TryF(val, out float nts)) NpcTextSize = Math.Clamp(nts, MinTextSize, MaxTextSize); break; + case "playerTextSize": if (TryF(val, out float pts)) PlayerTextSize = Math.Clamp(pts, MinTextSize, MaxTextSize); break; + case "selfBarWidth": if (TryF(val, out float sbw)) SelfBarWidth = Math.Clamp(sbw, MinBarWidth, MaxBarWidth); break; + case "selfBarHeight": if (TryF(val, out float sbh)) SelfBarHeight = Math.Clamp(sbh, MinBarHeight, MaxBarHeight); break; + case "selfTextSize": if (TryF(val, out float sts)) SelfTextSize = Math.Clamp(sts, MinTextSize, MaxTextSize); break; + } + } + } + private static bool TryF(string s, out float v) => float.TryParse(s, NumberStyles.Float, CultureInfo.InvariantCulture, out v); /// Writes the settings in the background. Any thread. @@ -220,56 +249,70 @@ internal static class MonsterHudSettings string? dir = Path.GetDirectoryName(path); if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); using var sw = new StreamWriter(path, append: false); - sw.WriteLine("# RynthCore monster nameplates - auto-generated, hand-edits OK. /rc plates in game."); - sw.WriteLine($"enabled={B(Enabled)}"); - sw.WriteLine(FormattableString.Invariant($"maxDistance={MaxDistance:0.#}")); - sw.WriteLine(FormattableString.Invariant($"maxPlates={MaxPlates}")); - sw.WriteLine($"filter={(Filter == PlateFilter.Engaged ? "engaged" : "all")}"); - sw.WriteLine($"showNames={B(ShowNames)}"); - sw.WriteLine($"showHp={B(ShowHpNumbers)}"); - sw.WriteLine($"showDistance={B(ShowDistance)}"); - sw.WriteLine($"showLevel={B(ShowLevel)}"); - sw.WriteLine($"showWeakness={B(ShowWeakness)}"); - sw.WriteLine($"fade={B(FadeWithDistance)}"); - sw.WriteLine(FormattableString.Invariant($"scale={Scale:0.##}")); - sw.WriteLine(FormattableString.Invariant($"opacity={Opacity:0.##}")); - sw.WriteLine(FormattableString.Invariant($"heightLift={HeightLift:0.##}")); - sw.WriteLine($"clickSelect={B(ClickToSelect)}"); - sw.WriteLine($"npcNames={B(NpcNames)}"); - sw.WriteLine(FormattableString.Invariant($"npcDistance={NpcMaxDistance:0.#}")); - sw.WriteLine(FormattableString.Invariant($"npcMax={MaxNpcLabels}")); - sw.WriteLine($"playerNames={B(PlayerNames)}"); - sw.WriteLine($"showDebuffs={B(ShowDebuffs)}"); - sw.WriteLine($"showOthersDebuff={B(ShowOthersDebuff)}"); - sw.WriteLine($"selfPlate={B(SelfPlate)}"); - sw.WriteLine($"selfNumbers={B(SelfNumbers)}"); - sw.WriteLine($"selfName={B(SelfName)}"); - sw.WriteLine($"selfHideFirstPerson={B(SelfHideFirstPerson)}"); - sw.WriteLine($"selfPlacement={(SelfPlacement == SelfPlacement.Follow ? "follow" : "fixed")}"); - sw.WriteLine($"selfLocked={B(SelfLocked)}"); - sw.WriteLine(FormattableString.Invariant($"selfFixedX={SelfFixedX:0.####}")); - sw.WriteLine(FormattableString.Invariant($"selfFixedY={SelfFixedY:0.####}")); - sw.WriteLine($"numbers={B(Numbers)}"); - sw.WriteLine($"numDealt={B(NumDealt)}"); - sw.WriteLine($"numTaken={B(NumTaken)}"); - sw.WriteLine($"numHeals={B(NumHeals)}"); - sw.WriteLine($"numKills={B(NumKills)}"); - sw.WriteLine($"keepOnScreen={B(KeepOnScreen)}"); - sw.WriteLine($"numRestores={B(NumRestores)}"); - sw.WriteLine(FormattableString.Invariant($"numSize={NumSize:0.##}")); - sw.WriteLine(FormattableString.Invariant($"numTime={NumTime:0.##}")); - sw.WriteLine(FormattableString.Invariant($"gainSize={GainSize:0.##}")); - sw.WriteLine($"selfPosition={SelfPosition}"); - sw.WriteLine(FormattableString.Invariant($"gainTime={GainTime:0.##}")); - sw.WriteLine($"gains={B(Gains)}"); - sw.WriteLine($"gainXp={B(GainXp)}"); - sw.WriteLine($"gainLum={B(GainLum)}"); - sw.WriteLine($"gainRadiance={B(GainRadiance)}"); + WriteAll(sw); } catch { /* non-fatal */ } } } + /// Every setting as the file's key=value lines. Also the tests' entry. + internal static void WriteAll(TextWriter sw) + { + sw.WriteLine("# RynthCore monster nameplates - auto-generated, hand-edits OK. /rc plates in game."); + sw.WriteLine($"enabled={B(Enabled)}"); + sw.WriteLine(FormattableString.Invariant($"maxDistance={MaxDistance:0.#}")); + sw.WriteLine(FormattableString.Invariant($"maxPlates={MaxPlates}")); + sw.WriteLine($"filter={(Filter == PlateFilter.Engaged ? "engaged" : "all")}"); + sw.WriteLine($"showNames={B(ShowNames)}"); + sw.WriteLine($"showHp={B(ShowHpNumbers)}"); + sw.WriteLine($"showDistance={B(ShowDistance)}"); + sw.WriteLine($"showLevel={B(ShowLevel)}"); + sw.WriteLine($"showWeakness={B(ShowWeakness)}"); + sw.WriteLine($"fade={B(FadeWithDistance)}"); + sw.WriteLine(FormattableString.Invariant($"scale={Scale:0.##}")); + sw.WriteLine(FormattableString.Invariant($"opacity={Opacity:0.##}")); + sw.WriteLine(FormattableString.Invariant($"heightLift={HeightLift:0.##}")); + sw.WriteLine($"clickSelect={B(ClickToSelect)}"); + sw.WriteLine($"npcNames={B(NpcNames)}"); + sw.WriteLine(FormattableString.Invariant($"npcDistance={NpcMaxDistance:0.#}")); + sw.WriteLine(FormattableString.Invariant($"npcMax={MaxNpcLabels}")); + sw.WriteLine($"playerNames={B(PlayerNames)}"); + sw.WriteLine($"showDebuffs={B(ShowDebuffs)}"); + sw.WriteLine($"showOthersDebuff={B(ShowOthersDebuff)}"); + sw.WriteLine($"selfPlate={B(SelfPlate)}"); + sw.WriteLine($"selfNumbers={B(SelfNumbers)}"); + sw.WriteLine($"selfName={B(SelfName)}"); + sw.WriteLine($"selfHideFirstPerson={B(SelfHideFirstPerson)}"); + sw.WriteLine($"selfPlacement={(SelfPlacement == SelfPlacement.Follow ? "follow" : "fixed")}"); + sw.WriteLine($"selfLocked={B(SelfLocked)}"); + sw.WriteLine(FormattableString.Invariant($"selfFixedX={SelfFixedX:0.####}")); + sw.WriteLine(FormattableString.Invariant($"selfFixedY={SelfFixedY:0.####}")); + sw.WriteLine($"numbers={B(Numbers)}"); + sw.WriteLine($"numDealt={B(NumDealt)}"); + sw.WriteLine($"numTaken={B(NumTaken)}"); + sw.WriteLine($"numHeals={B(NumHeals)}"); + sw.WriteLine($"numKills={B(NumKills)}"); + sw.WriteLine($"keepOnScreen={B(KeepOnScreen)}"); + sw.WriteLine($"numRestores={B(NumRestores)}"); + sw.WriteLine(FormattableString.Invariant($"numSize={NumSize:0.##}")); + sw.WriteLine(FormattableString.Invariant($"numTime={NumTime:0.##}")); + sw.WriteLine(FormattableString.Invariant($"gainSize={GainSize:0.##}")); + sw.WriteLine($"selfPosition={SelfPosition}"); + sw.WriteLine(FormattableString.Invariant($"gainTime={GainTime:0.##}")); + sw.WriteLine($"gains={B(Gains)}"); + sw.WriteLine($"gainXp={B(GainXp)}"); + sw.WriteLine($"gainLum={B(GainLum)}"); + sw.WriteLine($"gainRadiance={B(GainRadiance)}"); + sw.WriteLine(FormattableString.Invariant($"monsterBarWidth={MonsterBarWidth:0.##}")); + sw.WriteLine(FormattableString.Invariant($"monsterBarHeight={MonsterBarHeight:0.##}")); + sw.WriteLine(FormattableString.Invariant($"monsterTextSize={MonsterTextSize:0.##}")); + sw.WriteLine(FormattableString.Invariant($"npcTextSize={NpcTextSize:0.##}")); + sw.WriteLine(FormattableString.Invariant($"playerTextSize={PlayerTextSize:0.##}")); + sw.WriteLine(FormattableString.Invariant($"selfBarWidth={SelfBarWidth:0.##}")); + sw.WriteLine(FormattableString.Invariant($"selfBarHeight={SelfBarHeight:0.##}")); + sw.WriteLine(FormattableString.Invariant($"selfTextSize={SelfTextSize:0.##}")); + } + private static string B(bool v) => v ? "1" : "0"; /// Back to the defaults (and saved). Render / chat thread. @@ -286,9 +329,24 @@ internal static class MonsterHudSettings NumSize = 1.0f; NumTime = 1.0f; NumRestores = true; KeepOnScreen = true; GainSize = 1.0f; GainTime = 1.0f; SelfPosition = SelfPlatePosition.Above; Gains = true; GainXp = true; GainLum = true; GainRadiance = true; + ResetSizesNoSave(); Save(); } + /// Every plate type's bar and text size back to 1 (and saved). Render / chat thread. + public static void ResetSizes() + { + ResetSizesNoSave(); + Save(); + } + + private static void ResetSizesNoSave() + { + MonsterBarWidth = 1.0f; MonsterBarHeight = 1.0f; MonsterTextSize = 1.0f; + NpcTextSize = 1.0f; PlayerTextSize = 1.0f; + SelfBarWidth = 1.0f; SelfBarHeight = 1.0f; SelfTextSize = 1.0f; + } + /// The fixed plate back to its default spot (and saved). Render / chat thread. public static void ResetSelfPosition() { @@ -314,7 +372,10 @@ internal static class MonsterHudSettings $"self {OnOff(SelfPlate)} ({(SelfPlacement == SelfPlacement.Fixed ? "fixed on screen, " + (SelfLocked ? "locked" : "unlocked") : "follows you, " + SelfPosition.ToString().ToLowerInvariant())}, " + $"numbers {OnOff(SelfNumbers)}, name {OnOff(SelfName)}, hide in first person {OnOff(SelfHideFirstPerson)}); " + $"combat text {OnOff(Numbers)} (dealt {OnOff(NumDealt)}, taken {OnOff(NumTaken)}, heals {OnOff(NumHeals)}, kills {OnOff(NumKills)}); " + - $"gains {OnOff(Gains)} (xp {OnOff(GainXp)}, lum {OnOff(GainLum)}, radiance {OnOff(GainRadiance)})."); + $"gains {OnOff(Gains)} (xp {OnOff(GainXp)}, lum {OnOff(GainLum)}, radiance {OnOff(GainRadiance)}); " + + $"sizes: monster bar {MonsterBarWidth:0.##}x{MonsterBarHeight:0.##} text {MonsterTextSize:0.##}, " + + $"NPC text {NpcTextSize:0.##}, player text {PlayerTextSize:0.##}, " + + $"your bars {SelfBarWidth:0.##}x{SelfBarHeight:0.##} text {SelfTextSize:0.##}."); private static string OnOff(bool v) => v ? "on" : "off"; } diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettingsUi.cs b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettingsUi.cs index 01e3023..38be361 100644 --- a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettingsUi.cs +++ b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettingsUi.cs @@ -68,6 +68,12 @@ internal static class MonsterHudSettingsUi changed |= Toggle("Weak-to element", ref MonsterHudSettings.ShowWeakness, "What the monster takes most damage from, from RynthAi's Damage data (needs RynthAi)."); changed |= Toggle("Distance", ref MonsterHudSettings.ShowDistance, null); + changed |= SizeSlider("Bar width", ref MonsterHudSettings.MonsterBarWidth, MonsterHudSettings.MinBarWidth, MonsterHudSettings.MaxBarWidth, w, + "How wide a monster's health bar is (1.00x = the default). On top of Look > Scale."); + changed |= SizeSlider("Bar height", ref MonsterHudSettings.MonsterBarHeight, MonsterHudSettings.MinBarHeight, MonsterHudSettings.MaxBarHeight, w, + "How tall (thick) a monster's health bar is (1.00x = the default). HP numbers need a bar at least 9 px tall."); + changed |= SizeSlider("Text size", ref MonsterHudSettings.MonsterTextSize, MonsterHudSettings.MinTextSize, MonsterHudSettings.MaxTextSize, w, + "The monster plate's text: name, level badge, HP numbers, weak-to pill and distance (1.00x = the default)."); Section("Names over NPCs and players", w); changed |= Toggle("NPC names", ref MonsterHudSettings.NpcNames, @@ -77,8 +83,12 @@ internal static class MonsterHudSettingsUi MonsterHudSettings.MinNpcDistance, MonsterHudSettings.MaxNpcDistanceLimit, "%.0f", w); changed |= SliderI("Max names", ref MonsterHudSettings.MaxNpcLabels, MonsterHudSettings.MinNpcLabels, MonsterHudSettings.MaxNpcLabelsLimit, w); + changed |= SizeSlider("NPC name size", ref MonsterHudSettings.NpcTextSize, MonsterHudSettings.MinTextSize, MonsterHudSettings.MaxTextSize, w, + "Text size of the names over NPCs and vendors (1.00x = the default). Names have no bar."); changed |= Toggle("Player names", ref MonsterHudSettings.PlayerNames, "The name over other players too (blue), within the same distance and count. Chat: /rv plates players."); + changed |= SizeSlider("Player name size", ref MonsterHudSettings.PlayerTextSize, MonsterHudSettings.MinTextSize, MonsterHudSettings.MaxTextSize, w, + "Text size of the names over other players (1.00x = the default). Names have no bar."); Note("Names count apart from the monster plates, so they never push one out; the nearest win.", w); Section("Debuffs", w); @@ -94,6 +104,12 @@ internal static class MonsterHudSettingsUi "Your own health, stamina and mana bars: fixed on screen, or following your character. Chat: /rv plates self."); changed |= Toggle("Numbers on your bars", ref MonsterHudSettings.SelfNumbers, "\"cur / max\" inside each bar (taller bars).", sub: true); changed |= Toggle("Your name", ref MonsterHudSettings.SelfName, null, sub: true); + changed |= SizeSlider("Your bar width", ref MonsterHudSettings.SelfBarWidth, MonsterHudSettings.MinBarWidth, MonsterHudSettings.MaxBarWidth, w, + "How wide your health, stamina and mana bars are (1.00x = the default)."); + changed |= SizeSlider("Your bar height", ref MonsterHudSettings.SelfBarHeight, MonsterHudSettings.MinBarHeight, MonsterHudSettings.MaxBarHeight, w, + "How tall (thick) each of your bars is (1.00x = the default). The numbers need a bar at least 8 px tall."); + changed |= SizeSlider("Your text size", ref MonsterHudSettings.SelfTextSize, MonsterHudSettings.MinTextSize, MonsterHudSettings.MaxTextSize, w, + "Your plate's text: the cur / max numbers and your name (1.00x = the default)."); bool fixedOn = MonsterHudSettings.SelfPlacement == SelfPlacement.Fixed; if (Toggle("Fixed on screen", ref fixedOn, @@ -151,6 +167,14 @@ internal static class MonsterHudSettingsUi changed |= Toggle("Fade and shrink with distance", ref MonsterHudSettings.FadeWithDistance, null); ImGuiNET.ImGui.Dummy(new Vector2(0, 8)); + if (SmallButton("Reset bar and text sizes")) + { + MonsterHudSettings.ResetSizes(); // saves + changed = false; + } + if (ImGuiNET.ImGui.IsItemHovered()) + ImGuiNET.ImGui.SetTooltip("Every plate type's bar width, bar height and text size back to 1.00x."); + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); if (SmallButton("Reset all to defaults")) { MonsterHudSettings.ResetToDefaults(); @@ -238,6 +262,15 @@ internal static class MonsterHudSettingsUi return EndSliderRow(changed); } + /// A size multiplier slider ("1.00x" = the default look) with a tooltip. Labels are the ids: keep them unique. + private static bool SizeSlider(string label, ref float value, float min, float max, float w, string tip) + { + BeginSliderRow(label, w); + bool changed = ImGuiNET.ImGui.SliderFloat("##v", ref value, min, max, "%.2fx", ImGuiSliderFlags.AlwaysClamp); + if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(tip); + return EndSliderRow(changed); + } + private static bool SliderI(string label, ref int value, int min, int max, float w) { BeginSliderRow(label, w); diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/PlayerPlate.cs b/src/RynthCore.Engine/ImGui/MonsterHud/PlayerPlate.cs index c1779e5..dc4136d 100644 --- a/src/RynthCore.Engine/ImGui/MonsterHud/PlayerPlate.cs +++ b/src/RynthCore.Engine/ImGui/MonsterHud/PlayerPlate.cs @@ -280,15 +280,18 @@ internal static class PlayerPlate float k = l.K = MonsterHudSettings.Scale * uiScale; bool numbers = l.Numbers = MonsterHudSettings.SelfNumbers; // With numbers on, the bars grow to fit bold, outlined text that reads over any fill. - l.BarW = MathF.Round((numbers ? 124f : 96f) * k); - l.BarH = MathF.Round((numbers ? 15f : 5f) * k); + // Width, height and text each have their own multiplier on top (1 = the default look). + l.BarW = MathF.Round((numbers ? 124f : 96f) * k * MonsterHudSettings.SelfBarWidth); + l.BarH = MathF.Round((numbers ? 15f : 5f) * k * MonsterHudSettings.SelfBarHeight); l.Gap = MathF.Max(2f, MathF.Round(2f * k)); l.Round = MathF.Max(1f, 1.5f * k); - // Sized from the 11 px bold bake, drawn from the smallest bake at least that big (no blur when scaled up). - l.SmallSize = MathF.Round(ImGuiFonts.Get(UiFont.UiBold11).FontSize * MonsterHudSettings.Scale); + // Sized from the 11 px bold bake, drawn from the smallest bake at least that big (no blur when scaled up; + // nothing is re-baked when the text size changes). + float text = MonsterHudSettings.Scale * MonsterHudSettings.SelfTextSize; + l.SmallSize = MathF.Round(ImGuiFonts.Get(UiFont.UiBold11).FontSize * text); l.Small = ImGuiFonts.Sharp(l.SmallSize, bold: true); l.BlockH = 3 * l.BarH + 2 * l.Gap; - l.NameSize = MathF.Round(ImGuiFonts.Get(UiFont.UiBold11).FontSize * MonsterHudSettings.Scale); + l.NameSize = MathF.Round(ImGuiFonts.Get(UiFont.UiBold11).FontSize * text); l.NameFont = ImGuiFonts.Sharp(l.NameSize, bold: true); l.NameH = MonsterHudSettings.SelfName ? l.NameSize + 3f * k : 0f; return l; @@ -358,7 +361,9 @@ internal static class PlayerPlate float tw = MonsterHud.TextWidth(font, size, text); var pos = new Vector2(MathF.Round(left + (w - tw) * 0.5f), MathF.Round(top + (h - size) * 0.5f)); // A dark band behind the text, then an outline, so it reads over bright and dark fills alike. - dl.AddRectFilled(new Vector2(pos.X - 3f, top + 1f), new Vector2(pos.X + tw + 3f, top + h - 1f), MonsterHud.Mul(0x70000000u, a), 2f); + // (Text sized bigger than the bar: the band grows to the text.) + dl.AddRectFilled(new Vector2(pos.X - 3f, MathF.Min(top + 1f, pos.Y)), new Vector2(pos.X + tw + 3f, MathF.Max(top + h - 1f, pos.Y + size)), + MonsterHud.Mul(0x70000000u, a), 2f); MonsterHud.OutlinedText(dl, font, size, pos, a, text); dl.AddText(font, size, pos, MonsterHud.Mul(NumCol, a), text); } diff --git a/src/RynthCore.Engine/ImGui/Panels/LootAddDialog.cs b/src/RynthCore.Engine/ImGui/Panels/LootAddDialog.cs index 34b14fc..0c77514 100644 --- a/src/RynthCore.Engine/ImGui/Panels/LootAddDialog.cs +++ b/src/RynthCore.Engine/ImGui/Panels/LootAddDialog.cs @@ -7,6 +7,9 @@ // // item its name and the profile the rule goes to // match name + class (default), name only, items like this +// T11 "Include T11 attributes": also require the item's T11 tier, +// grade, damage %, modifiers, slot special and Cast on Strike, +// each at least this item's (any match; 2026-10-07) // action Keep, Keep # (with the count), Salvage, Sell, Read // name the rule's name (empty: RynthAi's default, "Keep Copper Pea") // preview the rule in words, where it goes in the list and why, notes @@ -48,6 +51,7 @@ internal sealed class LootAddDialog // What the popup asks for (0 / -1 = RynthAi's default). private int _match, _action, _keep = -1; + private bool _includeT11; private readonly byte[] _name = new byte[128]; private int _keepEdit = 1; @@ -88,6 +92,7 @@ internal sealed class LootAddDialog _match = 0; _action = 0; _keep = -1; + _includeT11 = false; Array.Clear(_name); _draft = null; _adding = false; @@ -113,7 +118,7 @@ internal sealed class LootAddDialog Item = new LootEditItemRequestDto { ItemId = _itemId, Match = _match, Action = _action, KeepCount = _keep, - RuleName = Utf8(_name).Trim(), ToOpenProfile = _toOpenProfile, Seq = _seq, + RuleName = Utf8(_name).Trim(), ToOpenProfile = _toOpenProfile, IncludeT11 = _includeT11, Seq = _seq, }, }); } @@ -255,6 +260,24 @@ internal sealed class LootAddDialog if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(MatchTips[i]); } + // T11 attributes. Shown for every item: a non-T11 item answers with a note saying so. + bool t11 = _includeT11; + if (ImGuiNET.ImGui.Checkbox("Include T11 attributes##la_t11", ref t11)) + { + _includeT11 = t11; + changed = true; + } + if (ImGuiNET.ImGui.IsItemHovered()) + ImGuiNET.ImGui.SetTooltip( + "Also require this item's T11 tier, weapon grade, damage %, every modifier, slot special\n" + + "and Cast on Strike, each at least as good as this one. Works with any match.\n" + + "Not added: Can Wield (depends on your character) and Zone Locked (depends on where it was assessed)."); + if (!d.IsT11) + { + ImGuiNET.ImGui.SameLine(); + ImGuiNET.ImGui.TextDisabled("(not a T11 item)"); + } + // Action. ImGuiNET.ImGui.TextDisabled("Action:"); for (int i = 0; i < ActionIds.Length; i++) diff --git a/src/RynthCore.Engine/ImGui/Panels/LootEditorFace.cs b/src/RynthCore.Engine/ImGui/Panels/LootEditorFace.cs index e013cf7..f7fca3a 100644 --- a/src/RynthCore.Engine/ImGui/Panels/LootEditorFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/LootEditorFace.cs @@ -205,6 +205,7 @@ internal sealed class LootEditorFace : IImGuiPanel else RuleView(origin, size, w); } End(origin, size); + AcceptAcDrops(origin, size); _lootAdd.Draw(); // An item rule added to the open profile: show it (the state already carries it and its Focus). if (_lootAdd.TakeAdded() && _mode == Mode.List && _state != null && _state.Focus >= 0 && _state.Focus < _state.Rules.Count) @@ -212,6 +213,39 @@ internal sealed class LootEditorFace : IImGuiPanel _picker.Draw(); } + // ── Drop an item from AC's own inventory on the editor (2026-10-05) ── + // Compatibility/UiElementHooks keeps a drop over this body from AC (AC's own + // "not caught" path, the item stays put) and hands the item here; it opens the + // same "Add to loot profile" popup as "Add selected item", for that item. + + private const string DropKey = "LootEditor"; + + private void AcceptAcDrops(Vector2 origin, Vector2 size) + { + LootEditStateDto? s = _state; + bool can = !_unavailable && s != null && s.Path.Length > 0 && !s.Dirty + && (!s.ReadOnly || s.Format == "json") && !_lootAdd.IsOpen; + UiDropTargets.Publish(DropKey, Title, origin, origin + size, can); + + if (UiDropTargets.TryTake(DropKey, out uint itemId) && can) + { + Compatibility.ClientObjectHooks.TryGetObjectName(itemId, out string name); + _lootAdd.Open(itemId, name ?? string.Empty, toOpenProfile: true); + } + + // While AC drags an item: show that letting go here adds a rule. + if (!can || Compatibility.UiElementHooks.CurrentDragObject == 0) + return; + bool over = UiDropTargets.IsCursorOver(DropKey); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + dl.AddRect(origin + new Vector2(1, 1), origin + size - new Vector2(1, 1), over ? Green : Teal, 4, ImDrawFlags.None, over ? 3f : 1.5f); + string hint = over ? "Let go: add a loot rule for this item" : "Drop an item here to add a loot rule"; + Vector2 ts = ImGuiNET.ImGui.CalcTextSize(hint); + Vector2 at = new(origin.X + (size.X - ts.X) * 0.5f, origin.Y + size.Y - ts.Y - 10); + dl.AddRectFilled(at - new Vector2(6, 3), at + ts + new Vector2(6, 3), ShellBg, 4); + dl.AddText(at, over ? Green : Teal, hint); + } + private void RequestOpen(string path) { if (_state != null && _state.Dirty && path.Length > 0 && !SamePath(path, _state.Path)) diff --git a/src/RynthCore.Engine/ImGui/Panels/NavFace.cs b/src/RynthCore.Engine/ImGui/Panels/NavFace.cs index ef81989..36d4235 100644 --- a/src/RynthCore.Engine/ImGui/Panels/NavFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/NavFace.cs @@ -2,21 +2,27 @@ // RynthCore.Engine - ImGui/Panels/NavFace.cs // ImGui face of the Nav panel (UI/Panels/NavPanel.cs): active nav + status, // Start/Stop, route type and insert mode, the Breadcrumbs and Route overlay -// toggles, Add Waypoint / Portal (not yet) / -// Recall / Clear / Save / Dungeon Patrol, a chat waypoint, Save As, the nav -// file picker, the nav point reach (RynthAi's FollowNavMin, the same row as -// Settings > Navigation), and the waypoint list (click selects the insert -// point, X deletes, => marks the active one). +// toggles, Add Waypoint / Portal (selected object) / +// Recall / Clear / Save / Dungeon Patrol, the route editor (move / duplicate / +// delete / set active / move here on the selection; nearest, reverse, snap to +// path, point at selection, pause, simplify; recording and trail -> route), +// a chat waypoint, Save As, the nav file picker, the nav point reach +// (RynthAi's FollowNavMin, the same row as Settings > Navigation), and the +// waypoint list (click selects, Ctrl/Shift-click multi-selects, double-click +// sets active, right-click edits, X or Delete deletes, => marks the active one). // // Data: UiSources.Nav (hub) and NavCommands. Button actions change a private // copy at once; the plugin applies commands immediately, so the next -// snapshot (requested right after) replaces the copy. The reach row reads -// UiSources.Settings and saves through SettingsCommands, like the Settings face. +// snapshot (requested right after) replaces the copy. Edits send indices into +// the route this face shows, so the selection is remapped locally as the copy +// changes. The reach row reads UiSources.Settings and saves through +// SettingsCommands, like the Settings face. // ============================================================================ using System; using System.Collections.Generic; using System.Globalization; +using System.Linq; using System.Numerics; using ImGuiNET; using RynthCore.Engine.UI.Data; @@ -29,7 +35,7 @@ internal sealed class NavFace : IImGuiPanel public const string Title = "Nav"; public static void Register() => ImGuiPanelHost.Register(Title, - new PanelSpec(new Vector2(400, 560), new Vector2(360, 380), EdgeToEdge: true), + new PanelSpec(new Vector2(400, 680), new Vector2(360, 440), EdgeToEdge: true), () => new NavFace()); private static readonly string[] Actions = @@ -39,12 +45,30 @@ internal sealed class NavFace : IImGuiPanel }; private const string StartNav = PhosphorIcons.Play + " Start Navigation", StopNav = PhosphorIcons.Stop + " Stop Navigation"; private const string AddChat = PhosphorIcons.Plus + " Add Chat", SaveAs = PhosphorIcons.FloppyDisk + " Save As"; - private static readonly bool[] ActionsEnabled = { true, false, true, true, true, true }; + + // Route editor rows. Edit acts on the selected waypoints; Tools on the route. + private static readonly string[] EditActions = + { + PhosphorIcons.ArrowUp + " Up", PhosphorIcons.ArrowDown + " Down", PhosphorIcons.Copy + " Duplicate", + PhosphorIcons.Trash + " Delete", PhosphorIcons.Target + " Set Active", PhosphorIcons.Crosshair + " Move Here", + }; + private static readonly string[] ToolActions = + { + PhosphorIcons.NavigationArrow + " Nearest", PhosphorIcons.ArrowsClockwise + " Reverse", PhosphorIcons.Path + " Snap to Path", + PhosphorIcons.MapPin + " Point at Selected", PhosphorIcons.Hourglass + " Add Pause", PhosphorIcons.Scissors + " Simplify", + }; + private static readonly string[] RowMenu = + { "Set Active", "Move Here", "Move Up", "Move Down", "Duplicate", "Delete" }; + private const string FromTrail = PhosphorIcons.Footprints + " Route from Trail..."; + private readonly bool[] _editEnabled = new bool[6]; private NavPayload _data = new(); private long _seenVersion = -1; private readonly List _pointText = new(); - private int _selected = -1, _addMode; + // _selected is the focus row (insert point, chat editing); _multi is every selected row, + // always containing _selected when it is set. _anchor starts Shift-click ranges. + private int _selected = -1, _anchor = -1, _addMode; + private readonly HashSet _multi = new(); private bool _typing; private string _routeLabel = "Route: Once", _insertLabel = "Insert: End", _activeLabel = "Active Nav: None (Unsaved)"; private string _fileLabel = "Select nav file..."; @@ -152,10 +176,11 @@ internal sealed class NavFace : IImGuiPanel typing |= ReachRow(w); // Actions - int action = WrapButtons("nav_act", Actions, w, 24, ActionsEnabled); + int action = WrapButtons("nav_act", Actions, w, 24); switch (action) { case 0: NavCommands.Send(new NavCmd { Cmd = "addWaypoint", AddMode = _addMode, InsertAt = _selected }); break; + case 1: NavCommands.Send(new NavCmd { Cmd = "addPortal", AddMode = _addMode, InsertAt = _selected }); break; case 2: _picker.Open(ImGuiNET.ImGui.GetIO().MousePos, NavCommands.RecallLabels, -1, i => NavCommands.Send(new NavCmd { Cmd = "addRecall", SpellId = NavCommands.RecallIds[i], AddMode = _addMode, InsertAt = _selected })); @@ -163,13 +188,15 @@ internal sealed class NavFace : IImGuiPanel case 3: NavCommands.Send(new NavCmd { Cmd = "clearRoute" }); _data.Points.Clear(); - _selected = -1; + ClearSelection(); RebuildPointText(); break; case 4: NavCommands.Send(new NavCmd { Cmd = "saveRoute" }); break; case 5: NavCommands.Send(new NavCmd { Cmd = "dunPatrol" }); break; } + RouteEditor(w); + // Chat waypoint: sent as if typed when the route reaches it. Selecting an // existing chat waypoint loads its command here; Update saves the edit. bool chatSelected = _selected >= 0 && _selected < _data.Points.Count @@ -249,6 +276,9 @@ internal sealed class NavFace : IImGuiPanel ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 1)); ImGuiNET.ImGui.BeginChild("##nav_points", new Vector2(w, listH)); Waypoints(ImGuiNET.ImGui.GetContentRegionAvail().X); + if (!typing && _multi.Count > 0 && ImGuiNET.ImGui.IsKeyPressed(ImGuiKey.Delete, false) + && (ImGuiNET.ImGui.IsWindowHovered() || ImGuiNET.ImGui.IsWindowFocused())) + DeleteSelected(); ImGuiNET.ImGui.EndChild(); ImGuiNET.ImGui.PopStyleVar(); ImGuiNET.ImGui.PopStyleColor(); @@ -334,20 +364,24 @@ internal sealed class NavFace : IImGuiPanel Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); const float h = 22; if (p.Y + h < clipMin.Y || p.Y > clipMax.Y) { ImGuiNET.ImGui.Dummy(new Vector2(w, h)); continue; } - bool active = i == _data.ActiveNavIndex, selected = i == _selected; + bool active = i == _data.ActiveNavIndex, selected = _multi.Contains(i); ImGuiNET.ImGui.PushID(i); // Row click selects (drawn first so the X button on top wins). ImGuiNET.ImGui.SetCursorScreenPos(p); ImGuiNET.ImGui.SetNextItemAllowOverlap(); // the X button on top gets its clicks - if (ImGuiNET.ImGui.InvisibleButton("##row", new Vector2(w, h))) _selected = i; + if (ImGuiNET.ImGui.InvisibleButton("##row", new Vector2(w, h))) ClickRow(i); + if (ImGuiNET.ImGui.IsItemHovered() && ImGuiNET.ImGui.IsMouseDoubleClicked(ImGuiMouseButton.Left)) + SetActive(i); + if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) + { + if (!selected) SelectOnly(i); + _picker.Open(ImGuiNET.ImGui.GetIO().MousePos, RowMenu, -1, RowMenuPick, width: 140); + } dl.AddRectFilled(p, p + new Vector2(w, h), selected ? Selected : i % 2 == 0 ? PanelBg : RowAlt); if (IconButton("##del", PhosphorIcons.X, new Vector2(p.X + 2, p.Y + 2), new Vector2(18, 18), Text, DeleteBg, font: UiFont.Ui11)) { NavCommands.Send(new NavCmd { Cmd = "deletePoint", Index = i }); - if (_selected == i) _selected = -1; - else if (_selected > i) _selected--; - _data.Points.RemoveAt(i); - RebuildPointText(); + RemoveLocal(new HashSet { i }); ImGuiNET.ImGui.PopID(); return; } @@ -362,6 +396,216 @@ internal sealed class NavFace : IImGuiPanel } } + /// + /// Route editor: Edit row (on the selection), Tools row (on the route), the Record toggle + /// with "Route from Trail...", and the last edit's result. Picker-backed buttons (pause, + /// simplify, trail) double as the confirmation for edits that can't be undone. + /// + private void RouteEditor(float w) + { + int n = _multi.Count, count = _data.Points.Count; + bool one = n == 1 && _selected >= 0; + _editEnabled[0] = n > 0 && _multi.Min() > 0; + _editEnabled[1] = n > 0 && _multi.Max() < count - 1; + _editEnabled[2] = _editEnabled[3] = n > 0; + _editEnabled[4] = _editEnabled[5] = one; + Label(n > 1 ? $"Edit ({n} selected)" : "Edit", Mute); + switch (WrapButtons("nav_edit", EditActions, w, 22, _editEnabled)) + { + case 0: MoveSelected(-1); break; + case 1: MoveSelected(+1); break; + case 2: DuplicateSelected(); break; + case 3: DeleteSelected(); break; + case 4: SetActive(_selected); break; + case 5: NavCommands.Send(new NavCmd { Cmd = "movePointHere", Index = _selected }); break; + } + + Vector2 at = ImGuiNET.ImGui.GetIO().MousePos; + switch (WrapButtons("nav_tools", ToolActions, w, 22)) + { + case 0: NavCommands.Send(new NavCmd { Cmd = "nearestActive" }); break; + case 1: + if (count < 2) break; + NavCommands.Send(new NavCmd { Cmd = "reverseRoute" }); + ReverseLocal(); + break; + case 2: NavCommands.Send(new NavCmd { Cmd = "snapToPath" }); break; + case 3: NavCommands.Send(new NavCmd { Cmd = "addPointAtSelected", AddMode = _addMode, InsertAt = _selected }); break; + case 4: + _picker.Open(at, NavCommands.PauseLabels, -1, i => NavCommands.Send(new NavCmd + { Cmd = "addPause", Seconds = NavCommands.PauseSeconds[i], AddMode = _addMode, InsertAt = _selected }), width: 140); + break; + case 5: + _picker.Open(at, NavCommands.SimplifyLabels, -1, i => + NavCommands.Send(new NavCmd { Cmd = "simplifyRoute", Yards = NavCommands.SimplifyYards[i] }), width: 300); + break; + } + + // Record | Route from Trail... + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + float half = (w - 4) / 2; + if (OverlayToggle("##record", "Record route", _data.IsRecording, p, half, + "Add a point every few yards as you walk, and portal steps as you use portals\n(/ra navrec on|off). Points go into the current route.")) + { + bool on = !_data.IsRecording; + NavCommands.Send(new NavCmd { Cmd = "setRecording", On = on }); + _data.IsRecording = on; + } + Vector2 tp = new(p.X + half + 4, p.Y); + if (Button("##fromtrail", FromTrail, tp, new Vector2(half, 22), Text, BtnFill, enabled: _data.TrailPoints >= 2)) + _picker.Open(new Vector2(tp.X, tp.Y + 22), NavCommands.TrailChoices, -1, i => + NavCommands.Send(new NavCmd { Cmd = "trailToRoute", Reverse = i == 1 }), width: 300); + if (ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled)) + ImGuiNET.ImGui.SetTooltip(_data.TrailPoints >= 2 + ? $"Breadcrumb trail: {_data.TrailPoints} crumbs, {_data.TrailYards:0} yd.\nThe new route is unsaved; the loaded nav file is not changed." + : "Turn on Breadcrumbs and walk a while to build a trail."); + NextLine(p, 26); + + if (_data.EditStatus.Length > 0) Label(_data.EditStatus, Amber); + } + + /// Plain click selects one row, Ctrl toggles a row, Shift selects from the anchor. + private void ClickRow(int i) + { + var io = ImGuiNET.ImGui.GetIO(); + if (io.KeyShift && _anchor >= 0) + { + if (!io.KeyCtrl) _multi.Clear(); + for (int k = Math.Min(_anchor, i); k <= Math.Max(_anchor, i); k++) _multi.Add(k); + _selected = i; + } + else if (io.KeyCtrl) + { + if (!_multi.Remove(i)) { _multi.Add(i); _selected = i; } + else if (_selected == i) _selected = _multi.Count > 0 ? _multi.Min() : -1; + _anchor = i; + } + else SelectOnly(i); + } + + private void SelectOnly(int i) + { + _multi.Clear(); + _multi.Add(i); + _selected = _anchor = i; + } + + private void ClearSelection() + { + _multi.Clear(); + _selected = _anchor = -1; + } + + private List SelectedIndices() + { + var list = new List(_multi); + list.Sort(); + return list; + } + + private void RowMenuPick(int item) + { + switch (item) + { + case 0: if (_selected >= 0) SetActive(_selected); break; + case 1: if (_selected >= 0) NavCommands.Send(new NavCmd { Cmd = "movePointHere", Index = _selected }); break; + case 2: MoveSelected(-1); break; + case 3: MoveSelected(+1); break; + case 4: DuplicateSelected(); break; + case 5: DeleteSelected(); break; + } + } + + private void SetActive(int i) + { + if (i < 0 || i >= _data.Points.Count) return; + NavCommands.Send(new NavCmd { Cmd = "setActive", Index = i }); + _data.ActiveNavIndex = i; + } + + /// Moves the selected rows one slot, the way the plugin does (NavRouteEditing.Move). + private void MoveSelected(int delta) + { + if (_multi.Count == 0) return; + NavCommands.Send(new NavCmd { Cmd = "movePoints", Indices = SelectedIndices(), Delta = delta }); + var pts = _data.Points; + var sel = new HashSet(); + foreach (int i in _multi) sel.Add(pts[i]); + NavPoint? focus = _selected >= 0 ? pts[_selected] : null, anchor = _anchor >= 0 && _anchor < pts.Count ? pts[_anchor] : null; + if (delta < 0) + { + for (int i = 1; i < pts.Count; i++) + if (sel.Contains(pts[i]) && !sel.Contains(pts[i - 1])) (pts[i - 1], pts[i]) = (pts[i], pts[i - 1]); + } + else + { + for (int i = pts.Count - 2; i >= 0; i--) + if (sel.Contains(pts[i]) && !sel.Contains(pts[i + 1])) (pts[i + 1], pts[i]) = (pts[i], pts[i + 1]); + } + _multi.Clear(); + for (int i = 0; i < pts.Count; i++) if (sel.Contains(pts[i])) _multi.Add(i); + _selected = focus != null ? pts.IndexOf(focus) : -1; + _anchor = anchor != null ? pts.IndexOf(anchor) : _selected; + RebuildPointText(); + } + + /// Each selected row gets a copy right after it (as the plugin does); the copies end up selected. + private void DuplicateSelected() + { + if (_multi.Count == 0) return; + NavCommands.Send(new NavCmd { Cmd = "duplicatePoints", Indices = SelectedIndices() }); + var result = new List(_data.Points.Count + _multi.Count); + var copies = new HashSet(); + for (int i = 0; i < _data.Points.Count; i++) + { + NavPoint pt = _data.Points[i]; + result.Add(pt); + if (!_multi.Contains(i)) continue; + copies.Add(result.Count); + result.Add(new NavPoint { Type = pt.Type, Desc = pt.Desc, Text = pt.Text, NS = pt.NS, EW = pt.EW, Z = pt.Z }); + } + _data.Points = result; + _multi.Clear(); + _multi.UnionWith(copies); + _selected = _anchor = _multi.Count > 0 ? _multi.Min() : -1; + RebuildPointText(); + } + + private void DeleteSelected() + { + if (_multi.Count == 0) return; + NavCommands.Send(new NavCmd { Cmd = "deletePoints", Indices = SelectedIndices() }); + RemoveLocal(new HashSet(_multi)); + } + + /// Drops rows from the local copy and shifts the selection past them. + private void RemoveLocal(HashSet removed) + { + int Shift(int i) { int s = 0; foreach (int r in removed) if (r < i) s++; return i - s; } + var keep = new List(); + foreach (int i in _multi) if (!removed.Contains(i)) keep.Add(Shift(i)); + _selected = _selected >= 0 && !removed.Contains(_selected) ? Shift(_selected) : -1; + _anchor = _anchor >= 0 && !removed.Contains(_anchor) ? Shift(_anchor) : _selected; + _multi.Clear(); + _multi.UnionWith(keep); + if (_selected < 0 && _multi.Count > 0) _selected = _multi.Min(); + for (int i = _data.Points.Count - 1; i >= 0; i--) if (removed.Contains(i)) _data.Points.RemoveAt(i); + RebuildPointText(); + } + + private void ReverseLocal() + { + int last = _data.Points.Count - 1; + _data.Points.Reverse(); + var flipped = new List(); + foreach (int i in _multi) flipped.Add(last - i); + _multi.Clear(); + _multi.UnionWith(flipped); + if (_selected >= 0) _selected = last - _selected; + if (_anchor >= 0) _anchor = last - _anchor; + RebuildPointText(); + } + private void TakeSnapshot() { var snap = UiSources.Nav.Current; @@ -369,7 +613,11 @@ internal sealed class NavFace : IImGuiPanel _seenVersion = snap.Version; _data = snap.Value.Clone(); _navFiles = _data.NavFiles.ToArray(); - if (_selected >= _data.Points.Count) _selected = -1; + int count = _data.Points.Count; + _multi.RemoveWhere(i => i >= count); + if (_selected >= count) _selected = -1; + if (_selected < 0 && _multi.Count > 0) _selected = _multi.Min(); + if (_anchor >= count) _anchor = _selected; RebuildPointText(); UpdateLabels(); } diff --git a/src/RynthCore.Engine/ImGui/Panels/SettingsFace.cs b/src/RynthCore.Engine/ImGui/Panels/SettingsFace.cs index 9d2f9d8..de18c2d 100644 --- a/src/RynthCore.Engine/ImGui/Panels/SettingsFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/SettingsFace.cs @@ -191,11 +191,64 @@ internal sealed class SettingsFace : IImGuiPanel case SettingKind.Note: Note(row.Label, w); break; case SettingKind.CraftingStatus: CraftingStatus(row); break; case SettingKind.Button: ButtonRow(row, w); break; + case SettingKind.TraceCategories: TraceCategoriesRow(row, w); break; case SettingKind.Text: TextRow(row, w); break; case SettingKind.Status: StatusRow(row, w); break; } } + // [All on] [All off] [ILT Hub on], then a 3-column grid of square toggles, one per + // RynthAi trace category. Edits the copy's DiagCategories and saves like any other row. + private void TraceCategoriesRow(SettingRow row, float w) + { + var cats = TraceCategoryLevels.Parse(_data.DiagCategories); + if (cats.Count == 0) + { + Note("Waiting for RynthAi...", w); + return; + } + + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + if (ImGuiNET.ImGui.Button("All on")) SaveCategories(TraceCategoryLevels.Set(_data.DiagCategories, "", true)); + ImGuiNET.ImGui.SameLine(0, 6); + if (ImGuiNET.ImGui.Button("All off")) SaveCategories(TraceCategoryLevels.Set(_data.DiagCategories, "", false)); + ImGuiNET.ImGui.SameLine(0, 6); + if (ImGuiNET.ImGui.Button("ILT Hub on")) SaveCategories(TraceCategoryLevels.Set(_data.DiagCategories, "", true, "Ilt")); + Tooltip(row); + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + float colW = Math.Max(80f, w / 3f); + int perRow = Math.Max(1, (int)(w / colW)); + Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos(); + for (int i = 0; i < cats.Count; i++) + { + var (name, level) = cats[i]; + bool on = level != TraceCategoryLevels.Off; + string label = TraceCategoryLevels.Label(name, level); + var p = start + new Vector2(i % perRow * colW, i / perRow * 18f); + ImGuiNET.ImGui.SetCursorScreenPos(p); + ImGuiNET.ImGui.PushID(name); + if (ImGuiNET.ImGui.InvisibleButton("##cat", new Vector2(colW - 4, 16))) + SaveCategories(TraceCategoryLevels.Set(_data.DiagCategories, name, !on)); + if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand); + ImGuiNET.ImGui.PopID(); + dl.AddRectFilled(p + new Vector2(0, 2), p + new Vector2(12, 14), on ? ToggleOn : ToggleOff, 2); + dl.PushClipRect(p, p + new Vector2(colW - 4, 16), true); + dl.AddText(p + new Vector2(18, (16 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), TextDim, label); + dl.PopClipRect(); + } + int rowsUsed = (cats.Count + perRow - 1) / perRow; + ImGuiNET.ImGui.SetCursorScreenPos(start + new Vector2(0, rowsUsed * 18f)); + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + } + + private void SaveCategories(string levels) + { + _data.DiagCategories = levels; + SettingsCommands.Save(_data.Clone()); + } + // Label, then a full-width box; the value commits on Enter or focus loss (like the number boxes). private void TextRow(SettingRow row, float w) { @@ -625,6 +678,7 @@ internal sealed class SettingsFace : IImGuiPanel ["Crafting"] = PhosphorIcons.Hammer, ["Looting"] = PhosphorIcons.Bag, ["Vendoring"] = PhosphorIcons.Storefront, + ["Diagnostics"] = PhosphorIcons.Wrench, [CharmsTabName] = PhosphorIcons.Gift, }; private static readonly System.Collections.Generic.Dictionary TabLabels = new(); diff --git a/src/RynthCore.Engine/ImGui/Panels/SkillsData.cs b/src/RynthCore.Engine/ImGui/Panels/SkillsData.cs index 46d7f68..9fe47f5 100644 --- a/src/RynthCore.Engine/ImGui/Panels/SkillsData.cs +++ b/src/RynthCore.Engine/ImGui/Panels/SkillsData.cs @@ -25,6 +25,7 @@ using System.Globalization; using System.IO; using System.Text; using System.Threading; +using RynthCore.Engine.Compatibility; using RynthCore.Engine.UI; using RynthCore.Engine.UI.ScriptWindows; @@ -53,6 +54,8 @@ internal sealed class SkillDatTables public uint[] TrainedXp = Array.Empty(); public uint[] SpecializedXp = Array.Empty(); public ulong[] LevelXp = Array.Empty(); + /// The same arrays as one object (Compatibility/TrainingCosts). + public XpTableData Xp = new(); } internal static class SkillDat @@ -137,51 +140,31 @@ internal static class SkillDat return r.Ok && t.Skills.Count > 0; } + // The XpTable layout and the cost arithmetic live in Compatibility/TrainingCosts.cs (shared + // with the plugin API's raise calls and tested against a real portal.dat). private static bool ParseXp(byte[] raw, SkillDatTables t) { - var r = new Reader(raw); - r.U32(); // file id - int attrs = (int)r.U32(), vitals = (int)r.U32(), trained = (int)r.U32(), spec = (int)r.U32(); - int levels = (int)r.U32(); - if (!r.Ok || attrs < 0 || vitals < 0 || trained < 0 || spec < 0 || levels < 0 - || attrs > 10000 || vitals > 10000 || trained > 10000 || spec > 10000 || levels > 10000) - return false; - t.AttributeXp = r.U32s(attrs + 1); - t.VitalXp = r.U32s(vitals + 1); - t.TrainedXp = r.U32s(trained + 1); - t.SpecializedXp = r.U32s(spec + 1); - var lv = new ulong[levels + 1]; - for (int i = 0; i <= levels; i++) lv[i] = r.U64(); - t.LevelXp = lv; - return r.Ok; + if (!TrainingCosts.TryParseXpTable(raw, out XpTableData xp)) return false; + t.Xp = xp; + t.AttributeXp = xp.AttributeXp; + t.VitalXp = xp.VitalXp; + t.TrainedXp = xp.TrainedXp; + t.SpecializedXp = xp.SpecializedXp; + t.LevelXp = xp.LevelXp; + return true; } // ── XP arithmetic (the server's: Player.SpendAttributeXp / SpendSkillXp) ── /// True when is the table's top rank (nothing left to buy). - public static bool IsMax(uint[] table, uint ranks) => table.Length == 0 || ranks + 1 >= (uint)table.Length; + public static bool IsMax(uint[] table, uint ranks) => TrainingCosts.IsMax(table, ranks); /// XP to buy more ranks from with already spent; -1 past the top. - public static long CostOf(uint[] table, uint ranks, uint spent, int n) - { - if (n < 1) return 0; - long target = (long)ranks + n; - if (target >= table.Length) return -1; - return Math.Max(0L, (long)table[target] - spent); - } + public static long CostOf(uint[] table, uint ranks, uint spent, int n) => TrainingCosts.CostOf(table, ranks, spent, n); /// How many ranks in a row XP buys (0 when not even one), up to the top rank. - public static int Affordable(uint[] table, uint ranks, uint spent, long available) - { - int lo = 0, hi = Math.Max(0, table.Length - 1 - (int)Math.Min(ranks, (uint)int.MaxValue)); - while (lo < hi) - { - int mid = (lo + hi + 1) / 2; - long c = CostOf(table, ranks, spent, mid); - if (c >= 0 && c <= available) lo = mid; else hi = mid - 1; - } - return lo; - } + public static int Affordable(uint[] table, uint ranks, uint spent, long available) => + TrainingCosts.Affordable(table, ranks, spent, available); /// Bounds-checked little-endian reader; Ok turns false on overrun. private ref struct Reader diff --git a/src/RynthCore.Engine/ImGui/Panels/VisionFace.cs b/src/RynthCore.Engine/ImGui/Panels/VisionFace.cs index 01f9a66..9d029ed 100644 --- a/src/RynthCore.Engine/ImGui/Panels/VisionFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/VisionFace.cs @@ -3,7 +3,8 @@ // ImGui face of the RynthVision settings (UI/Panels/RynthVisionPanel.cs), // in three tabs: // Terrain the plugin's overlays (radar ring, unclimbable slopes, -// impassable water), colours (AARRGGBB hex + swatch), tuning +// impassable water), colours (AARRGGBB hex + swatch) each +// with an opacity slider (the colour's alpha byte), tuning // sliders (Ctrl+click to type a value), water terrain types, // and "Log terrain types here"; // Nameplates the RynthVision nameplates (monster plates, debuff icons, @@ -115,10 +116,15 @@ internal sealed class VisionFace : IImGuiPanel if (ImGuiNET.ImGui.Checkbox("Unclimbable slopes", ref s.Slopes)) Save(VisionKeys.Slopes); if (ImGuiNET.ImGui.Checkbox("Impassable water", ref s.Water)) Save(VisionKeys.Water); - Header("Colors (hex AARRGGBB)"); + Header("Colors (hex AARRGGBB) and opacity"); + ImGuiNET.ImGui.PushItemWidth(Math.Max(120, ImGuiNET.ImGui.GetContentRegionAvail().X - 8)); busy |= ColorRow(SlopeColorF, _slopeHex, ref s.SlopeColor); + busy |= OpacitySlider(SlopeOpacityF, _slopeHex, ref s.SlopeColor); busy |= ColorRow(WaterColorF, _waterHex, ref s.WaterColor); + busy |= OpacitySlider(WaterOpacityF, _waterHex, ref s.WaterColor); busy |= ColorRow(RadarColorF, _radarHex, ref s.RadarColor); + busy |= OpacitySlider(RadarOpacityF, _radarHex, ref s.RadarColor); + ImGuiNET.ImGui.PopItemWidth(); Header("Tuning"); ImGuiNET.ImGui.PushItemWidth(Math.Max(120, ImGuiNET.ImGui.GetContentRegionAvail().X - 8)); @@ -188,6 +194,10 @@ internal sealed class VisionFace : IImGuiPanel private static readonly Field SlopeColorF = Field.Color("Slope", VisionKeys.SlopeColor); private static readonly Field WaterColorF = Field.Color("Water", VisionKeys.WaterColor); private static readonly Field RadarColorF = Field.Color("Radar", VisionKeys.RadarColor); + // Opacity is the colour's alpha byte: the slider saves the colour field. + private static readonly Field SlopeOpacityF = Field.Slider("Slope opacity", VisionKeys.SlopeColor); + private static readonly Field WaterOpacityF = Field.Slider("Water opacity", VisionKeys.WaterColor); + private static readonly Field RadarOpacityF = Field.Slider("Radar ring opacity", VisionKeys.RadarColor); private static readonly Field RadarRangeF = Field.Slider("Radar range", VisionKeys.RadarRange); private static readonly Field RingThickF = Field.Slider("Ring thickness", VisionKeys.RingThick); private static readonly Field RingHeightF = Field.Slider("Ring height (m)", VisionKeys.RingHeight); @@ -227,6 +237,24 @@ internal sealed class VisionFace : IImGuiPanel return typing; } + /// + /// The colour's alpha as 0-100 %: label, then the slider. Rewrites the alpha byte (RGB kept) and the hex + /// box as it moves, saves the colour on release. Untouched, the colour is never rewritten. True while in use. + /// + private bool OpacitySlider(Field f, byte[] hex, ref uint argb) + { + ImGuiNET.ImGui.TextUnformatted(f.Label); + float pct = ArgbOpacity.Percent(argb); + if (ImGuiNET.ImGui.SliderFloat(f.Id, ref pct, 0f, 100f, "%.0f%%", ImGuiSliderFlags.AlwaysClamp)) + { + argb = ArgbOpacity.WithPercent(argb, pct); + WriteUtf8(hex, argb.ToString("X8")); + } + if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) Save(f.Key); + ImGuiNET.ImGui.SetItemTooltip("0% = invisible, 100% = solid. Ctrl+click to type a value"); + return ImGuiNET.ImGui.IsItemActive(); + } + /// Label, then the slider; saves on release (or after Ctrl+click typing). True while in use. private bool Slider(Field f, ref double value, double min, double max, string format) { diff --git a/src/RynthCore.Engine/ImGui/RynthCoreShell.cs b/src/RynthCore.Engine/ImGui/RynthCoreShell.cs index 8a41906..601f90a 100644 --- a/src/RynthCore.Engine/ImGui/RynthCoreShell.cs +++ b/src/RynthCore.Engine/ImGui/RynthCoreShell.cs @@ -369,6 +369,8 @@ internal static class RynthCoreShell new System.Threading.Thread(() => { System.Threading.Thread.Sleep(120); + // Asked for by hand: the reload deferral (EntryPoint.Shutdown) doesn't hold it. + EntryPoint.NoteManualReload(); bool ok = EngineLifecycle.SignalReload(); RynthLog.Info($"ERl: SignalReload returned {ok}."); }) diff --git a/src/RynthCore.Engine/ImGui/UiDropTargets.cs b/src/RynthCore.Engine/ImGui/UiDropTargets.cs new file mode 100644 index 0000000..670334a --- /dev/null +++ b/src/RynthCore.Engine/ImGui/UiDropTargets.cs @@ -0,0 +1,135 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/UiDropTargets.cs +// +// AC items dropped on the engine's ImGui panels (2026-10-05). A face that takes +// drops publishes its body rect every frame it draws (Publish); when the player +// drags an item out of an AC item list (a pack, the main inventory) and lets go +// over that rect, Compatibility/UiElementHooks' UIElement::CatchDroppedItem +// detour asks TryClaim. A claimed drop never reaches AC: the detour answers +// "not caught" (false), which is AC's own drop-rejected path, so the item stays +// where it was. The face picks the item up with TryTake on its next draw. +// +// All on AC's main thread: faces draw in EndScene, the detour runs inside AC's +// StopDragandDrop. A target not published for StaleMs (panel closed, hidden, +// between characters) never claims. +// ============================================================================ +using System; +using System.Collections.Generic; +using System.Numerics; +using System.Runtime.InteropServices; + +namespace RynthCore.Engine.ImGuiBackend; + +internal static class UiDropTargets +{ + private const long StaleMs = 500; + + private sealed class Target + { + public required string Key; + public required string PanelTitle; + public bool Popped; + public Vector2 Min, Max; // ImGui coordinates of the game window's client area (docked) + public long SeenMs; + public bool Accepting; + public bool HasDrop; + public uint ItemId, SpellId; + } + + [StructLayout(LayoutKind.Sequential)] private struct POINT { public int X, Y; } + [DllImport("user32.dll")] private static extern bool GetCursorPos(out POINT p); + + private static readonly Dictionary Targets = new(StringComparer.Ordinal); + private static readonly object Sync = new(); + + /// + /// Once per frame from a face's Draw: .. is the + /// body in screen coordinates as ImGui sees them (FaceKit.Begin's origin and size). + /// false: drawn, but a drop now wouldn't be used (it then + /// goes to AC as usual). Popped-out faces hit-test against their own window. + /// + public static void Publish(string key, string panelTitle, Vector2 min, Vector2 max, bool accepting) + { + lock (Sync) + { + if (!Targets.TryGetValue(key, out Target? t)) + Targets[key] = t = new Target { Key = key, PanelTitle = panelTitle }; + t.Popped = ImGuiPopOuts.InPopOutFrame; + t.Min = min; + t.Max = max; + t.Accepting = accepting; + t.SeenMs = Environment.TickCount64; + } + } + + /// + /// UIElement::CatchDroppedItem detour, AC's main thread: is the cursor over a live, + /// accepting target? Then that target takes the item and the caller keeps it from AC. + /// + public static bool TryClaim(uint itemId, uint spellId, out string key) + { + key = string.Empty; + if (itemId == 0) + return false; + long now = Environment.TickCount64; + lock (Sync) + { + foreach (Target t in Targets.Values) + { + if (!t.Accepting || now - t.SeenMs > StaleMs || !IsCursorOver(t)) + continue; + t.HasDrop = true; + t.ItemId = itemId; + t.SpellId = spellId; + key = t.Key; + return true; + } + } + return false; + } + + /// The face's draw: an item dropped on it since the last call. + public static bool TryTake(string key, out uint itemId) + { + itemId = 0; + lock (Sync) + { + if (!Targets.TryGetValue(key, out Target? t) || !t.HasDrop) + return false; + t.HasDrop = false; + itemId = t.ItemId; + return itemId != 0; + } + } + + /// The cursor is over the target now (the face's "drop here" highlight). + public static bool IsCursorOver(string key) + { + lock (Sync) + return Targets.TryGetValue(key, out Target? t) && IsCursorOver(t); + } + + private static bool IsCursorOver(Target t) + { + if (t.Popped) + return ImGuiPopOuts.IsCursorOver(t.PanelTitle); + if (!GetCursorPos(out POINT p)) + return false; + Vector2 local = new Vector2(p.X, p.Y) - ImGuiPopOuts.ClientOriginOnScreen(); + return local.X >= t.Min.X && local.Y >= t.Min.Y && local.X < t.Max.X && local.Y < t.Max.Y; + } + + public static string Describe() + { + long now = Environment.TickCount64; + lock (Sync) + { + if (Targets.Count == 0) + return "Drop targets: none drawn yet."; + var parts = new List(); + foreach (Target t in Targets.Values) + parts.Add($"{t.Key} ({(now - t.SeenMs <= StaleMs ? (t.Accepting ? "live" : "drawn, not accepting") : "not drawn")}{(t.Popped ? ", popped out" : string.Empty)})"); + return "Drop targets: " + string.Join(", ", parts) + "."; + } + } +} diff --git a/src/RynthCore.Engine/ImGui/Win32Backend.cs b/src/RynthCore.Engine/ImGui/Win32Backend.cs index 89f3510..23882a9 100644 --- a/src/RynthCore.Engine/ImGui/Win32Backend.cs +++ b/src/RynthCore.Engine/ImGui/Win32Backend.cs @@ -853,6 +853,15 @@ internal static unsafe class Win32Backend } } + // ── Remote tap-to-click (the phone, via the StatusAgent's PostMessage) ── + // A posted mouse message whose point is not where the cursor was when it was queued did not come + // from the mouse: it is the StatusAgent clicking where the phone tapped. Without this, the ImGui + // capture below judged it by the REAL cursor (NewFrame's GetCursorPos): on the focused client, + // with the PC's mouse parked over a RynthCore panel, every remote click was eaten, and the + // phone's tap still fed ImGui a fake cursor. Hand it straight to AC instead. + if (IsRemoteClientMouse(hWnd, msg, lParam)) + return CallWindowProcA(_originalWndProc, hWnd, msg, wParam, lParam); + // ── Chat capture: consume all key input for the chat TextBox ──── // Game HWND keeps Win32 focus throughout; callbacks dispatch Text // updates to the panel on Avalonia's UI thread — no Avalonia focus needed. @@ -1464,6 +1473,29 @@ internal static unsafe class Win32Backend }; } + [DllImport("user32.dll")] + private static extern uint GetMessagePos(); + + /// + /// True for a client-area mouse message another process posted (the StatusAgent's remote click): + /// Windows stamps every queued message with the cursor position at the time it was queued + /// (GetMessagePos). Mouse input carries that same point in lParam; a PostMessage from elsewhere + /// carries its own point while the stamp is wherever the real cursor sat. A 2 px slack covers + /// rounding. Only the move/click messages whose lParam is client coordinates are tested (the wheel's + /// lParam is screen coordinates). + /// + private static bool IsRemoteClientMouse(IntPtr hWnd, uint msg, IntPtr lParam) + { + if (msg != WM_MOUSEMOVE && msg != WM_LBUTTONDOWN && msg != WM_LBUTTONUP && msg != WM_RBUTTONDOWN && msg != WM_RBUTTONUP) + return false; + uint pos = GetMessagePos(); + var stamp = new POINT { X = (short)(pos & 0xFFFF), Y = (short)((pos >> 16) & 0xFFFF) }; + if (!ScreenToClient(hWnd, ref stamp)) + return false; + int x = (short)((long)lParam & 0xFFFF), y = (short)(((long)lParam >> 16) & 0xFFFF); + return Math.Abs(stamp.X - x) > 2 || Math.Abs(stamp.Y - y) > 2; + } + private static bool IsMouseMessage(uint msg) { return msg >= WM_MOUSEMOVE && msg <= WM_MBUTTONUP diff --git a/src/RynthCore.Engine/Net/AcPacketWire.cs b/src/RynthCore.Engine/Net/AcPacketWire.cs new file mode 100644 index 0000000..91fbb5b --- /dev/null +++ b/src/RynthCore.Engine/Net/AcPacketWire.cs @@ -0,0 +1,157 @@ +// ============================================================================ +// RynthCore.Engine - Net/AcPacketWire.cs +// Where the message fragments sit in one server-to-client UDP datagram. +// +// Written from the AC wire format as the engine already reads it (RawPacketParser's +// 20-byte header + 16-byte fragment headers) and general knowledge of the protocol; +// no generated definitions. Pure code: no engine state, compiled into the +// NetMessageTests replay runner as is. +// +// Datagram: +// header (20 bytes) +// +0 u32 sequence +// +4 u32 flags (PacketFlags below) +// +8 u32 checksum (not checked: we only read) +// +12 u16 recipient id +// +14 u16 time +// +16 u16 size bytes after the header (optional headers + fragments) +// +18 u16 iteration +// optional headers, one per flag bit set, in ascending bit order +// fragments, back to back, when flags has BlobFragments +// +// Fragment (16-byte header, then its share of the message): +// +0 u32 sequence the message's id: every fragment of one message shares it +// +4 u32 id +// +8 u16 count fragments in the message +// +10 u16 size this fragment INCLUDING its 16-byte header +// +12 u16 index 0..count-1 +// +14 u16 queue the client's dispatch queue (not the opcode) +// +// The walk is self-checking: the optional headers and the fragments must end exactly at +// 20 + header.size. A datagram that doesn't is counted as malformed and skipped whole, +// so a wrong guess about an optional header shows up as a counter, never as garbage. +// ============================================================================ + +namespace RynthCore.Engine.Net; + +/// Packet header flag bits the reader needs. +internal static class PacketFlags +{ + public const uint Retransmission = 0x00000001; + public const uint EncryptedChecksum = 0x00000002; + public const uint BlobFragments = 0x00000004; + public const uint ServerSwitch = 0x00000100; // 8 bytes + public const uint LogonServerAddr = 0x00000200; // size unknown here: skip the datagram + public const uint EmptyHeader1 = 0x00000400; // 0 bytes + public const uint Referral = 0x00000800; // size unknown here: skip the datagram + public const uint RequestRetransmit = 0x00001000; // u32 count + count * u32 + public const uint RejectRetransmit = 0x00002000; // u32 count + count * u32 + public const uint AckSequence = 0x00004000; // 4 bytes + public const uint Disconnect = 0x00008000; // 0 bytes + public const uint LoginRequest = 0x00010000; // client to server only: skip + public const uint WorldLoginRequest = 0x00020000; // 8 bytes + public const uint ConnectRequest = 0x00040000; // 32 bytes; starts a new session + public const uint ConnectResponse = 0x00080000; // 8 bytes + public const uint NetError = 0x00100000; // 8 bytes + public const uint NetErrorDisconnect = 0x00200000; // 8 bytes + public const uint CICMDCommand = 0x00400000; // 8 bytes + public const uint TimeSync = 0x01000000; // 8 bytes + public const uint EchoRequest = 0x02000000; // 4 bytes + public const uint EchoResponse = 0x04000000; // 8 bytes + public const uint Flow = 0x08000000; // 6 bytes + + /// Flags whose optional header this reader can't size; a fragment datagram carrying one is skipped. + public const uint Unsized = LogonServerAddr | Referral | LoginRequest | 0x00800000u | 0xF0000000u | 0x000000F8u; +} + +internal enum PacketWalk : byte +{ + /// Fragments located. + Ok, + /// No BlobFragments flag: nothing to reassemble (acks, pings, time sync...). + NoFragments, + /// Shorter than a header, or the sizes don't add up. + Malformed, + /// Carries an optional header this reader can't size. + UnknownOptional, +} + +internal static unsafe class AcPacketWire +{ + public const int HeaderSize = 20; + public const int FragmentHeaderSize = 16; + + public static uint ReadU32(byte* p) => (uint)(p[0] | (p[1] << 8) | (p[2] << 16) | (p[3] << 24)); + public static ushort ReadU16(byte* p) => (ushort)(p[0] | (p[1] << 8)); + + /// The datagram's flags, or 0 when it is shorter than a header. + public static uint Flags(byte* data, int length) => length >= HeaderSize ? ReadU32(data + 4) : 0; + + /// + /// Finds the fragment area of one datagram: [fragStart, fragEnd). Never reads past + /// . Ok only when the optional headers sized and fragEnd is + /// exactly where the header's size says the datagram ends. + /// + public static PacketWalk LocateFragments(byte* data, int length, out int fragStart, out int fragEnd) + { + fragStart = fragEnd = 0; + if (data == null || length < HeaderSize) + return PacketWalk.Malformed; + + uint flags = ReadU32(data + 4); + if ((flags & PacketFlags.BlobFragments) == 0) + return PacketWalk.NoFragments; + if ((flags & PacketFlags.Unsized) != 0) + return PacketWalk.UnknownOptional; + + int end = HeaderSize + ReadU16(data + 16); + if (end > length) + return PacketWalk.Malformed; + + int pos = HeaderSize; + if ((flags & PacketFlags.ServerSwitch) != 0) pos += 8; + if ((flags & PacketFlags.RequestRetransmit) != 0 && !SkipU32List(data, end, ref pos)) return PacketWalk.Malformed; + if ((flags & PacketFlags.RejectRetransmit) != 0 && !SkipU32List(data, end, ref pos)) return PacketWalk.Malformed; + if ((flags & PacketFlags.AckSequence) != 0) pos += 4; + if ((flags & PacketFlags.WorldLoginRequest) != 0) pos += 8; + if ((flags & PacketFlags.ConnectRequest) != 0) pos += 32; + if ((flags & PacketFlags.ConnectResponse) != 0) pos += 8; + if ((flags & PacketFlags.NetError) != 0) pos += 8; + if ((flags & PacketFlags.NetErrorDisconnect) != 0) pos += 8; + if ((flags & PacketFlags.CICMDCommand) != 0) pos += 8; + if ((flags & PacketFlags.TimeSync) != 0) pos += 8; + if ((flags & PacketFlags.EchoRequest) != 0) pos += 4; + if ((flags & PacketFlags.EchoResponse) != 0) pos += 8; + if ((flags & PacketFlags.Flow) != 0) pos += 6; + if (pos > end) + return PacketWalk.Malformed; + + // The fragments must tile [pos, end) exactly. + int walk = pos; + int guard = 0; + while (walk < end) + { + if (walk + FragmentHeaderSize > end || ++guard > 64) + return PacketWalk.Malformed; + int size = ReadU16(data + walk + 10); + if (size < FragmentHeaderSize || walk + size > end) + return PacketWalk.Malformed; + walk += size; + } + if (walk == pos) + return PacketWalk.Malformed; // the flag promised fragments + + fragStart = pos; + fragEnd = end; + return PacketWalk.Ok; + } + + private static bool SkipU32List(byte* data, int end, ref int pos) + { + if (pos + 4 > end) return false; + uint n = ReadU32(data + pos); + if (n > 256) return false; + pos += 4 + (int)n * 4; + return pos <= end; + } +} diff --git a/src/RynthCore.Engine/Net/FragmentReassembler.cs b/src/RynthCore.Engine/Net/FragmentReassembler.cs new file mode 100644 index 0000000..0c71097 --- /dev/null +++ b/src/RynthCore.Engine/Net/FragmentReassembler.cs @@ -0,0 +1,307 @@ +// ============================================================================ +// RynthCore.Engine - Net/FragmentReassembler.cs +// Turns server-to-client datagrams into whole messages (u32 opcode + body). +// +// Runs on the consumer side of PacketRing (the plugin pump), never in the RecvFrom +// detour. Read-only: it sees copies of the client's datagrams. +// +// Bounded: +// - at most MaxPartials messages in progress; the least recently touched one is +// dropped when another starts, and any untouched for StaleMs is dropped (either +// way its sequence counts as done, so its late fragments are ignored); +// - at most MaxFragments fragments (MaxFragments * FragmentStride bytes) per message; +// a bigger one is dropped and its sequence remembered as done; +// - a window of the last DoneWindow completed sequences rejects retransmitted copies. +// Slot buffers are pinned arrays reused from one message to the next, so a steady +// stream allocates nothing; a one-fragment message is handed over straight from the +// datagram without a copy. +// +// Messages are delivered in the order they complete (a long message completes after +// shorter ones that started later). The client applies them in its own order. +// +// Pure code; compiled into the NetMessageTests replay runner. +// ============================================================================ + +using System; + +namespace RynthCore.Engine.Net; + +/// Receives each completed message. starts with the u32 opcode and is valid only during the call. +internal unsafe interface IServerMessageSink +{ + void OnServerMessage(uint fragmentSequence, byte* message, int length); +} + +internal sealed unsafe class FragmentReassembler +{ + public const int FragmentStride = 512; // > the largest fragment body a 484-byte datagram can carry + public const int MaxFragments = 256; // 256 * 448 = ~112 KB of message + public const int MaxPartials = 16; + public const int DoneWindow = 4096; // power of two + public const long StaleMs = 30_000; + + private sealed class Slot + { + public bool InUse; + public uint Sequence; + public int Count; + public int Received; + public int Bytes; + public long TouchedMs; + public byte[]? Buffer; // pinned; Count * FragmentStride + public readonly ushort[] Lengths = new ushort[MaxFragments]; + public readonly ulong[] Have = new ulong[MaxFragments / 64]; + } + + private readonly Slot[] _slots = new Slot[MaxPartials]; + private readonly ulong[] _done = new ulong[DoneWindow / 64]; + private uint _maxDone; + private bool _anyDone; + + // ── counters (read by /rc netmsg; written on the consumer thread only) ── + public long Packets, PacketsNoFragments, PacketsMalformed, PacketsUnknownOptional; + public long Fragments, Messages, MultiFragmentMessages, DuplicateFragments, DuplicateMessages; + public long BadFragments, Oversized, EvictedStale, EvictedFull, SessionResets; + public uint LastUnknownFlags; + + public FragmentReassembler() + { + for (int i = 0; i < _slots.Length; i++) + _slots[i] = new Slot(); + } + + public int PartialCount + { + get + { + int n = 0; + foreach (Slot s in _slots) if (s.InUse) n++; + return n; + } + } + + /// Forget everything in progress and the done window (a new session, or the stream switched on). + public void Reset() + { + foreach (Slot s in _slots) + s.InUse = false; + Array.Clear(_done); + _maxDone = 0; + _anyDone = false; + } + + /// One received datagram. is any monotonic millisecond clock. + public void ProcessDatagram(byte* data, int length, long nowMs, IServerMessageSink sink) + { + Packets++; + uint flags = AcPacketWire.Flags(data, length); + if ((flags & PacketFlags.ConnectRequest) != 0) + { + // The server's half of a new connection: fragment sequences start over. + Reset(); + SessionResets++; + } + + PacketWalk walk = AcPacketWire.LocateFragments(data, length, out int pos, out int end); + switch (walk) + { + case PacketWalk.NoFragments: PacketsNoFragments++; return; + case PacketWalk.Malformed: PacketsMalformed++; return; + case PacketWalk.UnknownOptional: PacketsUnknownOptional++; LastUnknownFlags = flags; return; + } + + while (pos < end) + { + byte* f = data + pos; + int size = AcPacketWire.ReadU16(f + 10); + Fragments++; + Fragment(AcPacketWire.ReadU32(f), AcPacketWire.ReadU16(f + 8), AcPacketWire.ReadU16(f + 12), + f + AcPacketWire.FragmentHeaderSize, size - AcPacketWire.FragmentHeaderSize, nowMs, sink); + pos += size; + } + + EvictStale(nowMs); + } + + private void Fragment(uint seq, int count, int index, byte* body, int bodyLen, long nowMs, IServerMessageSink sink) + { + if (count == 0 || index >= count) + { + BadFragments++; + return; + } + if (IsDone(seq)) + { + DuplicateFragments++; + if (count == 1) DuplicateMessages++; + return; + } + + if (count == 1) + { + if (bodyLen < 4) + { + BadFragments++; + MarkDone(seq); + return; + } + MarkDone(seq); + Messages++; + sink.OnServerMessage(seq, body, bodyLen); + return; + } + + if (count > MaxFragments || bodyLen > FragmentStride) + { + Oversized++; + DropSequence(seq); + return; + } + + Slot? slot = FindSlot(seq) ?? StartSlot(seq, count, nowMs); + if (slot.Count != count) + { + BadFragments++; + return; + } + int word = index >> 6; + ulong bit = 1UL << (index & 63); + if ((slot.Have[word] & bit) != 0) + { + DuplicateFragments++; + return; + } + + slot.Have[word] |= bit; + slot.Lengths[index] = (ushort)bodyLen; + slot.Received++; + slot.Bytes += bodyLen; + slot.TouchedMs = nowMs; + fixed (byte* dst = slot.Buffer) + Buffer.MemoryCopy(body, dst + index * FragmentStride, bodyLen, bodyLen); + + if (slot.Received < slot.Count) + return; + + // Complete: pack the fragments together in place (fragment i moves down, never up). + fixed (byte* buf = slot.Buffer) + { + int at = 0; + for (int i = 0; i < slot.Count; i++) + { + int len = slot.Lengths[i]; + if (at != i * FragmentStride) + Buffer.MemoryCopy(buf + i * FragmentStride, buf + at, len, len); + at += len; + } + slot.InUse = false; + MarkDone(seq); + if (at < 4) + { + BadFragments++; + return; + } + Messages++; + MultiFragmentMessages++; + sink.OnServerMessage(seq, buf, at); + } + } + + private Slot? FindSlot(uint seq) + { + foreach (Slot s in _slots) + if (s.InUse && s.Sequence == seq) + return s; + return null; + } + + private Slot StartSlot(uint seq, int count, long nowMs) + { + Slot? pick = null; + foreach (Slot s in _slots) + { + if (!s.InUse) { pick = s; break; } + } + if (pick == null) + { + // All busy: drop the one touched longest ago. + pick = _slots[0]; + foreach (Slot s in _slots) + if (s.TouchedMs < pick.TouchedMs) pick = s; + EvictedFull++; + MarkDone(pick.Sequence); // its stragglers are ignored, not given a new slot + } + + int need = count * FragmentStride; + if (pick.Buffer == null || pick.Buffer.Length < need) + { + // Rounded up so a slot settles at the size it needs; at most MaxFragments * 512. + int cap = 4096; + while (cap < need) cap <<= 1; + pick.Buffer = GC.AllocateUninitializedArray(cap, pinned: true); + } + pick.InUse = true; + pick.Sequence = seq; + pick.Count = count; + pick.Received = 0; + pick.Bytes = 0; + pick.TouchedMs = nowMs; + Array.Clear(pick.Have); + return pick; + } + + private void DropSequence(uint seq) + { + Slot? s = FindSlot(seq); + if (s != null) s.InUse = false; + MarkDone(seq); + } + + private void EvictStale(long nowMs) + { + foreach (Slot s in _slots) + { + if (s.InUse && nowMs - s.TouchedMs > StaleMs) + { + s.InUse = false; + MarkDone(s.Sequence); // a straggler can't start it again + EvictedStale++; + } + } + } + + // ── done window: the last DoneWindow sequences, by bit ────────────────── + + private bool IsDone(uint seq) + { + if (!_anyDone) return false; + if (seq > _maxDone) return false; + if (_maxDone - seq >= DoneWindow) return true; // too old to still be in flight + return (_done[(seq & (DoneWindow - 1)) >> 6] & (1UL << (int)(seq & 63))) != 0; + } + + private void MarkDone(uint seq) + { + if (!_anyDone) + { + _anyDone = true; + _maxDone = seq; + } + else if (seq > _maxDone) + { + // Clear the bits of the sequences the window slides over. + uint advance = seq - _maxDone; + if (advance >= DoneWindow) + Array.Clear(_done); + else + for (uint s = _maxDone + 1; s != seq; s++) + _done[(s & (DoneWindow - 1)) >> 6] &= ~(1UL << (int)(s & 63)); + _maxDone = seq; + } + else if (_maxDone - seq >= DoneWindow) + { + return; + } + _done[(seq & (DoneWindow - 1)) >> 6] |= 1UL << (int)(seq & 63); + } +} diff --git a/src/RynthCore.Engine/Net/PacketRing.cs b/src/RynthCore.Engine/Net/PacketRing.cs new file mode 100644 index 0000000..e482622 --- /dev/null +++ b/src/RynthCore.Engine/Net/PacketRing.cs @@ -0,0 +1,139 @@ +// ============================================================================ +// RynthCore.Engine - Net/PacketRing.cs +// Hand-off of received datagrams from the RecvFrom detour to the plugin pump. +// +// The producer (the detour) only copies the datagram: no allocation, no lock, no +// wait. A full ring, or a second producer arriving while one is writing, drops the +// datagram and counts it; the client's own copy is never touched either way. The +// consumer (the single TickAll driver) reads records in place and releases them. +// +// Records are 8-byte aligned: [i32 length][u32 stamp ms][bytes][pad]. A length of -1 +// means "the rest of the buffer is unused, continue at 0". Capacity is a power of two +// and a multiple of 8, so a wrap marker always fits. +// +// Pure code (native memory, no engine state); compiled into the NetMessageTests runner. +// ============================================================================ + +using System; +using System.Runtime.InteropServices; +using System.Threading; + +namespace RynthCore.Engine.Net; + +internal sealed unsafe class PacketRing +{ + private const int RecordHeader = 8; + private const int WrapMarker = -1; + + private readonly byte* _buf; + private readonly int _capacity; + private readonly int _mask; + // Byte counters that wrap (int, so reads and writes are single instructions on x86); + // only their difference and their low bits are used. + private int _head; // bytes written (producer) + private int _tail; // bytes released (consumer) + private int _writing; // producer claim + + /// Largest datagram accepted; anything longer is dropped (AC's are under 500 bytes). + public const int MaxDatagram = 2048; + + public long Written; + public long DroppedFull; + public long DroppedContended; + public long DroppedTooLong; + + /// The ring's memory is never freed: the detour may still be running at teardown. + /// Where the wrapping byte counters start (tests start them near int.MaxValue). + public PacketRing(int capacityPow2, int startCounter = 0) + { + _head = _tail = startCounter & ~7; + if (capacityPow2 < 4096 || (capacityPow2 & (capacityPow2 - 1)) != 0) + throw new ArgumentOutOfRangeException(nameof(capacityPow2)); + _capacity = capacityPow2; + _mask = capacityPow2 - 1; + _buf = (byte*)NativeMemory.AllocZeroed((nuint)capacityPow2); + } + + public int Capacity => _capacity; + + /// Bytes in use (approximate when read from another thread). + public int Used => unchecked(Volatile.Read(ref _head) - Volatile.Read(ref _tail)); + + /// Producer: copy one datagram in. Never blocks; false = dropped (counted). + public bool TryWrite(byte* data, int length, uint stampMs) + { + if (length <= 0 || length > MaxDatagram) + { + DroppedTooLong++; + return false; + } + if (Interlocked.CompareExchange(ref _writing, 1, 0) != 0) + { + Interlocked.Increment(ref DroppedContended); + return false; + } + try + { + int need = RecordHeader + ((length + 7) & ~7); + int head = _head; + int used = unchecked(head - Volatile.Read(ref _tail)); + int pos = head & _mask; + int toEnd = _capacity - pos; + int skip = need > toEnd ? toEnd : 0; + if (used + skip + need > _capacity) + { + DroppedFull++; + return false; + } + if (skip != 0) + { + *(int*)(_buf + pos) = WrapMarker; + pos = 0; + } + *(int*)(_buf + pos) = length; + *(uint*)(_buf + pos + 4) = stampMs; + Buffer.MemoryCopy(data, _buf + pos + RecordHeader, length, length); + Written++; + Volatile.Write(ref _head, unchecked(head + skip + need)); // publish after the bytes + return true; + } + finally + { + Volatile.Write(ref _writing, 0); + } + } + + /// + /// Consumer: the oldest record, in place. Call with the returned + /// token when done with it (the bytes stay valid until then). + /// + public bool TryPeek(out byte* data, out int length, out uint stampMs, out int releaseTo) + { + data = null; + length = 0; + stampMs = 0; + releaseTo = 0; + int tail = _tail; + int head = Volatile.Read(ref _head); + if (tail == head) + return false; + int pos = tail & _mask; + int len = *(int*)(_buf + pos); + if (len == WrapMarker) + { + tail = unchecked(tail + _capacity - pos); + pos = 0; + len = *(int*)_buf; + } + data = _buf + pos + RecordHeader; + length = len; + stampMs = *(uint*)(_buf + pos + 4); + releaseTo = unchecked(tail + RecordHeader + ((len + 7) & ~7)); + return true; + } + + public void Release(int releaseTo) => Volatile.Write(ref _tail, releaseTo); + + /// Consumer: drop everything queued (used when the stream is switched on again). + public void Clear() => Volatile.Write(ref _tail, Volatile.Read(ref _head)); +} diff --git a/src/RynthCore.Engine/Net/ServerMessageInterest.cs b/src/RynthCore.Engine/Net/ServerMessageInterest.cs new file mode 100644 index 0000000..8d08f43 --- /dev/null +++ b/src/RynthCore.Engine/Net/ServerMessageInterest.cs @@ -0,0 +1,84 @@ +// ============================================================================ +// RynthCore.Engine - Net/ServerMessageInterest.cs +// Which server messages one plugin asked for (PluginContract.SetServerMessageInterestFn). +// +// Opcodes and game event types are 16-bit on the wire in practice; each set is a +// 65536-bit map (8 KB), so a check is one load. Special entries: +// opcode 0xFFFFFFFF every message; +// opcode 0xF7B0 every game event (otherwise only the listed event types). +// Pure code; compiled into the NetMessageTests runner. +// ============================================================================ + +using System; + +namespace RynthCore.Engine.Net; + +internal sealed class ServerMessageInterest +{ + public const uint GameEventOpcode = 0xF7B0; + public const uint AllMessages = 0xFFFFFFFF; + public const int MaxEntries = 4096; + + private readonly ulong[] _opcodes = new ulong[65536 / 64]; + private readonly ulong[] _events = new ulong[65536 / 64]; + + public bool All { get; private set; } + public bool AllGameEvents { get; private set; } + public int OpcodeCount { get; private set; } + public int EventCount { get; private set; } + public bool IsEmpty => !All && OpcodeCount == 0 && EventCount == 0; + + /// Replaces the set. False (set left empty) for an entry out of range or too many entries. + public unsafe bool Set(uint* opcodes, int opcodeCount, uint* events, int eventCount) + { + Clear(); + if (opcodeCount < 0 || eventCount < 0 || opcodeCount > MaxEntries || eventCount > MaxEntries) + return false; + if ((opcodeCount > 0 && opcodes == null) || (eventCount > 0 && events == null)) + return false; + + for (int i = 0; i < opcodeCount; i++) + { + uint op = opcodes[i]; + if (op == AllMessages) { All = true; continue; } + if (op > 0xFFFF) { Clear(); return false; } + if (op == GameEventOpcode) AllGameEvents = true; + if (Add(_opcodes, op)) OpcodeCount++; + } + for (int i = 0; i < eventCount; i++) + { + uint ev = events[i]; + if (ev > 0xFFFF) { Clear(); return false; } + if (Add(_events, ev)) EventCount++; + } + return true; + } + + public void Clear() + { + Array.Clear(_opcodes); + Array.Clear(_events); + All = AllGameEvents = false; + OpcodeCount = EventCount = 0; + } + + /// is only looked at for opcode 0xF7B0. + public bool Wants(uint opcode, uint eventType) + { + if (All) return true; + if (opcode > 0xFFFF) return false; + if (opcode == GameEventOpcode) + return AllGameEvents || (eventType <= 0xFFFF && Has(_events, eventType)); + return Has(_opcodes, opcode); + } + + private static bool Has(ulong[] map, uint v) => (map[v >> 6] & (1UL << (int)(v & 63))) != 0; + + private static bool Add(ulong[] map, uint v) + { + ulong bit = 1UL << (int)(v & 63); + if ((map[v >> 6] & bit) != 0) return false; + map[v >> 6] |= bit; + return true; + } +} diff --git a/src/RynthCore.Engine/Net/ServerMessageStream.cs b/src/RynthCore.Engine/Net/ServerMessageStream.cs new file mode 100644 index 0000000..588834a --- /dev/null +++ b/src/RynthCore.Engine/Net/ServerMessageStream.cs @@ -0,0 +1,336 @@ +// ============================================================================ +// RynthCore.Engine - Net/ServerMessageStream.cs +// The reassembled server-message stream for plugins (API v78). +// +// RecvFrom detour (RawPacketHooks) plugin pump (PluginManager.ProcessPendingActions) +// OnDatagram: one volatile check; while Pump: drains the ring through the +// capturing, copies fragment datagrams -> FragmentReassembler; each whole message goes +// into PacketRing (no alloc, no lock, to the plugins that asked for it (and to the +// never waits; full = dropped + counted) /rc netmsg log tap and capture file). +// +// Strictly read-only: the detour copies the client's bytes after the real recvfrom +// returned them; it never alters, delays or drops anything the client gets. +// +// Capturing runs only while it is wanted: a plugin with a non-empty interest, or +// /rc netmsg log / capture. engine.json "ServerMessageStream": false (or /rc netmsg off) +// keeps it off whatever is wanted, and the detour is then exactly what it was before. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using RynthCore.Engine.Plugins; +using RynthCore.PluginSdk.Net; + +namespace RynthCore.Engine.Net; + +internal static unsafe class ServerMessageStream +{ + private const int RingBytes = 512 * 1024; + private const int MaxPacketsPerPump = 8192; + private const long MaxCaptureBytes = 32L * 1024 * 1024; + private const int MaxLogLinesPerKind = 5; + private const int MaxLogLines = 300; + + private static PacketRing? _ring; // created on first use, never freed (see PacketRing) + private static readonly FragmentReassembler Reassembler = new(); + private static readonly Sink MessageSink = new(); + private static volatile bool _capturing; + private static bool _sessionOff; + private static bool _pluginsWant; + + // Delivery counters (pump thread). + private static long _delivered, _dispatchedToPlugins; + private static long _pumpTicksTotal, _pumpTicksMax, _pumps; + + // /rc netmsg log: check the SDK parsers against the live server. + private static bool _logOn; + private static int _logLines; + private static readonly Dictionary Kinds = new(); + private static readonly Dictionary Opcodes = new(); + private static readonly object LogLock = new(); // Kinds/Opcodes: pump writes, chat commands read + + // /rc netmsg capture: raw fragment datagrams for tools\NetMessageTests. + private static volatile FileStream? _capture; // opened by the command, written and closed by the pump + private static volatile bool _captureStopRequested; + private static string _capturePath = ""; + private static long _captureBytes; + + private sealed class KindStats + { + public long Ok, Failed, Leftover; + public int Logged; + } + + /// True while the detour copies datagrams. + public static bool Capturing => _capturing; + + // ── receive hook side ─────────────────────────────────────────────────── + + /// Called by the RecvFrom detour after the real recvfrom, with the bytes it returned. + public static void OnDatagram(byte* data, int length) + { + if (!_capturing) + return; + PacketRing? ring = _ring; + if (ring == null || length < AcPacketWire.HeaderSize) + return; + uint flags = AcPacketWire.ReadU32(data + 4); + if ((flags & (PacketFlags.BlobFragments | PacketFlags.ConnectRequest)) == 0) + return; // acks, pings, time sync: nothing to reassemble + ring.TryWrite(data, length, (uint)Environment.TickCount); + } + + // ── pump side ─────────────────────────────────────────────────────────── + + /// + /// Once per ProcessPendingActions (the single TickAll driver). : + /// some initialized plugin has a non-empty interest. + /// + public static void Pump(bool pluginsWant) + { + _pluginsWant = pluginsWant; + if (_captureStopRequested) + { + _captureStopRequested = false; + StopCapture("stopped"); + } + bool want = EngineSettings.ServerMessageStream && !_sessionOff && (pluginsWant || _logOn || _capture != null); + if (want != _capturing) + { + if (want) + { + _ring ??= new PacketRing(RingBytes); + _ring.Clear(); + Reassembler.Reset(); + } + _capturing = want; + RynthLog.Compat($"ServerMessageStream: capture {(want ? "on" : "off")} (plugins={pluginsWant} log={_logOn} file={_capture != null})"); + } + + PacketRing? ring = _ring; + if (ring == null) + return; + if (!_capturing) + { + if (ring.Used != 0) ring.Clear(); + return; + } + + long start = System.Diagnostics.Stopwatch.GetTimestamp(); + long now = Environment.TickCount64; + int n = 0; + while (n < MaxPacketsPerPump && ring.TryPeek(out byte* data, out int len, out uint stamp, out int releaseTo)) + { + n++; + try + { + if (_capture != null) WriteCapture(data, len, stamp); + Reassembler.ProcessDatagram(data, len, now, MessageSink); + } + catch (Exception ex) + { + RynthLog.Compat($"ServerMessageStream: datagram failed - {ex.GetType().Name}: {ex.Message}"); + } + ring.Release(releaseTo); + } + if (n > 0) + { + long ticks = System.Diagnostics.Stopwatch.GetTimestamp() - start; + _pumps++; + _pumpTicksTotal += ticks; + if (ticks > _pumpTicksMax) _pumpTicksMax = ticks; + } + } + + private sealed class Sink : IServerMessageSink + { + public void OnServerMessage(uint fragmentSequence, byte* message, int length) + { + _delivered++; + uint opcode = AcPacketWire.ReadU32(message); + uint eventType = opcode == ServerMessage.GameEventOpcode && length >= 16 ? AcPacketWire.ReadU32(message + 12) : 0; + if (_logOn) + { + try { LogTap(opcode, eventType, message, length); } + catch (Exception ex) { RynthLog.Compat($"ServerMessageStream: log tap failed - {ex.GetType().Name}: {ex.Message}"); } + } + if (_pluginsWant) + _dispatchedToPlugins += PluginManager.DispatchServerMessage(opcode, eventType, message + 4, length - 4); + } + } + + // ── /rc netmsg ────────────────────────────────────────────────────────── + + public static string[] HandleCommand(string args) + { + string[] parts = args.Split(' ', StringSplitOptions.RemoveEmptyEntries); + string verb = parts.Length > 0 ? parts[0].ToLowerInvariant() : "status"; + string arg = parts.Length > 1 ? parts[1].ToLowerInvariant() : ""; + switch (verb) + { + case "on": + _sessionOff = false; + return new[] { EngineSettings.ServerMessageStream + ? "Server message stream allowed for this session (it runs while a plugin, the log or a capture wants it)." + : "engine.json has \"ServerMessageStream\": false - the stream stays off. Remove it (or set true) and restart." }; + case "off": + _sessionOff = true; + return new[] { "Server message stream off for this session (plugins get nothing until /rc netmsg on)." }; + case "log": + if (arg is "on" or "") + { + lock (LogLock) { _logLines = 0; Kinds.Clear(); Opcodes.Clear(); } + _logOn = true; + return new[] { "Server message log on: parsed messages go to the RynthCore log (NetMsg:), counts to /rc netmsg." }; + } + if (arg == "off") { _logOn = false; return new[] { "Server message log off." }; } + return new[] { "Usage: /rc netmsg log on|off" }; + case "capture": + if (arg is "on" or "") return new[] { StartCapture() }; + if (arg == "off") + { + if (_capture == null) return new[] { "Not capturing." }; + _captureStopRequested = true; // the pump closes it after its current write + return new[] { $"Capture stopping: {_capturePath}." }; + } + return new[] { "Usage: /rc netmsg capture on|off" }; + case "status": + return StatusLines(); + default: + return new[] { "Usage: /rc netmsg [status|on|off|log on|off|capture on|off]" }; + } + } + + public static string[] StatusLines() + { + var r = Reassembler; + var lines = new List + { + $"Server messages: setting {(EngineSettings.ServerMessageStream ? "on" : "OFF (engine.json)")}, session {(_sessionOff ? "off" : "on")}, " + + $"capturing {(_capturing ? "yes" : "no")}, hook {(Compatibility.RawPacketHooks.IsInstalled ? "installed" : "NOT installed")}; " + + $"plugins {PluginManager.ServerMessageSubscriberCount()} subscribed", + }; + if (_ring != null) + lines.Add($"Ring: {_ring.Written} datagrams copied, dropped {_ring.DroppedFull} full / {_ring.DroppedContended} contended / {_ring.DroppedTooLong} too long, {_ring.Used / 1024} KB queued"); + lines.Add($"Reassembly: {r.Packets} packets ({r.PacketsNoFragments} no fragments, {r.PacketsMalformed} malformed, {r.PacketsUnknownOptional} unknown header" + + (r.PacketsUnknownOptional > 0 ? $" last flags 0x{r.LastUnknownFlags:X8}" : "") + $"), {r.Fragments} fragments, " + + $"{r.Messages} messages ({r.MultiFragmentMessages} multi-fragment), dup {r.DuplicateFragments} fragments / {r.DuplicateMessages} messages, " + + $"bad {r.BadFragments}, oversized {r.Oversized}, evicted {r.EvictedStale} stale / {r.EvictedFull} full, {r.PartialCount} partial, {r.SessionResets} session resets"); + double tickUs = 1_000_000.0 / System.Diagnostics.Stopwatch.Frequency; + lines.Add($"Delivered {_delivered}, plugin calls {_dispatchedToPlugins}; drain (incl. plugin calls) avg {(_pumps > 0 ? _pumpTicksTotal * tickUs / _pumps : 0):0.0} us, max {_pumpTicksMax * tickUs:0} us over {_pumps} drains"); + lock (LogLock) + if (_logOn || Kinds.Count > 0) + { + string kinds = string.Join(", ", Kinds.OrderBy(k => k.Key).Select(k => $"{k.Key} {k.Value.Ok} ok" + + (k.Value.Failed > 0 ? $"/{k.Value.Failed} FAILED" : "") + (k.Value.Leftover > 0 ? $"/{k.Value.Leftover} leftover" : ""))); + lines.Add($"Parsed ({(_logOn ? "log on" : "log off")}): {(kinds.Length > 0 ? kinds : "none yet")}"); + string top = string.Join(" ", Opcodes.OrderByDescending(o => o.Value).Take(12).Select(o => $"{FormatKey(o.Key)}x{o.Value}")); + if (top.Length > 0) lines.Add($"Top opcodes: {top}"); + } + if (_capture != null) + lines.Add($"Capturing to {_capturePath} ({_captureBytes / 1024} KB)"); + return lines.ToArray(); + } + + private static string FormatKey(uint key) => key >= 0x10000 ? $"F7B0/{key & 0xFFFF:X4}" : $"{key:X4}"; + + // ── log tap ───────────────────────────────────────────────────────────── + + private static void LogTap(uint opcode, uint eventType, byte* message, int length) + { + uint key = opcode == ServerMessage.GameEventOpcode ? 0x10000u | (eventType & 0xFFFF) : opcode & 0xFFFF; + var msg = new ServerMessage(opcode, new ReadOnlySpan(message + 4, length - 4)); + NetMessageInfo info = NetMessages.Inspect(msg); + bool interesting = !info.Parsed || info.Leftover != 0; + bool log; + lock (LogLock) + { + Opcodes[key] = Opcodes.TryGetValue(key, out long c) ? c + 1 : 1; + if (!info.Known) + return; + if (!Kinds.TryGetValue(info.Kind, out KindStats? k)) + Kinds[info.Kind] = k = new KindStats(); + if (info.Parsed) k.Ok++; else k.Failed++; + if (info.Parsed && info.Leftover != 0) k.Leftover++; + log = _logLines < MaxLogLines && (k.Logged < MaxLogLinesPerKind || interesting); + if (log) + { + _logLines++; + k.Logged++; + } + } + if (log) + { + string hex = interesting ? " bytes=" + Convert.ToHexString(new ReadOnlySpan(message, Math.Min(length, 96))) : ""; + RynthLog.Compat($"NetMsg: {info.Kind} len={length} {(info.Parsed ? "ok" : "FAILED")}" + + (info.Leftover != 0 ? $" leftover={info.Leftover}" : "") + $" {info.Summary}{hex}"); + } + } + + // ── capture file ──────────────────────────────────────────────────────── + // Format "RNC1": the 4 magic bytes, then per datagram [u32 stamp ms][u16 length][bytes]. + + private static string StartCapture() + { + if (_capture != null) + return $"Already capturing to {_capturePath}."; + if (!EngineSettings.ServerMessageStream || _sessionOff) + return "The server message stream is off; /rc netmsg on first (engine.json must allow it)."; + try + { + LogPaths.EnsureLogDirectory(); + _capturePath = Path.Combine(LogPaths.LogDirectory, $"netcapture-{Environment.ProcessId}-{DateTime.Now:yyyyMMdd-HHmmss}.rnc"); + _capture = new FileStream(_capturePath, FileMode.CreateNew, FileAccess.Write, FileShare.Read, 64 * 1024); + _capture.Write("RNC1"u8); + _captureBytes = 4; + return $"Capturing server datagrams to {_capturePath} (stops at {MaxCaptureBytes / (1024 * 1024)} MB; holds chat text, keep it local)."; + } + catch (Exception ex) + { + _capture = null; + return $"Capture failed: {ex.Message}"; + } + } + + private static string StopCapture(string why) + { + if (_capture == null) + return "Not capturing."; + try { _capture.Dispose(); } catch { } + _capture = null; + string msg = $"Capture {why}: {_capturePath} ({_captureBytes / 1024} KB)."; + RynthLog.Compat("ServerMessageStream: " + msg); + return msg; + } + + private static void WriteCapture(byte* data, int len, uint stamp) + { + FileStream? f = _capture; + if (f == null) return; + Span head = stackalloc byte[6]; + System.Buffers.Binary.BinaryPrimitives.WriteUInt32LittleEndian(head, stamp); + System.Buffers.Binary.BinaryPrimitives.WriteUInt16LittleEndian(head.Slice(4), (ushort)len); + try + { + f.Write(head); + f.Write(new ReadOnlySpan(data, len)); + _captureBytes += 6 + len; + } + catch (Exception ex) + { + StopCapture($"failed ({ex.Message})"); + return; + } + if (_captureBytes >= MaxCaptureBytes) + StopCapture("reached its size cap"); + } + + /// Engine shutdown: close a capture file. The ring stays allocated (see PacketRing). + public static void Shutdown() + { + _capturing = false; + if (_capture != null) StopCapture("closed at shutdown"); + } +} diff --git a/src/RynthCore.Engine/Plugins/EngineSettings.cs b/src/RynthCore.Engine/Plugins/EngineSettings.cs index e8692b7..1698fcd 100644 --- a/src/RynthCore.Engine/Plugins/EngineSettings.cs +++ b/src/RynthCore.Engine/Plugins/EngineSettings.cs @@ -33,6 +33,9 @@ internal static class EngineSettings private static DecalBridgeMode _decalBridgeMode = DecalBridgeMode.Auto; private static bool _decalInGameImGui = true; private static bool _decalStandDown = true; + // "DisabledUiHooks": the UI hooks (Compatibility/UiHookRegistry) switched off by name. + private static readonly HashSet _disabledUiHooks = new(StringComparer.OrdinalIgnoreCase); + private static bool _serverMessageStream = true; private static bool _loaded; public static IReadOnlyList PluginPaths @@ -279,6 +282,39 @@ internal static class EngineSettings } } + /// "DisabledUiHooks" in engine.json: an array of UI hook names + /// (Compatibility/UiHookRegistry: UseNewMode, ClientCleanup, StartTooltip, ResetTooltip, + /// CheckTooltip, StartDragandDrop, CatchDroppedItem). A listed hook is not installed at + /// the next start. Missing = every hook on. /rc hooks on|off <name> edits it. + public static bool IsUiHookEnabled(string name) + { + EnsureLoaded(); + return !_disabledUiHooks.Contains(name); + } + + /// Switches a UI hook on or off for the next start, and saves engine.json. + public static void SetUiHookEnabled(string name, bool enabled) + { + EnsureLoaded(); + bool changed = enabled ? _disabledUiHooks.Remove(name) : _disabledUiHooks.Add(name); + if (changed) + Save(); + } + + /// "ServerMessageStream" in engine.json (default true): the kill switch for the + /// reassembled server-message stream (Net/ServerMessageStream.cs, plugin API v78). Even when + /// true, nothing is copied off the receive hook until a plugin asks for messages (or + /// /rc netmsg log|capture is on). false = the RecvFrom detour does exactly what it did + /// before the stream existed; /rc netmsg on can't override it. + public static bool ServerMessageStream + { + get + { + EnsureLoaded(); + return _serverMessageStream; + } + } + public static void AddPluginPath(string path) { EnsureLoaded(); @@ -407,12 +443,26 @@ internal static class EngineSettings (dsdEl.ValueKind == JsonValueKind.True || dsdEl.ValueKind == JsonValueKind.False)) _decalStandDown = dsdEl.GetBoolean(); + if (doc.RootElement.TryGetProperty("ServerMessageStream", out var smsEl) && + (smsEl.ValueKind == JsonValueKind.True || smsEl.ValueKind == JsonValueKind.False)) + _serverMessageStream = smsEl.GetBoolean(); + if (doc.RootElement.TryGetProperty("PreventIdleLogoff", out var pilEl) && (pilEl.ValueKind == JsonValueKind.True || pilEl.ValueKind == JsonValueKind.False)) { _preventIdleLogoff = pilEl.GetBoolean(); } + if (doc.RootElement.TryGetProperty("DisabledUiHooks", out var duhEl) && + duhEl.ValueKind == JsonValueKind.Array) + { + foreach (var el in duhEl.EnumerateArray()) + { + if (el.ValueKind == JsonValueKind.String && el.GetString() is { Length: > 0 } hookName) + _disabledUiHooks.Add(hookName.Trim()); + } + } + if (doc.RootElement.TryGetProperty("LoggingLevel", out var logLevelEl) && logLevelEl.ValueKind == JsonValueKind.String) { @@ -462,6 +512,15 @@ internal static class EngineSettings w.WriteBoolean("DecalInGameImGui", false); if (!_decalStandDown) // default true: leave the file as it was w.WriteBoolean("DecalStandDown", false); + if (_disabledUiHooks.Count > 0) // default none: leave the file as it was + { + w.WriteStartArray("DisabledUiHooks"); + foreach (string hookName in _disabledUiHooks) + w.WriteStringValue(hookName); + w.WriteEndArray(); + } + if (!_serverMessageStream) // default true: leave the file as it was + w.WriteBoolean("ServerMessageStream", false); w.WriteEndObject(); } File.WriteAllBytes(SettingsPath, ms.ToArray()); diff --git a/src/RynthCore.Engine/Plugins/LoadedPlugin.cs b/src/RynthCore.Engine/Plugins/LoadedPlugin.cs index 35a96a7..b2ce607 100644 --- a/src/RynthCore.Engine/Plugins/LoadedPlugin.cs +++ b/src/RynthCore.Engine/Plugins/LoadedPlugin.cs @@ -60,6 +60,21 @@ internal sealed class LoadedPlugin /// Set after the first RenderOverlay call has been logged (render thread only). public bool RenderOverlayLogged { get; set; } + // ─── v77 UI exports (resolved lazily by PluginManager.ResolveUiExports) ─── + public bool UiExportsResolved { get; set; } + public IntPtr OnScreenChangedPtr { get; set; } + public IntPtr OnClientCleanupPtr { get; set; } + public IntPtr OnTooltipShowPtr { get; set; } + public IntPtr OnTooltipHidePtr { get; set; } + public IntPtr OnDragStartPtr { get; set; } + public IntPtr OnItemDroppedPtr { get; set; } + + // ─── v78 server messages (resolved when the plugin calls SetServerMessageInterest) ── + /// void RynthPluginOnServerMessage(uint opcode, byte* data, int length), Cdecl. + public IntPtr OnServerMessagePtr { get; set; } + /// What the plugin asked for; null or empty = nothing. + public Net.ServerMessageInterest? ServerMessageInterest { get; set; } + // ─── Runtime state ─────────────────────────────────────────────── public bool Initialized { get; set; } public bool LoginCompleteDispatched { get; set; } @@ -68,6 +83,14 @@ internal sealed class LoadedPlugin public string DisplayName { get; set; } = ""; public string VersionString { get; set; } = ""; + /// + /// The manifest embedded in the DLL (read before loading it; see PluginManifestGate), or null + /// for a plugin without one. Set by PluginManager after PluginLoader loads the plugin. + /// + public RynthCore.PluginSdk.Manifest.RynthPluginManifest? Manifest { get; set; } + /// Why the plugin was not started (a required plugin missing or failed); empty otherwise. + public string NotStartedReason { get; set; } = ""; + /// /// Drops managed delegates wrapping exports so the native module can fully unload after /// the host calls FreeLibrary (hot-reload / rescan). diff --git a/src/RynthCore.Engine/Plugins/PluginContract.cs b/src/RynthCore.Engine/Plugins/PluginContract.cs index b4b0de8..72d76f3 100644 --- a/src/RynthCore.Engine/Plugins/PluginContract.cs +++ b/src/RynthCore.Engine/Plugins/PluginContract.cs @@ -15,6 +15,9 @@ // off (Avalonia mode): only windows that have no // Avalonia panel. Gated by engine.json // "EnablePluginOverlayWindows" (default true). +// void RynthPluginOnServerMessage(uint opcode, byte* data, int length) +// — v78, reassembled server messages the plugin +// asked for with SetServerMessageInterestFn // ============================================================================ using System; @@ -785,15 +788,166 @@ internal struct RynthCoreAPI /// after it). Returns 1 if sent or queued. Requires API v76+. public IntPtr CloseContainerFn; - /// v77: int GetMergeStackResult(uint sourceObjectId, uint targetObjectId, int* amount, int* ageMs): + /// v77: int GetScreenMode(int* previousMode): the client's screen (UIFlow mode, + /// Compatibility/UiFlowHooks.cs): 0x10000001 intro, 0x10000002 disconnected, 0x10000008 the + /// world, 0x10000009 epilogue, 0x1000000A character select, 0x1000000B character creation; + /// 0 = not known yet. *previousMode (may be null) = the screen before. Any thread. + /// Requires API v77+. + public IntPtr GetScreenModeFn; + + /// v77: uint GetUiHookFlags(void): which UI hooks are live, so a plugin knows + /// which v77 callbacks can arrive. bit0 RynthPluginOnScreenChanged from the UseNewMode hook, + /// bit1 ... from the +0x8C mode poll instead (one tick late), bit2 RynthPluginOnClientCleanup, + /// bit3 RynthPluginOnTooltipShow, bit4 RynthPluginOnTooltipHide, bit5 RynthPluginOnDragStart, + /// bit6 RynthPluginOnItemDropped, bit7 Client::Cleanup has started. Any thread. + /// Requires API v77+. + public IntPtr GetUiHookFlagsFn; + + /// v78: int SetServerMessageInterest(uint* opcodes, int opcodeCount, uint* gameEvents, + /// int eventCount): which reassembled server messages the calling plugin wants on its + /// void RynthPluginOnServerMessage(uint opcode, byte* data, int length) export (Cdecl; + /// data = the message after its u32 opcode, valid only during the call; for 0xF7B0 it starts + /// with object id, sequence, event type). Replaces the plugin's previous set; both counts 0 = + /// none. Opcodes are 16-bit; 0xF7B0 = every game event, 0xFFFFFFFF = every message; + /// gameEvents lists single event types. Read-only: the client's packets are never changed. + /// Call from the plugin's Init, Tick or an event (the engine finds the caller that way). + /// Returns 1 = streaming, 2 = accepted but the stream is off (engine.json + /// "ServerMessageStream": false or /rc netmsg off), 0 = the plugin has no + /// RynthPluginOnServerMessage export, -1 = caller unknown (another thread), -3 = bad + /// arguments. Requires API v78+. + public IntPtr SetServerMessageInterestFn; + + /// v79: int GetTrainingInfo(TrainingInfoNative* info, TrainingEntryNative* entries, + /// int maxEntries): what spending experience would do (Compatibility/TrainingApi.cs): the + /// unassigned XP, skill credits and level, and one entry per attribute (1..6), vital maximum + /// (1 health, 3 stamina, 5 mana) and portal-SkillTable skill with ranks, XP spent, base and + /// buffed value and the XP for +1 / +10 from the portal XpTable. Set info->Size to sizeof + /// before the call (info may be null; entries may be null to ask for the count). Returns the + /// number of entries there are (at most maxEntries written), 0 when there are no numbers yet + /// (not in the world, or the first read hasn't happened: it is asked for by this call and + /// comes within a couple of seconds). Asking keeps the numbers coming every 2 s for 5 s. + /// Any thread. Requires API v79+. + public IntPtr GetTrainingInfoFn; + + /// v79: int Raise(uint kind, uint stype, uint ranks, long expectedXp, long* xpSent): + /// spend unassigned XP like the character window's "+": kind 1 attribute (stype 1..6), 2 vital + /// (1 health, 3 stamina, 5 mana), 3 trained or specialized skill; ranks 1..100. The engine works + /// the XP out from the numbers GetTrainingInfo reports and sends it with the client's own + /// CM_Train sender (0x0045 / 0x0044 / 0x0046) on AC's main thread. expectedXp > 0 must equal + /// that XP (the cost the user confirmed), else nothing is sent; 0 skips the comparison. + /// *xpSent (may be null) = the XP sent. Returns 1 sent or queued, 0 the senders aren't bound, + /// -1 not in the world, -2 bad arguments, -3 no numbers yet, -4 the numbers are over 3 s old + /// (a read was asked for: call again shortly), -5 the cost changed, -6 not enough XP, -7 not + /// raisable (top rank, untrained skill), -8 an earlier raise hasn't landed yet, -9 the send + /// failed. Any thread. Requires API v79+. + public IntPtr RaiseFn; + + /// v79: int TrainSkill(uint stype, int expectedCredits): train an untrained + /// skill with skill credits, as the skills window's train dialog does (0x0047, exactly the + /// portal SkillTable's TrainedCost; the server refuses anything else). expectedCredits > 0 + /// must equal that price; 0 skips the comparison. Same results and threading as Raise. + /// Requires API v79+. + public IntPtr TrainSkillFn; + + /// v80: int GetMergeStackResult(uint sourceObjectId, uint targetObjectId, int* amount, int* ageMs): /// outcome of the latest MergeStackInternal(source, target) request: 0 none, 1 queued, /// 2 sent (amount = units sent), 3 skipped because the target was already full, /// 4 failed (invalid ids / AC rejected / threw), 5 dropped (main-thread queue full). /// ageMs = how long ago the outcome was recorded. Either out pointer may be null. - /// The thunk is cdecl. Any thread. Requires API v77+. APPENDED-AT-END for ABI safety. + /// The thunk is cdecl. Any thread. Requires API v80+ (it was v77 on QOL-items before + /// upstream's v77-v79 landed; plugins built against that SDK must be rebuilt). public IntPtr GetMergeStackResultFn; } +/// v79 bits. +internal static class TrainingInfoFlags +{ + public const uint InWorld = 1u << 0; + /// The attribute, vital and skill raise senders are bound on this client. + public const uint RaiseBound = 1u << 1; + /// The train-with-credits sender is bound. + public const uint TrainBound = 1u << 2; + /// The player's numbers have been read (entries follow). + public const uint HaveNumbers = 1u << 3; + /// The portal SkillTable and XpTable are loaded. + public const uint HaveTables = 1u << 4; + /// A raise or train from the API hasn't shown up in the numbers yet. + public const uint Busy = 1u << 5; +} + +/// v79 bits. +internal static class TrainingEntryFlags +{ + /// Can be raised with XP (an attribute, a vital, a trained or specialized skill below the top rank). + public const uint Raisable = 1u << 0; + public const uint AtTop = 1u << 1; + /// Skills: usable untrained (the SkillTable's min level 1). + public const uint UsableUntrained = 1u << 2; + /// Skills: untrained, and the SkillTable prices training it (TrainCredits). + public const uint Trainable = 1u << 3; +} + +/// +/// v79 GetTrainingInfo header. Pack 4, 64 bytes; later versions only append. +/// Mirrored by RynthCore.PluginSdk (TrainingInfoNative in RynthCoreApiNative.cs). +/// +[StructLayout(LayoutKind.Sequential, Pack = 4)] +internal unsafe struct TrainingInfoNative +{ + /// In: the caller's sizeof. Out: bytes written. + public uint Size; + /// . + public uint Flags; + /// Changes whenever any number changes. + public uint SnapshotVersion; + /// Milliseconds since the numbers were read; 0xFFFFFFFF = never. + public uint AgeMs; + /// -1 when unknown. + public long UnassignedXp; + /// -1 when unknown. + public long TotalXp; + public int Level; + /// -1 when unknown. + public int SkillCredits; + public int EntryCount; + /// Raise refuses numbers older than this (Stale). + public int StaleAfterMs; + public fixed uint Reserved[4]; +} + +/// +/// v79 GetTrainingInfo entry: one attribute, vital or skill. Pack 4, 64 bytes; later +/// versions only append. Mirrored by RynthCore.PluginSdk (TrainingEntryNative). +/// +[StructLayout(LayoutKind.Sequential, Pack = 4)] +internal struct TrainingEntryNative +{ + /// 1 attribute, 2 vital, 3 skill. + public uint Kind; + /// Attribute 1..6, vital maximum 1 / 3 / 5, skill id. + public uint Stype; + /// Skills: 0 not in the table, 1 untrained, 2 trained, 3 specialized. 0 otherwise. + public uint Class; + public uint Ranks; + public uint XpSpent; + /// The innate (starting) level. + public uint Innate; + /// Without enchantments (a vital's maximum). + public int Base; + public int Buffed; + /// XP for one more rank; -1 at the top or not raisable. + public long CostOne; + /// XP for ten more ranks; -1 when fewer than ten are left or not raisable. + public long CostTen; + public int RanksLeft; + /// Ranks in a row the unassigned XP buys now. + public int Affordable; + /// Untrained skills: the credits to train it (0 = can't be trained from the client). + public int TrainCredits; + /// . + public uint Flags; +} + /// v72 bits. internal static class TradeStateFlags { @@ -976,11 +1130,8 @@ internal unsafe struct VendorTradeStatusNative -/// Current API version. Bump when adding fields to RynthCoreAPI. -internal static class PluginContractVersion -{ - public const uint Current = 77; // v77: GetMergeStackResult -} +// PluginContractVersion (the current API version) lives in PluginContractVersion.cs, which +// the SDK and the launcher compile in too, so their copies can't drift from the engine's. internal static class ClientActionHookFlags { @@ -1089,6 +1240,17 @@ internal delegate void PluginTickDelegate(); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void PluginRenderDelegate(); +// v77 callbacks (exports resolved by PluginManager.ResolveUiExports, not PluginLoader): +// void RynthPluginOnScreenChanged(int oldMode, int newMode) - UIFlow mode change (GetScreenModeFn values) +// void RynthPluginOnClientCleanup(void) - Client::Cleanup starting; no ticks after it +// void RynthPluginOnTooltipShow(uint objectId, uint spellId) - AC shows a tooltip (0/0: not an item or spell) +// void RynthPluginOnTooltipHide(void) - that tooltip is gone +// void RynthPluginOnDragStart(uint objectId, uint spellId, uint iconId) - a drag out of AC's UI began +// void RynthPluginOnItemDropped(uint objectId, uint spellId, uint targetElementId) - AC caught a drop +// All cdecl, all on the plugin pump like the other events, except OnClientCleanup (see +// PluginManager.DispatchClientCleanup). + + // ─── Log callback that plugins can call ───────────────────────────────── [UnmanagedFunctionPointer(CallingConvention.Cdecl)] @@ -1501,3 +1663,21 @@ internal unsafe delegate int GetServerInfoCallbackDelegate(byte* worldName, int [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate int CloseContainerCallbackDelegate(uint containerId); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate int GetScreenModeCallbackDelegate(int* previousMode); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal delegate uint GetUiHookFlagsCallbackDelegate(); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate int SetServerMessageInterestCallbackDelegate(uint* opcodes, int opcodeCount, uint* gameEvents, int eventCount); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate int GetTrainingInfoCallbackDelegate(TrainingInfoNative* info, TrainingEntryNative* entries, int maxEntries); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate int RaiseCallbackDelegate(uint kind, uint stype, uint ranks, long expectedXp, long* xpSent); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal delegate int TrainSkillCallbackDelegate(uint stype, int expectedCredits); diff --git a/src/RynthCore.Engine/Plugins/PluginContractVersion.cs b/src/RynthCore.Engine/Plugins/PluginContractVersion.cs new file mode 100644 index 0000000..0aabc31 --- /dev/null +++ b/src/RynthCore.Engine/Plugins/PluginContractVersion.cs @@ -0,0 +1,20 @@ +// ============================================================================ +// RynthCore.Engine - Plugins/PluginContractVersion.cs +// The plugin API's version: the number of the last table (RynthCoreAPI) layout. +// +// One file, compiled into three assemblies so they can't disagree: +// - the engine (this folder), which hands it to plugins in RynthCoreAPI.Version; +// - the SDK (RynthCore.PluginSdk), as RynthCoreHost.CurrentApiVersion; +// - the launcher (RynthCore.App.Avalonia), as the API of the engine it installed, +// to hold back feed plugins whose minEngineApi is newer. +// tools\PluginManifestTests also checks the SDK's table covers this version. +// ============================================================================ + +namespace RynthCore.Engine.Plugins; + +/// Current API version. Bump when adding fields to RynthCoreAPI (and the SDK's RynthCoreApiNative). +internal static class PluginContractVersion +{ + // v80: GetMergeStackResult (was v77 on QOL-items, renumbered after upstream's v77-v79). + public const uint Current = 80; +} diff --git a/src/RynthCore.Engine/Plugins/PluginManager.UiHooks.cs b/src/RynthCore.Engine/Plugins/PluginManager.UiHooks.cs new file mode 100644 index 0000000..ec1dfc8 --- /dev/null +++ b/src/RynthCore.Engine/Plugins/PluginManager.UiHooks.cs @@ -0,0 +1,282 @@ +// ============================================================================ +// RynthCore.Engine - Plugins/PluginManager.UiHooks.cs +// +// API v77 (2026-10-05): the plugin side of Compatibility/UiFlowHooks and +// Compatibility/UiElementHooks. +// +// Callbacks (optional plugin exports, cdecl; looked up here on first use, not by +// PluginLoader): +// RynthPluginOnScreenChanged(int oldMode, int newMode) +// RynthPluginOnClientCleanup() +// RynthPluginOnTooltipShow(uint objectId, uint spellId) +// RynthPluginOnTooltipHide() +// RynthPluginOnDragStart(uint objectId, uint spellId, uint iconId) +// RynthPluginOnItemDropped(uint objectId, uint spellId, uint targetElementId) +// The hooks queue them from AC's main thread; ProcessPendingActions delivers them +// on the plugin pump in the order they happened (one queue), like every other +// event. OnClientCleanup is the exception: it must arrive while AC's UI still +// stands, so the Client::Cleanup detour (AC's main thread) waits, bounded, for the +// pump to deliver it, and delivers it itself (under the pump's frame guard) if the +// pump doesn't come. After it the pump delivers no more events and TickAll stops +// ticking. Plugins: keep OnClientCleanup short and never wait on AC's main thread +// inside it (it may be running on it, or waiting for you). +// +// Table functions: GetScreenModeFn, GetUiHookFlagsFn (PluginContract.cs). +// Older engines have neither the table fields nor the callbacks: a plugin checks +// RynthCoreAPI.Version >= 77 before reading the fields (RynthCoreHost.HasUiHooks). +// ============================================================================ +using System; +using System.Collections.Generic; +using System.Threading; +using RynthCore.Engine.Compatibility; + +namespace RynthCore.Engine.Plugins; + +internal static partial class PluginManager +{ + private static GetScreenModeCallbackDelegate? _getScreenModeCallback; // v77 + private static GetUiHookFlagsCallbackDelegate? _getUiHookFlagsCallback; // v77 + + /// The thread that ran TickAll last (the plugin pump). + private static int _tickThread; + + private enum UiEventKind : byte { ScreenChanged, TooltipShow, TooltipHide, DragStart, ItemDropped } + private readonly record struct PendingUiEvent(UiEventKind Kind, uint A, uint B, uint C); + + private const int MaxPendingUiEvents = 256; + private static readonly Queue _pendingUiEvents = new(); + private static readonly object PendingUiEventsLock = new(); + + // Client::Cleanup: 0 nothing, 1 waiting for the pump, 2 delivered (or nobody to tell). + private static int _cleanupState; + + // ── Queueing (AC's main thread) ────────────────────────────────────── + + public static void QueueScreenChanged(int oldMode, int newMode) => QueueUiEvent(UiEventKind.ScreenChanged, (uint)oldMode, (uint)newMode, 0); + public static void QueueTooltipShown(uint objectId, uint spellId) => QueueUiEvent(UiEventKind.TooltipShow, objectId, spellId, 0); + public static void QueueTooltipHidden() => QueueUiEvent(UiEventKind.TooltipHide, 0, 0, 0); + public static void QueueDragStarted(uint objectId, uint spellId, uint iconId) => QueueUiEvent(UiEventKind.DragStart, objectId, spellId, iconId); + public static void QueueItemDropped(uint objectId, uint spellId, uint targetElementId) => QueueUiEvent(UiEventKind.ItemDropped, objectId, spellId, targetElementId); + + private static void QueueUiEvent(UiEventKind kind, uint a, uint b, uint c) + { + if (!_initialized || _plugins.Count == 0 || Volatile.Read(ref _cleanupState) != 0) + return; + lock (PendingUiEventsLock) + { + if (_pendingUiEvents.Count >= MaxPendingUiEvents) + _pendingUiEvents.Dequeue(); + _pendingUiEvents.Enqueue(new PendingUiEvent(kind, a, b, c)); + } + } + + // ── Delivery (plugin pump) ─────────────────────────────────────────── + + private static void ResolveUiExports(LoadedPlugin plugin) + { + if (plugin.UiExportsResolved || plugin.ModuleHandle == IntPtr.Zero) + return; + plugin.UiExportsResolved = true; + plugin.OnScreenChangedPtr = GetProcAddress(plugin.ModuleHandle, "RynthPluginOnScreenChanged"); + plugin.OnClientCleanupPtr = GetProcAddress(plugin.ModuleHandle, "RynthPluginOnClientCleanup"); + plugin.OnTooltipShowPtr = GetProcAddress(plugin.ModuleHandle, "RynthPluginOnTooltipShow"); + plugin.OnTooltipHidePtr = GetProcAddress(plugin.ModuleHandle, "RynthPluginOnTooltipHide"); + plugin.OnDragStartPtr = GetProcAddress(plugin.ModuleHandle, "RynthPluginOnDragStart"); + plugin.OnItemDroppedPtr = GetProcAddress(plugin.ModuleHandle, "RynthPluginOnItemDropped"); + int count = (plugin.OnScreenChangedPtr != IntPtr.Zero ? 1 : 0) + (plugin.OnClientCleanupPtr != IntPtr.Zero ? 1 : 0) + + (plugin.OnTooltipShowPtr != IntPtr.Zero ? 1 : 0) + (plugin.OnTooltipHidePtr != IntPtr.Zero ? 1 : 0) + + (plugin.OnDragStartPtr != IntPtr.Zero ? 1 : 0) + (plugin.OnItemDroppedPtr != IntPtr.Zero ? 1 : 0); + if (count > 0) + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} takes {count} v77 UI callback(s)."); + } + + private static unsafe void DispatchQueuedUiEvents() + { + if (!_initialized || _plugins.Count == 0) + return; + + PendingUiEvent[] pending; + lock (PendingUiEventsLock) + { + if (_pendingUiEvents.Count == 0) + return; + pending = _pendingUiEvents.ToArray(); + _pendingUiEvents.Clear(); + } + + foreach (PendingUiEvent evt in pending) + { + for (int i = 0; i < _plugins.Count; i++) + { + var plugin = _plugins[i]; + if (!plugin.Initialized || plugin.Failed) + continue; + ResolveUiExports(plugin); + IntPtr fn = evt.Kind switch + { + UiEventKind.ScreenChanged => plugin.OnScreenChangedPtr, + UiEventKind.TooltipShow => plugin.OnTooltipShowPtr, + UiEventKind.TooltipHide => plugin.OnTooltipHidePtr, + UiEventKind.DragStart => plugin.OnDragStartPtr, + _ => plugin.OnItemDroppedPtr, + }; + if (fn == IntPtr.Zero) + continue; + + LoadedPlugin? outer = EnterDispatch(plugin); + try + { + switch (evt.Kind) + { + case UiEventKind.ScreenChanged: + ((delegate* unmanaged[Cdecl])fn)((int)evt.A, (int)evt.B); + break; + case UiEventKind.TooltipShow: + ((delegate* unmanaged[Cdecl])fn)(evt.A, evt.B); + break; + case UiEventKind.TooltipHide: + ((delegate* unmanaged[Cdecl])fn)(); + break; + case UiEventKind.DragStart: + case UiEventKind.ItemDropped: + ((delegate* unmanaged[Cdecl])fn)(evt.A, evt.B, evt.C); + break; + } + } + catch (Exception ex) + { + plugin.Failed = true; + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} On{evt.Kind} threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); + } + finally + { + LeaveDispatch(outer); + } + } + } + } + + // ── Client::Cleanup ────────────────────────────────────────────────── + + /// + /// AC's main thread, inside the Client::Cleanup detour before AC tears anything down. + /// Plugins are called from the plugin pump (a managed thread: a NativeAOT engine must not + /// run plugin code on AC's threads, the 2026-05-16 fail-fast), never from two threads at + /// once. So: the pump delivers RynthPluginOnClientCleanup at the top of its next frame + /// (ProcessClientCleanup, every ~16 ms) while this waits for up to half of + /// . A pump that doesn't come (no frames: the device is + /// gone) leaves it to this thread, which delivers it holding the pump's frame guard + /// (EngineFrameController.TryRunOutsidePumpFrame). Exactly once either way; after the + /// full timeout AC's cleanup goes ahead regardless. + /// + public static void DispatchClientCleanup(int timeoutMs) + { + if (!_initialized || _plugins.Count == 0) + { + Volatile.Write(ref _cleanupState, 2); + return; + } + if (Interlocked.CompareExchange(ref _cleanupState, 1, 0) != 0) + return; + + int pump = Volatile.Read(ref _tickThread); + if (pump == 0 || pump == Environment.CurrentManagedThreadId) + { + TakeAndDeliverClientCleanup("the calling thread (no separate pump)"); + return; + } + + long start = Environment.TickCount64; + long pumpUntil = start + timeoutMs / 2, until = start + timeoutMs; + while (Volatile.Read(ref _cleanupState) != 2) + { + long now = Environment.TickCount64; + if (now >= pumpUntil + && ImGuiBackend.EngineFrameController.TryRunOutsidePumpFrame(() => TakeAndDeliverClientCleanup("AC's main thread (the pump didn't come)"))) + return; + if (now >= until) + { + RynthLog.Plugin($"PluginManager: OnClientCleanup not delivered within {timeoutMs} ms (a pump frame is running); AC's cleanup goes ahead, the pump delivers it at its next frame."); + return; + } + Thread.Sleep(5); + } + } + + /// + /// Plugin pump, top of ProcessPendingActions. True once Client::Cleanup started: the + /// rest of the frame's events are dropped (AC is tearing down what they describe). + /// + private static bool ProcessClientCleanup() + { + if (Volatile.Read(ref _cleanupState) == 0) + return UiFlowHooks.ClientCleanupStarted; + TakeAndDeliverClientCleanup("the plugin pump"); + return true; + } + + // 1 -> 2 exactly once, whoever gets there first. + private static void TakeAndDeliverClientCleanup(string where) + { + if (Interlocked.CompareExchange(ref _cleanupState, 2, 1) != 1) + return; + DeliverClientCleanup(where); + } + + private static unsafe void DeliverClientCleanup(string where) + { + lock (PendingUiEventsLock) + _pendingUiEvents.Clear(); + int told = 0; + for (int i = 0; i < _plugins.Count; i++) + { + var plugin = _plugins[i]; + if (!plugin.Initialized || plugin.Failed) + continue; + ResolveUiExports(plugin); + if (plugin.OnClientCleanupPtr == IntPtr.Zero) + continue; + LoadedPlugin? outer = EnterDispatch(plugin); + try + { + ((delegate* unmanaged[Cdecl])plugin.OnClientCleanupPtr)(); + told++; + } + catch (Exception ex) + { + plugin.Failed = true; + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} OnClientCleanup threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); + } + finally + { + LeaveDispatch(outer); + } + } + RynthLog.Plugin($"PluginManager: OnClientCleanup delivered to {told} plugin(s) from {where}; no more plugin ticks or events."); + } + + // ── Table functions ────────────────────────────────────────────────── + + /// v77: see PluginContract.GetScreenModeFn. + private static unsafe int GetScreenModeAction(int* previousMode) + { + if (previousMode != null) + *previousMode = UiFlowHooks.PreviousMode; + return UiFlowHooks.CurrentMode; + } + + /// v77: see PluginContract.GetUiHookFlagsFn. + private static uint GetUiHookFlagsAction() + { + uint flags = 0; + if (UiFlowHooks.ScreenHookLive) flags |= 1u << 0; + else flags |= 1u << 1; // the +0x8C poll drives OnScreenChanged + if (UiFlowHooks.CleanupHookLive) flags |= 1u << 2; + if (UiElementHooks.TooltipShowLive) flags |= 1u << 3; + if (UiElementHooks.TooltipHideLive) flags |= 1u << 4; + if (UiElementHooks.DragStartLive) flags |= 1u << 5; + if (UiElementHooks.DropLive) flags |= 1u << 6; + if (UiFlowHooks.ClientCleanupStarted) flags |= 1u << 7; + return flags; + } +} diff --git a/src/RynthCore.Engine/Plugins/PluginManager.cs b/src/RynthCore.Engine/Plugins/PluginManager.cs index 8c788db..ebc7651 100644 --- a/src/RynthCore.Engine/Plugins/PluginManager.cs +++ b/src/RynthCore.Engine/Plugins/PluginManager.cs @@ -12,10 +12,11 @@ using System.Threading; using RynthCore.Engine.Compatibility; using RynthCore.Engine.UI.ScriptWindows; using RynthCore.Engine.D3D9; +using RynthCore.PluginSdk.Manifest; namespace RynthCore.Engine.Plugins; -internal static class PluginManager +internal static partial class PluginManager { // Held: set when AC hasn't printed the line yet (ChatCallbackHooks holds it until the // plugins' verdict is in; see IncomingChatHold.cs). Null for lines AC already printed. @@ -259,6 +260,10 @@ internal static class PluginManager private static GetCharacterTitlesCallbackDelegate? _getCharacterTitlesCallback; // v75 private static GetServerInfoCallbackDelegate? _getServerInfoCallback; // v75 private static CloseContainerCallbackDelegate? _closeContainerCallback; // v76 + private static SetServerMessageInterestCallbackDelegate? _setServerMessageInterestCallback; // v78 + private static GetTrainingInfoCallbackDelegate? _getTrainingInfoCallback; // v79 + private static RaiseCallbackDelegate? _raiseCallback; // v79 + private static TrainSkillCallbackDelegate? _trainSkillCallback; // v79 private static GetVendorInfoCallbackDelegate? _getVendorInfoCallback; private static GetVendorItemsCallbackDelegate? _getVendorItemsCallback; private static VendorBuyCallbackDelegate? _vendorBuyCallback; @@ -522,6 +527,10 @@ internal static class PluginManager public static void ProcessPendingActions(IntPtr imguiContext, IntPtr d3dDevice, IntPtr gameHwnd) { + // v77: Client::Cleanup started (UiFlowHooks): tell the plugins once, then no more events. + if (ProcessClientCleanup()) + return; + UiLifecycleHooks.Poll(); LoginLifecycleHooks.Poll(); SessionStateRegistry.Poll(); @@ -540,6 +549,11 @@ internal static class PluginManager // • View BEFORE Stop — a container open-then-close in one frame must // end "closed"; draining Stop-then-View left the plugin believing the // container was still open. + // v78 server messages first: the wire comes before the client's handling of it, + // which is what the queued events below report. Cheap when nobody asked for any. + try { Net.ServerMessageStream.Pump(_initialized && ServerMessageSubscriberCount() > 0); } + catch (Exception ex) { RynthLog.Compat($"PluginManager: server message pump failed - {ex.GetType().Name}: {ex.Message}"); } + DispatchQueuedBusyCountIncremented(); DispatchQueuedBusyCountDecremented(); DispatchQueuedCombatModeChange(); @@ -559,6 +573,7 @@ internal static class PluginManager DispatchQueuedEnchantmentAdded(); DispatchQueuedEnchantmentRemoved(); DispatchQueuedChatWindowText(); + DispatchQueuedUiEvents(); // v77 screen / tooltip / drag / drop (PluginManager.UiHooks.cs) if (_rescanRequested) { @@ -1005,6 +1020,10 @@ internal static class PluginManager public static void TickAll() { TickCount++; + Volatile.Write(ref _tickThread, Environment.CurrentManagedThreadId); + // v77: after Client::Cleanup no plugin ticks (AC is tearing its UI down); Shutdown still comes. + if (UiFlowHooks.ClientCleanupStarted) + return; // Fire the delayed login self-identify once AC's vitals UI has settled // (armed in DispatchLoginCompleteToLoadedPlugins; deferred past the @@ -1323,6 +1342,35 @@ internal static class PluginManager return IntPtr.Zero; } + /// + /// Reload deferral (2026-10-05, ReloadDeferral): asks every running plugin's optional + /// const char* RynthPluginReloadBlocker(void) export whether a hot reload now would + /// hurt. Null or "" = safe; a plugin without the export never objects. Fixed signature, so no + /// mismatch can reach the stack; the plugin owns the buffer and it is copied at once. Called + /// on the loader's reload thread before the engine tears down, while every plugin is loaded. + /// + internal static unsafe IReadOnlyList<(string Plugin, string Reason)> QueryReloadBlockers() + { + var result = new List<(string, string)>(); + LoadedPlugin[] plugins; + try { plugins = _plugins.ToArray(); } + catch { return result; } // the list changed under us (a plugin loading): don't hold the reload on it + foreach (var p in plugins) + { + try + { + if (p.ModuleHandle == IntPtr.Zero || !p.Initialized || p.Failed) continue; + IntPtr fn = GetProcAddress(p.ModuleHandle, "RynthPluginReloadBlocker"); + if (fn == IntPtr.Zero) continue; + IntPtr text = ((delegate* unmanaged[Cdecl])fn)(); + string? reason = text != IntPtr.Zero ? Marshal.PtrToStringAnsi(text) : null; + if (!string.IsNullOrWhiteSpace(reason)) result.Add((p.DisplayName, reason.Trim())); + } + catch { /* a plugin that can't answer doesn't hold the reload */ } + } + return result; + } + private static void LogFromPlugin(IntPtr messageUtf8) { string? msg = Marshal.PtrToStringAnsi(messageUtf8); @@ -2398,6 +2446,7 @@ internal static class PluginManager var loadedCanonicalPaths = new HashSet(StringComparer.OrdinalIgnoreCase); var extraPaths = EngineSettings.PluginPaths; + var candidates = new List(extraPaths.Count); for (int i = 0; i < extraPaths.Count; i++) { string dllPath = extraPaths[i]; @@ -2419,14 +2468,38 @@ internal static class PluginManager RynthLog.Plugin($"PluginManager: Skipping extra plugin (same resolved path already loaded): {dllPath}"); continue; } + candidates.Add(dllPath); + loadedBasenames.Add(baseName); + TryAddCanonicalPath(loadedCanonicalPaths, dllPath); + } + + // Manifests (embedded in the DLLs, read without loading them): refuse a plugin that needs + // a newer engine API or a missing plugin, and put required plugins first. Without + // manifests the list loads exactly as before. + PluginManifestGate.LoadPlan plan = PluginManifestGate.Plan(candidates, PluginContractVersion.Current, RawFileVersion); + foreach (string line in plan.Log) + RynthLog.Plugin($"PluginManager: {line}"); + foreach (PluginRefusal refusal in plan.Refused) + RefusePlugin(Path.GetFileName(refusal.Plugin.Key), refusal.Reason); + + foreach ((string dllPath, RynthPluginManifest? manifest) in plan.Load) + { + // A required plugin that failed to load (PluginLoader said no) takes its dependents with it. + string? missing = PluginManifestGate.CheckRequiredStarted(manifest, name => FindPlugin(name) != null ? true : null); + if (missing != null) + { + RefusePlugin(Path.GetFileName(dllPath), missing); + continue; + } RynthLog.Plugin($"PluginManager: Loading extra plugin: {dllPath}"); var plugin = PluginLoader.LoadSingle(dllPath, _shadowRootDir, _loadGeneration); if (plugin != null) { + plugin.Manifest = manifest; + if (manifest != null && !string.Equals(manifest.Name, plugin.DisplayName, StringComparison.OrdinalIgnoreCase)) + RynthLog.Plugin($"PluginManager: {plugin.FileName}: manifest name '{manifest.Name}' differs from RynthPluginName '{plugin.DisplayName}'; dependencies use the manifest's."); _plugins.Add(plugin); - loadedBasenames.Add(plugin.FileName); - TryAddCanonicalPath(loadedCanonicalPaths, plugin.SourceFilePath); } } @@ -2455,6 +2528,63 @@ internal static class PluginManager } } + // ── Plugin manifests ───────────────────────────────────────────────── + + /// Refusals not yet said in chat; said once each, at login (see AnnouncePluginRefusals). + private static readonly List _pendingRefusalNotices = new(); + private static readonly HashSet _announcedRefusals = new(StringComparer.Ordinal); + + private static void RefusePlugin(string fileName, string reason) + { + RynthLog.Plugin($"PluginManager: NOT starting {fileName}: {reason} (this RynthCore is plugin API {PluginContractVersion.Current})."); + lock (_pendingRefusalNotices) + { + if (!_announcedRefusals.Contains(reason) && !_pendingRefusalNotices.Contains(reason)) + _pendingRefusalNotices.Add(reason); + } + if (_loginCompleteObserved) + AnnouncePluginRefusals(); + } + + /// Says each refusal once in chat ("[RynthCore] RynthOracle needs a newer RynthCore (API 77) - not started."). Pump thread. + private static void AnnouncePluginRefusals() + { + List lines; + lock (_pendingRefusalNotices) + { + if (_pendingRefusalNotices.Count == 0) return; + lines = new List(_pendingRefusalNotices); + _pendingRefusalNotices.Clear(); + foreach (string l in lines) _announcedRefusals.Add(l); + } + foreach (string line in lines) + AcMainThreadQueue.EnqueueWriteToChat($"[RynthCore] {line} - not started.", 1); + } + + /// The loaded plugin going by : manifest name, else its file's name, else RynthPluginName. + private static LoadedPlugin? FindPlugin(string name) + { + for (int i = 0; i < _plugins.Count; i++) + { + LoadedPlugin p = _plugins[i]; + if (p.Manifest != null && string.Equals(p.Manifest.Name, name, StringComparison.OrdinalIgnoreCase)) return p; + } + for (int i = 0; i < _plugins.Count; i++) + { + LoadedPlugin p = _plugins[i]; + if (string.Equals(RynthPluginManifest.NameFromFile(p.SourceFilePath), name, StringComparison.OrdinalIgnoreCase) + || string.Equals(p.DisplayName, name, StringComparison.OrdinalIgnoreCase)) + return p; + } + return null; + } + + private static string RawFileVersion(string path) + { + try { return System.Diagnostics.FileVersionInfo.GetVersionInfo(path).ProductVersion ?? ""; } + catch { return ""; } + } + private static void InitializeLoadedPlugins() { if (_plugins.Count == 0) @@ -2469,6 +2599,20 @@ internal static class PluginManager for (int i = 0; i < _plugins.Count; i++) { var plugin = _plugins[i]; + + // Manifest: a plugin whose required plugin didn't start isn't started either (they + // come first: LoadPluginsFromDisk ordered them). No manifest, no check. + string? blocked = PluginManifestGate.CheckRequiredStarted(plugin.Manifest, name => + FindPlugin(name) is { } dep ? dep.Initialized && !dep.Failed : null); + if (blocked != null) + { + plugin.Failed = true; + plugin.NotStartedReason = blocked; + RefusePlugin(plugin.FileName, blocked); + continue; + } + plugin.NotStartedReason = ""; + LoadedPlugin? outer = EnterDispatch(plugin); try { @@ -2583,6 +2727,7 @@ internal static class PluginManager return; _loginDispatchPending = false; + AnnouncePluginRefusals(); // plugins the manifests kept out, once each, now that chat is up for (int i = 0; i < _plugins.Count; i++) { @@ -2765,6 +2910,12 @@ internal static class PluginManager unsafe { _getCharacterTitlesCallback ??= GetCharacterTitlesAction; } unsafe { _getServerInfoCallback ??= GetServerInfoAction; } _closeContainerCallback ??= CloseContainerAction; + unsafe { _getScreenModeCallback ??= GetScreenModeAction; } // v77 (PluginManager.UiHooks.cs) + _getUiHookFlagsCallback ??= GetUiHookFlagsAction; + unsafe { _setServerMessageInterestCallback ??= SetServerMessageInterestAction; } + unsafe { _getTrainingInfoCallback ??= GetTrainingInfoAction; } // v79 + unsafe { _raiseCallback ??= RaiseAction; } + _trainSkillCallback ??= TrainSkillAction; _getVendorInfoCallback ??= GetVendorInfoAction; _getVendorItemsCallback ??= GetVendorItemsAction; _vendorBuyCallback ??= VendorBuyAction; @@ -2903,6 +3054,12 @@ internal static class PluginManager _api.GetCharacterTitlesFn = Marshal.GetFunctionPointerForDelegate(_getCharacterTitlesCallback); _api.GetServerInfoFn = Marshal.GetFunctionPointerForDelegate(_getServerInfoCallback); _api.CloseContainerFn = Marshal.GetFunctionPointerForDelegate(_closeContainerCallback); + _api.GetScreenModeFn = Marshal.GetFunctionPointerForDelegate(_getScreenModeCallback); + _api.GetUiHookFlagsFn = Marshal.GetFunctionPointerForDelegate(_getUiHookFlagsCallback); + _api.SetServerMessageInterestFn = Marshal.GetFunctionPointerForDelegate(_setServerMessageInterestCallback); + _api.GetTrainingInfoFn = Marshal.GetFunctionPointerForDelegate(_getTrainingInfoCallback); + _api.RaiseFn = Marshal.GetFunctionPointerForDelegate(_raiseCallback); + _api.TrainSkillFn = Marshal.GetFunctionPointerForDelegate(_trainSkillCallback); _api.GetVendorInfoFn = Marshal.GetFunctionPointerForDelegate(_getVendorInfoCallback); _api.GetVendorItemsFn = Marshal.GetFunctionPointerForDelegate(_getVendorItemsCallback); _api.VendorBuyFn = Marshal.GetFunctionPointerForDelegate(_vendorBuyCallback); @@ -3978,6 +4135,133 @@ internal static class PluginManager /// v72: see PluginContract.TradeCloseFn. private static int TradeCloseAction() => ToAbiBool(PlayerTrade.Close()); + // ── v79: spending experience (Compatibility/TrainingApi.cs) ───────── + + /// v79: see PluginContract.GetTrainingInfoFn. + private static unsafe int GetTrainingInfoAction(TrainingInfoNative* info, TrainingEntryNative* entries, int maxEntries) + { + try + { + return TrainingApi.GetInfo(info, entries, maxEntries); + } + catch + { + return 0; + } + } + + /// v79: see PluginContract.RaiseFn. + private static unsafe int RaiseAction(uint kind, uint stype, uint ranks, long expectedXp, long* xpSent) + { + try + { + RaiseStatus r = TrainingApi.Raise(kind, stype, ranks, expectedXp, out long sent); + if (xpSent != null) *xpSent = sent; + return (int)r; + } + catch (Exception ex) + { + RynthLog.Compat($"Raise failed - {ex.GetType().Name}: {ex.Message}"); + return (int)RaiseStatus.SendFailed; + } + } + + /// v79: see PluginContract.TrainSkillFn. + private static int TrainSkillAction(uint stype, int expectedCredits) + { + try + { + return (int)TrainingApi.TrainSkill(stype, expectedCredits); + } + catch (Exception ex) + { + RynthLog.Compat($"TrainSkill failed - {ex.GetType().Name}: {ex.Message}"); + return (int)RaiseStatus.SendFailed; + } + } + + /// v78: see PluginContract.SetServerMessageInterestFn. + private static unsafe int SetServerMessageInterestAction(uint* opcodes, int opcodeCount, uint* gameEvents, int eventCount) + { + try + { + LoadedPlugin? owner = CurrentDispatch; + if (owner == null) + return -1; + if (opcodeCount == 0 && eventCount == 0) + { + owner.ServerMessageInterest?.Clear(); + RynthLog.Plugin($"PluginManager: {owner.DisplayName} stopped server messages."); + return 1; + } + if (owner.OnServerMessagePtr == IntPtr.Zero) + owner.OnServerMessagePtr = GetProcAddress(owner.ModuleHandle, "RynthPluginOnServerMessage"); + if (owner.OnServerMessagePtr == IntPtr.Zero) + return 0; + var interest = owner.ServerMessageInterest ??= new Net.ServerMessageInterest(); + if (!interest.Set(opcodes, opcodeCount, gameEvents, eventCount)) + return -3; + RynthLog.Plugin($"PluginManager: {owner.DisplayName} wants server messages: " + + (interest.All ? "all" : $"{interest.OpcodeCount} opcode(s), {interest.EventCount} game event(s){(interest.AllGameEvents ? " + all game events" : "")}")); + return EngineSettings.ServerMessageStream ? 1 : 2; + } + catch (Exception ex) + { + RynthLog.Plugin($"PluginManager: SetServerMessageInterest failed - {ex.GetType().Name}: {ex.Message}"); + return -3; + } + } + + /// v78: initialized, healthy plugins with a non-empty server-message interest. + internal static int ServerMessageSubscriberCount() + { + int n = 0; + for (int i = 0; i < _plugins.Count; i++) + { + var p = _plugins[i]; + if (p.Initialized && !p.Failed && p.OnServerMessagePtr != IntPtr.Zero && + p.ServerMessageInterest is { IsEmpty: false }) + n++; + } + return n; + } + + /// + /// v78: one reassembled server message to the plugins that asked for it (called from + /// ServerMessageStream.Pump, on this pump). is the message after + /// its opcode, valid only during the call. Returns how many plugins were called. + /// + internal static unsafe int DispatchServerMessage(uint opcode, uint eventType, byte* body, int length) + { + int called = 0; + for (int i = 0; i < _plugins.Count; i++) + { + var plugin = _plugins[i]; + if (!plugin.Initialized || plugin.Failed || plugin.OnServerMessagePtr == IntPtr.Zero) + continue; + var interest = plugin.ServerMessageInterest; + if (interest == null || !interest.Wants(opcode, eventType)) + continue; + + LoadedPlugin? outer = EnterDispatch(plugin); + try + { + ((delegate* unmanaged[Cdecl])plugin.OnServerMessagePtr)(opcode, body, length); + called++; + } + catch (Exception ex) + { + plugin.Failed = true; + RynthLog.Error($"PluginManager: {plugin.DisplayName} OnServerMessage threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)} - disabled."); + } + finally + { + LeaveDispatch(outer); + } + } + return called; + } + /// v76: close an external container (see PluginContract.CloseContainerFn). private static int CloseContainerAction(uint containerId) { diff --git a/src/RynthCore.Engine/Plugins/PluginManifestGate.cs b/src/RynthCore.Engine/Plugins/PluginManifestGate.cs new file mode 100644 index 0000000..fa23acb --- /dev/null +++ b/src/RynthCore.Engine/Plugins/PluginManifestGate.cs @@ -0,0 +1,119 @@ +// ============================================================================ +// RynthCore.Engine - Plugins/PluginManifestGate.cs +// The engine's use of plugin manifests (RynthCore.PluginSdk.Manifest, compiled in): +// - before any plugin DLL is loaded, read each one's embedded manifest from the +// file (no LoadLibrary: a refused NativeAOT plugin would otherwise keep a whole +// runtime in acclient's 4 GB for good) and decide which may load, in what order; +// - before a plugin's Init, check the plugins it requires started. +// A plugin without a manifest is never refused and keeps its place in the list, +// so a plugin list with no manifests loads exactly as before. +// +// BCL + the manifest files only, so tools\PluginManifestTests compiles it too. +// PluginManager owns the logging and the chat notice. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.IO; +using RynthCore.PluginSdk.Manifest; + +namespace RynthCore.Engine.Plugins; + +internal static class PluginManifestGate +{ + internal sealed class LoadPlan + { + /// Paths to load, in order, with their manifests (null for a plugin without one). + public List<(string Path, RynthPluginManifest? Manifest)> Load { get; } = new(); + /// Plugins not loaded, with the reason (one sentence, fit for chat). + public List Refused { get; } = new(); + /// Log lines: manifests found, broken manifests, notes. + public List Log { get; } = new(); + } + + /// + /// Reads the manifests of and resolves them against + /// . gives a DLL's version resource + /// (for dependency versions of plugins whose manifest has none); null skips it. + /// + public static LoadPlan Plan(IReadOnlyList paths, uint engineApi, Func? fileVersion = null) + { + var plan = new LoadPlan(); + var candidates = new List(paths.Count); + int withManifest = 0; + foreach (string path in paths) + { + RynthPluginManifest? manifest = null; + try + { + manifest = PluginManifestReader.Read(path); + } + catch (InvalidDataException ex) + { + // A broken manifest is a build problem, not the player's: load it the old way. + plan.Log.Add($"{Path.GetFileName(path)}: manifest unreadable ({ex.Message}) - loading it as a plugin without one."); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + plan.Log.Add($"{Path.GetFileName(path)}: could not read its manifest ({ex.Message}) - loading it as a plugin without one."); + } + + string fv = ""; + if (fileVersion != null && string.IsNullOrEmpty(manifest?.Version)) + { + try { fv = fileVersion(path) ?? ""; } catch { fv = ""; } + } + if (manifest != null) + { + withManifest++; + plan.Log.Add($"{Path.GetFileName(path)}: manifest {Describe(manifest)}."); + } + candidates.Add(new PluginCandidate(path, manifest, fv)); + } + + PluginResolution res = PluginManifestResolver.Resolve(candidates, engineApi); + foreach (PluginCandidate c in res.Order) + plan.Load.Add((c.Key, c.Manifest)); + plan.Refused.AddRange(res.Refused); + foreach (string note in res.Notes) + plan.Log.Add(note); + if (withManifest == 0 && paths.Count > 0) + plan.Log.Add("no plugin has a manifest; loading them as listed."); + return plan; + } + + /// + /// Null when every plugin requires has started; otherwise why not. + /// answers by plugin name: true started, false loaded but not + /// started (failed or refused at Init), null not loaded at all. + /// + public static string? CheckRequiredStarted(RynthPluginManifest? manifest, Func started) + { + if (manifest == null) return null; + foreach (RynthPluginDependency d in manifest.Dependencies) + { + if (d.Optional) continue; + bool? s = started(d.Name); + if (s == true) continue; + return s == false + ? $"{manifest.Name} needs {d.Name}, which failed to start" + : $"{manifest.Name} needs {d.Name}, which is not loaded"; + } + return null; + } + + /// "RynthOracle 2026.10.5.1, API 71+, needs RynthAi (optional)". + public static string Describe(RynthPluginManifest m) + { + string api = m.MaxEngineApi != 0 ? $"API {m.MinEngineApi}-{m.MaxEngineApi}" : $"API {m.MinEngineApi}+"; + string s = $"{m.Name}{(m.Version.Length > 0 ? " " + m.Version : "")}, {api}"; + if (m.Dependencies.Count > 0) + { + var parts = new List(m.Dependencies.Count); + foreach (RynthPluginDependency d in m.Dependencies) + parts.Add(d.Name + (d.MinVersion.Length > 0 ? " " + d.MinVersion + "+" : "") + (d.Optional ? " (optional)" : "")); + s += ", needs " + string.Join(", ", parts); + } + return s; + } +} diff --git a/src/RynthCore.Engine/ReloadDeferral.cs b/src/RynthCore.Engine/ReloadDeferral.cs new file mode 100644 index 0000000..7f5f1ec --- /dev/null +++ b/src/RynthCore.Engine/ReloadDeferral.cs @@ -0,0 +1,113 @@ +// ============================================================================ +// RynthCore.Engine - ReloadDeferral.cs +// Holds a hot reload while a plugin says one now would hurt (2026-10-05). +// +// Drakkon died on DreamWeave at 13:43:20 after the loader's file watcher saw a +// new RynthCore.Engine.dll at 13:42:54 and reloaded the engine mid-fight: every +// plugin was down for about 8 s, then RynthAi came back as if it had just logged +// in. The loader (native\Loader, off-limits here) decides to reload and calls +// RynthCoreShutdown on its own reload thread; nothing in the game waits on that +// thread. So the engine's side of the handshake is: before tearing down, ask +// every plugin's optional RynthPluginReloadBlocker export, and while one answers +// with a reason, wait and ask again, up to Cap. The game keeps running on the +// old engine meanwhile; the loader stages the new one after Shutdown returns, so +// the newest file on disk is what loads. +// +// Pure: the plugin query, the clock, the sleep and the log are injected, so the +// loop is tested offline (tools\ReloadDeferralTests). EntryPoint wires it. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Threading; + +namespace RynthCore.Engine; + +internal sealed class ReloadDeferral +{ + /// Longest a reload waits for the plugins (then it goes ahead, and says so). + public static readonly TimeSpan DefaultCap = TimeSpan.FromMinutes(2); + /// How often the plugins are asked again while one blocks. + public static readonly TimeSpan DefaultPoll = TimeSpan.FromMilliseconds(500); + /// While waiting, the "still waiting" line repeats this often (the first line is at once). + public static readonly TimeSpan DefaultLogEvery = TimeSpan.FromSeconds(15); + + public enum Outcome + { + /// No plugin objected: reload at once. + Clear, + /// A plugin objected, then cleared within the cap. + ClearedAfterWait, + /// Still objecting at the cap: reload anyway. + TimedOut, + } + + /// The plugins that object now, each with its reason (empty = safe). + public required Func> Query { get; init; } + public required Action Log { get; init; } + /// Told once, when the wait starts (the engine puts it in chat). + public Action? Notify { get; init; } + public Func Clock { get; init; } = () => DateTime.UtcNow; + public Action Sleep { get; init; } = t => Thread.Sleep(t); + public TimeSpan Cap { get; init; } = DefaultCap; + public TimeSpan Poll { get; init; } = DefaultPoll; + public TimeSpan LogEvery { get; init; } = DefaultLogEvery; + + /// Asks the plugins until none objects or has passed. + public Outcome Run(out TimeSpan waited) + { + DateTime start = Clock(); + waited = TimeSpan.Zero; + var blockers = SafeQuery(); + if (blockers.Count == 0) return Outcome.Clear; + + string first = Describe(blockers); + Log($"engine reload waiting: {first} (asking again every {Poll.TotalSeconds:0.#} s, at most {Cap.TotalSeconds:0} s)."); + try { Notify?.Invoke(first); } catch { } + DateTime lastLog = start; + + while (true) + { + DateTime now = Clock(); + waited = now - start; + if (waited >= Cap) + { + Log($"engine reload: waited {waited.TotalSeconds:0} s and {Describe(blockers)} still; reloading anyway."); + return Outcome.TimedOut; + } + Sleep(Poll); + blockers = SafeQuery(); + now = Clock(); + waited = now - start; + if (blockers.Count == 0) + { + Log($"engine reload: the plugins are clear after {waited.TotalSeconds:0.0} s; reloading now."); + return Outcome.ClearedAfterWait; + } + if (now - lastLog >= LogEvery) + { + lastLog = now; + Log($"engine reload waiting: {Describe(blockers)} ({waited.TotalSeconds:0} s of at most {Cap.TotalSeconds:0} s)."); + } + } + } + + /// "RynthAi in combat (a monster engaged)", several joined with "; ". + public static string Describe(IReadOnlyList<(string Plugin, string Reason)> blockers) + { + var parts = new List(blockers.Count); + foreach (var (plugin, reason) in blockers) parts.Add($"{plugin} {reason}"); + return string.Join("; ", parts); + } + + // A plugin query that throws must never hold a reload: count it as "nothing objects". + private IReadOnlyList<(string Plugin, string Reason)> SafeQuery() + { + try { return Query() ?? Array.Empty<(string, string)>(); } + catch (Exception ex) + { + try { Log($"engine reload: asking the plugins failed ({ex.GetType().Name}: {ex.Message}); not waiting."); } catch { } + return Array.Empty<(string, string)>(); + } + } +} diff --git a/src/RynthCore.Engine/RynthCore.Engine.csproj b/src/RynthCore.Engine/RynthCore.Engine.csproj index 6d6a3b2..bf8c366 100644 --- a/src/RynthCore.Engine/RynthCore.Engine.csproj +++ b/src/RynthCore.Engine/RynthCore.Engine.csproj @@ -78,10 +78,14 @@ - + + + + + diff --git a/src/RynthCore.Engine/RynthLog.cs b/src/RynthCore.Engine/RynthLog.cs index b4b9232..a6fd341 100644 --- a/src/RynthCore.Engine/RynthLog.cs +++ b/src/RynthCore.Engine/RynthLog.cs @@ -39,7 +39,7 @@ internal static class RynthLog /// Uncategorised line (General category, Info by default). internal static void Info(string msg) => WriteCategory(LogCategory.General, msg); - /// Alias kept for SK-local call sites; same as . + /// Same as . internal static void Warning(string msg) => Warn(msg); // Most recent WRN/ERR text + when, surfaced via the GetEngineStatusJson host bridge so a stuck box @@ -55,6 +55,15 @@ internal static class RynthLog EntryPoint.LogTagged("engine", msg, "WRN"); } + /// + /// Always-on heartbeat line, written at every LoggingLevel (Off included). The launcher's + /// wedge watchdog reads RynthCore.<pid>.log going quiet for 120 s as a dead engine and + /// kills the client, so this line must never be filtered: on 2026-10-06 LoggingLevel=Info + /// with General=Trace dropped it and healthy in-world clients were killed and relaunched + /// every few minutes. + /// + internal static void Heartbeat(string msg) => EntryPoint.LogTagged("engine", msg, "INF"); + /// Always-on ERROR line — a fault/crash/disable, written even at level Off. Triage with grep "[ERR]". internal static void Error(string msg) { @@ -62,11 +71,95 @@ internal static class RynthLog EntryPoint.LogTagged("engine", msg, "ERR"); } + // ── Diagnostic traces (2026-10-05, Drakkon's held casts on DreamWeave) ── + // A movement packet sent while a cast winds up can cancel the cast or leave the server + // holding it open, and the old movement lines were 1 in 8 with no caller. Both switches + // are on by default; each costs one bool test when off. + + /// Every plugin movement call (SetAutoRun, SetMotion, DoMovement/StopMovement, + /// StopCompletely, TurnToHeading, jumps), one "Move:" line each with the calling plugin. + /// Identical calls in a row from one caller (turns: any angle) are counted, not written, + /// for up to MoveRepeatWindowMs; the count rides on the next line written. + internal static bool MoveTraceEnabled = true; + + /// Every server UseDone (0x01C7) with its sequence number and error code + /// (before: the first 25 of a session). + internal static bool ActionDoneTraceEnabled = true; + + private const long MoveRepeatWindowMs = 1000; + private static readonly object _moveGate = new(); + private static string _moveLastKey = ""; + private static long _moveLastWrittenMs = long.MinValue; + private static int _moveRepeats; + private static long _moveRepeatFirstMs; + private static string _moveRepeatLastArg = ""; + + /// + /// One plugin movement call (see ). + /// must be a string literal (it also goes into AcActionTrace, which keeps the last 256 + /// actions for crash dumps); / are its trace args. + /// + internal static void Move(string name, string arg, bool ok, bool collapseByKind = false, uint a = 0, uint b = 0) + { + Compatibility.AcActionTrace.Record(name, a, b); + if (!MoveTraceEnabled) return; + string? line = null; + try + { + string caller = MoveCaller(); + lock (_moveGate) + { + long now = Environment.TickCount64; + string key = collapseByKind ? $"{caller}|{name}" : $"{caller}|{name}({arg})|{ok}"; + if (key == _moveLastKey && now - _moveLastWrittenMs < MoveRepeatWindowMs) + { + if (_moveRepeats == 0) _moveRepeatFirstMs = now; + _moveRepeats++; + _moveRepeatLastArg = arg; + return; + } + string more = ""; + if (_moveRepeats > 0) + { + string[] parts = _moveLastKey.Split('|'); + string what = parts.Length > 1 ? parts[1] : "?"; + string last = parts.Length > 2 ? "" : $", last {_moveRepeatLastArg}"; + more = $" (+{_moveRepeats} more {what}{last} by {parts[0]} before this, over {now - _moveRepeatFirstMs} ms)"; + } + line = $"Move: {name}({arg}) by {caller} -> {(ok ? "ok" : "FAILED")}{more}"; + _moveLastKey = key; + _moveLastWrittenMs = now; + _moveRepeats = 0; + _moveRepeatLastArg = ""; + } + } + catch { return; } + Write(line); + } + + /// The plugin whose tick or event is calling, else the thread. + private static string MoveCaller() + { + var plugin = Plugins.PluginManager.CurrentDispatch; + if (plugin != null) + return string.IsNullOrEmpty(plugin.DisplayName) ? plugin.FileName : plugin.DisplayName; + return Compatibility.MainThreadGuard.IsOnMainThread() + ? "AC main thread" + : $"thread {Environment.CurrentManagedThreadId}"; + } + /// True when a line in would be written (guard expensive messages). internal static bool IsEnabled(LogCategory category) => LogSettings.IsEnabled(category); // ── Sink ───────────────────────────────────────────────────────────── + /// Uncategorised line (General category); used by the Move/UseDone traces. + private static void Write(string? message) + { + if (message != null) + WriteCategory(LogCategory.General, message); + } + private static void WriteCategory(LogCategory category, string message) => WriteAt(LogSettings.LevelFor(category), message); diff --git a/src/RynthCore.Engine/UI/Data/ArgbOpacity.cs b/src/RynthCore.Engine/UI/Data/ArgbOpacity.cs new file mode 100644 index 0000000..af08e28 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/ArgbOpacity.cs @@ -0,0 +1,28 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/ArgbOpacity.cs +// An AARRGGBB colour's alpha as an opacity percentage, for the Vision face's +// overlay opacity sliders (slopes, water, radar ring). The opacity lives in the +// colour the RynthVision plugin already saves, so the slider needs no new +// setting and no plugin change: moving it rewrites the colour's alpha byte. +// +// Percent is a float so an untouched value round-trips exactly +// (0x60 -> 37.65 % -> 0x60); only a slider move changes the byte. +// ============================================================================ + +using System; + +namespace RynthCore.Engine.UI.Data; + +internal static class ArgbOpacity +{ + /// The colour's alpha as 0..100 %. + public static float Percent(uint argb) => (argb >> 24) * 100f / 255f; + + /// The colour with its alpha set from (clamped to 0..100); RGB kept. + public static uint WithPercent(uint argb, float percent) + { + float p = float.IsNaN(percent) ? 0f : Math.Clamp(percent, 0f, 100f); + uint a = (uint)Math.Clamp((int)MathF.Round(p * 255f / 100f), 0, 255); + return (argb & 0x00FFFFFFu) | (a << 24); + } +} diff --git a/src/RynthCore.Engine/UI/Data/ChatData.cs b/src/RynthCore.Engine/UI/Data/ChatData.cs index da6ac12..fc452d6 100644 --- a/src/RynthCore.Engine/UI/Data/ChatData.cs +++ b/src/RynthCore.Engine/UI/Data/ChatData.cs @@ -1190,7 +1190,7 @@ internal static class ChatModel _ => ChatColorMode.None, }, ColorArgb = ParseColor(f.Color) ?? ChatFilterRule.DefaultColor, - // Absent (older settings, upstream format): Regex. + // Absent (settings saved before match modes existed): Regex. Mode = Enum.TryParse(f.Mode, ignoreCase: true, out ChatMatchMode mode) ? mode : ChatMatchMode.Regex, }; rule.Recompile(); diff --git a/src/RynthCore.Engine/UI/Data/LootEditData.cs b/src/RynthCore.Engine/UI/Data/LootEditData.cs index 7148ea5..3a89213 100644 --- a/src/RynthCore.Engine/UI/Data/LootEditData.cs +++ b/src/RynthCore.Engine/UI/Data/LootEditData.cs @@ -139,6 +139,8 @@ internal sealed class LootEditItemRequestDto public string RuleName { get; set; } = string.Empty; /// True: the profile open in the Loot Editor; false: the one RynthAi loots with. public bool ToOpenProfile { get; set; } + /// Also require the item's T11 attributes (added 2026-10-07; an older RynthAi ignores it). + public bool IncludeT11 { get; set; } public int Seq { get; set; } } @@ -157,6 +159,10 @@ internal sealed class LootEditItemDraftDto public bool TargetInUse { get; set; } public string Format { get; set; } = string.Empty; public int Match { get; set; } + /// The rule includes the item's T11 attributes (added 2026-10-07; false from an older RynthAi). + public bool IncludeT11 { get; set; } + /// The item is T11 gear (added 2026-10-07; false from an older RynthAi). + public bool IsT11 { get; set; } public int Action { get; set; } public int KeepCount { get; set; } public string RuleName { get; set; } = string.Empty; diff --git a/src/RynthCore.Engine/UI/Data/NavData.cs b/src/RynthCore.Engine/UI/Data/NavData.cs index 43f2ad3..b6f1b8d 100644 --- a/src/RynthCore.Engine/UI/Data/NavData.cs +++ b/src/RynthCore.Engine/UI/Data/NavData.cs @@ -43,6 +43,13 @@ internal sealed class NavPayload public bool TrackBreadcrumbs { get; set; } /// RynthAi draws the route overlay (rings / lines, waypoint labels, guide line). public bool ShowRouteOverlay { get; set; } + /// Route recording is on (points are added as you walk). Older plugins omit it. + public bool IsRecording { get; set; } + /// Breadcrumb trail size, for "Trail to route" / "Backtrack". + public int TrailPoints { get; set; } + public double TrailYards { get; set; } + /// The last route edit's result, for a few seconds after it (empty otherwise). + public string EditStatus { get; set; } = string.Empty; /// A copy a face may change (its own point list); the points themselves are shared. public NavPayload Clone() @@ -63,7 +70,12 @@ internal sealed class NavCmd public int InsertAt { get; set; } = -1; public string NavName { get; set; } = string.Empty; public string Text { get; set; } = string.Empty; // addChat - public bool On { get; set; } // setBreadcrumbs / setRouteOverlay + public bool On { get; set; } // setBreadcrumbs / setRouteOverlay / setRecording + public List? Indices { get; set; } // movePoints / duplicatePoints / deletePoints + public int Delta { get; set; } // movePoints: -1 up, +1 down + public double Seconds { get; set; } // addPause + public double Yards { get; set; } // simplifyRoute tolerance + public bool Reverse { get; set; } // trailToRoute: backtrack } [JsonSerializable(typeof(NavPayload))] @@ -109,6 +121,19 @@ internal static class NavCommands public static readonly string[] RouteTypes = { "Once", "Circular", "Linear", "Follow" }; public static readonly string[] AddModes = { "End", "Above", "Below" }; + public static readonly double[] PauseSeconds = { 1, 2, 3, 5, 10, 15, 30, 60 }; + public static readonly string[] PauseLabels = Array.ConvertAll(PauseSeconds, s => $"Pause {s:0} s"); + + public static readonly double[] SimplifyYards = { 0.5, 1, 2, 3, 5 }; + public static readonly string[] SimplifyLabels = + Array.ConvertAll(SimplifyYards, y => $"Drop points within {y:0.#} yd of a straight line"); + + public static readonly string[] TrailChoices = + { + "Replace route with the trail (walk it again)", + "Replace route with a backtrack (walk it back)", + }; + /// Route picker index for the plugin's RouteType (1 Circular, 2 Linear, 3 Follow, else Once). public static int RouteIndex(int routeType) => routeType switch { 1 => 1, 2 => 2, 3 => 3, _ => 0 }; diff --git a/src/RynthCore.Engine/UI/Data/SettingsData.cs b/src/RynthCore.Engine/UI/Data/SettingsData.cs index 5743159..f26df4b 100644 --- a/src/RynthCore.Engine/UI/Data/SettingsData.cs +++ b/src/RynthCore.Engine/UI/Data/SettingsData.cs @@ -11,6 +11,7 @@ // ============================================================================ using System; +using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text.Json; using System.Text.Json.Serialization; @@ -163,6 +164,9 @@ internal sealed class RynthAiSettings public bool RebuffWhenIdle { get; set; } public int RebuffSecondsRemaining { get; set; } = 300; public int RebuffTopOffSecondsRemaining { get; set; } = 1200; + // Cast our own buff even when gear already gives it (servers with buff augments). Default + // on; a RynthAi that predates it doesn't send it, and must not read as off. + public bool CastBuffsOverItemBuffs { get; set; } = true; public int BuffMinSkillLevelTier1 { get; set; } = 35; public int BuffMinSkillLevelTier2 { get; set; } = 85; public int BuffMinSkillLevelTier3 { get; set; } = 135; @@ -183,6 +187,10 @@ internal sealed class RynthAiSettings public bool LootJumpEnabled { get; set; } public int LootJumpHeight { get; set; } = 10; public int LootOwnership { get; set; } + // Recover your own death corpse whole (default on), and travel back to it after a death + // (default off). A RynthAi that predates them doesn't send them; on must not read as off. + public bool LootOwnCorpse { get; set; } = true; + public bool TravelToOwnCorpse { get; set; } public bool EnableAutostack { get; set; } = true; public bool ReadUnknownScrolls { get; set; } = true; // VTank's default public bool EnableCombineSalvage { get; set; } = true; @@ -202,6 +210,16 @@ internal sealed class RynthAiSettings public int SalvageSalvageDelayMs { get; set; } = 50; public int SalvageResultDelayFirstMs { get; set; } = 1000; public int SalvageResultDelayFastMs { get; set; } = 250; + // Ground loot and item info + public bool EnableGroundLoot { get; set; } + public bool ItemInfoOnSelect { get; set; } + // Diagnostics (RynthAi's RynthLog: per PC in Logs\Diagnostics\diagnostics.json, not the profile) + public bool DiagDebugToChat { get; set; } + public bool DiagFileLogAll { get; set; } = true; + /// "Name=Level" per trace category, ','-joined; Level 0 Off, 1 Trace, 2 Info. See . + public string DiagCategories { get; set; } = string.Empty; + /// Read-only (RynthAi ignores it on save): the diagnostics folder. + public string DiagFolder { get; set; } = string.Empty; /// A private copy for a face to edit (all members are values or strings). public RynthAiSettings Clone() => (RynthAiSettings)MemberwiseClone(); @@ -272,7 +290,60 @@ internal static unsafe class SettingsCommands // ── Schema ───────────────────────────────────────────────────────────────── -internal enum SettingKind { Bool, Int, Float, Double, Combo, Section, Spacer, Note, CraftingStatus, Button, Text, Status } +internal enum SettingKind { Bool, Int, Float, Double, Combo, Section, Spacer, Note, CraftingStatus, Button, TraceCategories, Text, Status } + +/// +/// Reads and edits ("Name=Level,..."). The category +/// list comes from RynthAi, so a category it adds shows up without an engine change. +/// +internal static class TraceCategoryLevels +{ + public const int Off = 0, Trace = 1, Info = 2; + + /// The categories in RynthAi's order; malformed entries are skipped. + public static List<(string Name, int Level)> Parse(string? levels) + { + var list = new List<(string, int)>(); + if (string.IsNullOrWhiteSpace(levels)) return list; + foreach (string entry in levels.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) + { + int eq = entry.IndexOf('='); + if (eq <= 0 || !int.TryParse(entry[(eq + 1)..], out int level)) continue; + list.Add((entry[..eq], Math.Clamp(level, Off, Info))); + } + return list; + } + + private static string Format(List<(string Name, int Level)> list) + { + var parts = new string[list.Count]; + for (int i = 0; i < list.Count; i++) parts[i] = list[i].Name + "=" + list[i].Level; + return string.Join(",", parts); + } + + /// + /// Turns tracing on or off for one category (empty with a + /// : every category starting with it; both empty: all). On keeps + /// a category already at Info at Info, the same rule as /ra trace. + /// + public static string Set(string? levels, string name, bool on, string prefix = "") + { + List<(string Name, int Level)> list = Parse(levels); + for (int i = 0; i < list.Count; i++) + { + var (n, level) = list[i]; + bool match = name.Length > 0 + ? string.Equals(n, name, StringComparison.OrdinalIgnoreCase) + : n.StartsWith(prefix, StringComparison.OrdinalIgnoreCase); + if (!match) continue; + list[i] = (n, !on ? Off : level == Off ? Trace : level); + } + return Format(list); + } + + /// Checkbox label: the name, plus " +log" at Info (trace lines also go to the normal log). + public static string Label(string name, int level) => level == Info ? name + " +log" : name; +} /// /// One row of a settings tab. Numeric values go through double (bools as @@ -433,6 +504,12 @@ internal static class SettingsSchema TextSize("Status", "Status"), TextSize("Log", "Log"), TextSize("Tracker", "Tracker"), + Spacer(), + Section("Item Info"), + Bool("Describe Items When Selected", s => s.ItemInfoOnSelect, (s, v) => s.ItemInfoOnSelect = v, + "Print a Mag-style description of an item in chat when you select it.\nAlso: /ra iteminfo on|off."), + Button("Item Info Options", "Open...", () => RynthAiCommands.ApplyRemoteCommand("iteminfo", "window"), + "Which fields the description shows and which item types are described on select (/ra iteminfo window)."), }), new("UI", new[] @@ -683,6 +760,8 @@ internal static class SettingsSchema "Recast a self buff when its remaining duration drops below this value.\nDefault 300 (5 minutes). Lower values rebuff more eagerly."), Int("Also Refresh Under (seconds left)", s => s.RebuffTopOffSecondsRemaining, (s, v) => s.RebuffTopOffSecondsRemaining = v, 30, 3600, 60, "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."), + Bool("Cast buffs even when an item gives them", s => s.CastBuffsOverItemBuffs, (s, v) => s.CastBuffsOverItemBuffs = v, + "Cast your own buff even when worn gear already gives that buff.\nFor servers with buff augments, where your own cast is stronger or lasts longer.\nOn by default: on retail it costs a few extra casts."), Spacer(), Section("Buff Difficulty (Min Buffed Skill)"), Tiers( @@ -712,9 +791,15 @@ internal static class SettingsSchema "Don't start on another corpse when no pack has a free slot (says so once in chat)."), Bool("Jump When Looting", s => s.LootJumpEnabled, (s, v) => s.LootJumpEnabled = v, gates: true), Int("Jump Height", s => s.LootJumpHeight, (s, v) => s.LootJumpHeight = v, 1, 100, 5, when: s => s.LootJumpEnabled), + Bool("Loot Items On Ground", s => s.EnableGroundLoot, (s, v) => s.EnableGroundLoot = v, + "Pick up loose items on the ground that match your loot profile, within Corpse Max range.\nCorpses always come first. Status and rescan: /ra groundloot."), Spacer(), Section("Corpse Ownership"), Combo("Loot From", LootOwnershipModes, s => s.LootOwnership, (s, v) => s.LootOwnership = v), + Bool("Recover My Corpse", s => s.LootOwnCorpse, (s, v) => s.LootOwnCorpse = v, + "When your own corpse (\"Corpse of \") is within loot range, open it and take every\nitem on it, whatever the loot profile and Loot From say. Needs Enable Looting.\n/ra owncorpse says where your last corpse is."), + Bool("Travel Back To My Corpse", s => s.TravelToOwnCorpse, (s, v) => s.TravelToOwnCorpse = v, + "After a death, walk back to where you died with RynthNav (outdoor deaths only),\nfighting on the way as usual, recover the corpse, then carry on. Needs the macro\nrunning and RynthNav loaded. /ra owncorpse stop cancels."), Spacer(), Section("Inventory Management"), Bool("Enable Autostack", s => s.EnableAutostack, (s, v) => s.EnableAutostack = v), @@ -768,5 +853,24 @@ internal static class SettingsSchema Spacer(), Note("Never sold: equipped, attuned, bonded, retained, tinkered, imbued, inscribed, rare, zero value, packs, or anything a Keep rule could match."), }), + + new("Diagnostics", new[] + { + Section("Logging & Debugging"), + Bool("Debug to chat", s => s.DiagDebugToChat, (s, v) => s.DiagDebugToChat = v, + "Echo trace lines and errors from the categories ticked below into the chat window.\nAlso: /ra debug on|off."), + Bool("Daily RynthAi log file", s => s.DiagFileLogAll, (s, v) => s.DiagFileLogAll = v, + "Mirror every RynthAi log line to rynthai_.txt in the log folder (kept 7 days).\nAlso: /ra logs file on|off."), + Button("Log Folder", "Open", () => RynthAiCommands.ApplyRemoteCommand("logs", "open"), + "Open RynthAi's Logs\\Diagnostics folder in Explorer (/ra logs open)."), + Button("Old Log Files", "Prune", () => RynthAiCommands.ApplyRemoteCommand("logs", "prune"), + "Delete diagnostics files past the retention limit now (/ra logs prune)."), + Spacer(), + Section("Trace Per Category"), + new SettingRow(SettingKind.TraceCategories, "Categories", + "Ticked categories write their trace lines to Trace\\_.txt (/ra trace on|off)."), + Note("+log = the category is at Info: its trace lines also go to the normal log. The launcher's Logging page sets Off, Trace or Info."), + Note("Exceptions always go to exceptions_.txt with full stack traces (throttled). Settings here are for this PC, not the profile."), + }), }; } diff --git a/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs b/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs index e3a7fe4..df6f44e 100644 --- a/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs @@ -335,6 +335,8 @@ internal static class SettingsPanel return Spacer(); case SettingKind.Button: return ButtonRow(row.Label, row.ButtonText ?? row.Label, () => row.Click?.Invoke(), row.Tooltip); + case SettingKind.TraceCategories: + return TraceCategoriesRow(state, row); case SettingKind.Text: return TextRow(row.Label, row.GetText?.Invoke(d) ?? string.Empty, row.Hint, v => { @@ -801,6 +803,58 @@ internal static class SettingsPanel return row; } + /// + /// [All on] [All off] [ILT Hub on] over a 3-column grid of toggles, one per RynthAi trace + /// category. Each change edits DiagCategories, saves, and rebuilds the tab so the grid redraws. + /// + private static Control TraceCategoriesRow(PanelState state, SettingRow row) + { + var cats = TraceCategoryLevels.Parse(state.Data.DiagCategories); + if (cats.Count == 0) + return new TextBlock { Text = "Waiting for RynthAi...", Foreground = ColMute, FontSize = 10, Margin = new Thickness(0, 2, 0, 0) }; + + void Save(string levels) + { + state.Data.DiagCategories = levels; + Push(state); + state.Rebuild?.Invoke(); + } + + Button Bulk(string text, Func next) + { + var b = new Button + { + Content = text, FontSize = 10, Height = 20, Padding = new Thickness(6, 1), + Background = ColBtnFill, Foreground = ColTextDim, BorderBrush = ColBtnBord, BorderThickness = new Thickness(1), + }; + b.Click += (_, _) => Save(next()); + return b; + } + + var box = new StackPanel { Margin = new Thickness(0, 2, 0, 2) }; + var buttons = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, Margin = new Thickness(0, 0, 0, 4) }; + buttons.Children.Add(Bulk("All on", () => TraceCategoryLevels.Set(state.Data.DiagCategories, "", true))); + buttons.Children.Add(Bulk("All off", () => TraceCategoryLevels.Set(state.Data.DiagCategories, "", false))); + buttons.Children.Add(Bulk("ILT Hub on", () => TraceCategoryLevels.Set(state.Data.DiagCategories, "", true, "Ilt"))); + if (row.Tooltip != null) + { + ToolTip.SetTip(buttons, row.Tooltip); + ToolTip.SetShowDelay(buttons, 400); + } + box.Children.Add(buttons); + + var grid = new Avalonia.Controls.Primitives.UniformGrid { Columns = 3 }; + foreach (var (name, level) in cats) + { + string catName = name; + bool on = level != TraceCategoryLevels.Off; + grid.Children.Add(BoolRow(TraceCategoryLevels.Label(name, level), on, + v => Save(TraceCategoryLevels.Set(state.Data.DiagCategories, catName, v)))); + } + box.Children.Add(grid); + return box; + } + // SimpleTheme wraps TextBox content in a ScrollViewer, and its vertical // scrollbar's up RepeatButton is a filled triangle Path. On these short // (Height=20) single-line numeric fields that scrollbar shows and the diff --git a/src/RynthCore.Engine/UI/ScriptWindows/AcIconDecoder.cs b/src/RynthCore.Engine/UI/ScriptWindows/AcIconDecoder.cs index 0366a5b..8096a6b 100644 --- a/src/RynthCore.Engine/UI/ScriptWindows/AcIconDecoder.cs +++ b/src/RynthCore.Engine/UI/ScriptWindows/AcIconDecoder.cs @@ -5,13 +5,20 @@ // into one picture. Pure code: no AC memory, no D3D, no engine state, so the // RynthSuite offline tests compile it in and decode real icons. // -// The texture formats and their byte layouts are the ones RynthCore.StatusAgent -// (Dat/IconDecoder.cs, the phone remote's icons) decodes, ported from -// ACEmulator's DatLoader; DXT1/3/5 use the StatusAgent's DxtUtil.cs (MonoGame, -// Ms-PL), linked into the engine project. The dat reader is the on-demand -// B-tree walk of ImGui/MonsterHud/PortalSpellTable.cs over one open stream: -// header at 0x140, a B-tree searched by file id, block chains whose first -// dword is the next block's offset. +// Written for RynthCore (MIT); the dat reader and the texture decoding were +// rewritten on 2026-10-05 from the public dat container layout and the +// Texture / Palette layouts as Chorizite's DatReaderWriter (MIT) describes +// them (its notice is in RynthCore.StatusAgent/Dat/DatDatabase.cs): +// - header at 0x140: magic, block size, file size, ..., root node offset +// (uint32 at 0x160); a block starts with the next block's offset (0 = +// last); the directory is a B-tree of nodes (62 child offsets, an entry +// count, entries of 24 bytes: flags, id, offset, size, date, iteration); +// - Texture: id u32, data category u32, width i32, height i32, format u32, +// length i32, data[length], and for P8 / INDEX16 a palette id u32; +// Palette: id u32, count i32, count x u32 A8R8G8B8. +// DXT1/3/5 use the StatusAgent's DxtUtil.cs, linked into the engine project. +// The pixels are the same as the StatusAgent's Dat/IconDecoder.cs (the phone +// remote's icons) produces. // // Threads: whatever thread owns the AcDatFile (the icon worker). Every read is // bounds-checked; a bad file returns null, never throws out of Decode/Compose. @@ -21,26 +28,30 @@ using System; using System.Buffers.Binary; using System.Collections.Generic; using System.IO; -using ACE.DatLoader; +using RynthCore.Imaging; namespace RynthCore.Engine.UI.ScriptWindows; /// A read-only portal.dat opened for a batch of reads. Not thread-safe. internal sealed class AcDatFile : IDisposable { - private const int HeaderOffset = 0x140; - private const int Branches = 62, MaxEntries = 61, EntrySize = 24; - private const int NodeSize = 4 * Branches + 4 + EntrySize * MaxEntries; // 1716 - private const int MaxDepth = 16; + private const long HeaderOffset = 0x140; + private const int ChildSlots = 62, MaxEntries = 61, EntryBytes = 24; + private const int EntriesOffset = ChildSlots * 4 + 4; // 252 + private const int NodeBytes = EntriesOffset + MaxEntries * EntryBytes; // 1716 + private const int DepthLimit = 16; private readonly FileStream _fs; - private readonly uint _blockSize; + private readonly long _length; + private readonly int _payload; // block size - 4 private readonly uint _root; + private readonly byte[] _node = new byte[NodeBytes]; private AcDatFile(FileStream fs, uint blockSize, uint root) { _fs = fs; - _blockSize = blockSize; + _length = fs.Length; + _payload = (int)blockSize - 4; _root = root; } @@ -52,24 +63,24 @@ internal sealed class AcDatFile : IDisposable { fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 4096, FileOptions.RandomAccess); - Span hdr = stackalloc byte[36]; - fs.Seek(HeaderOffset, SeekOrigin.Begin); - if (!ReadFully(fs, hdr)) { why = "short header"; fs.Dispose(); return null; } - uint blockSize = BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(4, 4)); - uint root = BinaryPrimitives.ReadUInt32LittleEndian(hdr.Slice(32, 4)); + Span header = stackalloc byte[36]; + fs.Position = HeaderOffset; + if (!ReadFully(fs, header)) { why = "short header"; fs.Dispose(); return null; } + uint blockSize = BinaryPrimitives.ReadUInt32LittleEndian(header.Slice(4)); + uint root = BinaryPrimitives.ReadUInt32LittleEndian(header.Slice(32)); if (blockSize <= 4 || blockSize > 65536 || root == 0 || root >= fs.Length) { - why = "bad header"; + why = $"not a dat file (block size {blockSize}, root 0x{root:X8})"; fs.Dispose(); return null; } - why = string.Empty; + why = ""; return new AcDatFile(fs, blockSize, root); } catch (Exception ex) { fs?.Dispose(); - why = $"{ex.GetType().Name}: {ex.Message}"; + why = ex.Message; return null; } } @@ -104,26 +115,34 @@ internal sealed class AcDatFile : IDisposable { try { - uint offset = _root; - for (int depth = 0; depth < MaxDepth && offset != 0; depth++) + uint at = _root; + for (int depth = 0; depth < DepthLimit && at != 0; depth++) { - byte[]? node = ReadChain(offset, NodeSize); - if (node == null) return null; - uint count = BinaryPrimitives.ReadUInt32LittleEndian(node.AsSpan(4 * Branches)); - if (count > MaxEntries) return null; - int i = 0; - while (i < count && EntryId(node, i) < fileId) i++; - if (i < count && EntryId(node, i) == fileId) + int got = ReadChain(at, _node); + if (got < EntriesOffset) return null; + int count = BinaryPrimitives.ReadInt32LittleEndian(_node.AsSpan(EntriesOffset - 4)); + if (count < 0 || count > MaxEntries || got < EntriesOffset + count * EntryBytes) return null; + + // Entries are sorted by id: binary search for the first id >= fileId. + int lo = 0, hi = count; + while (lo < hi) { - int e = 4 * Branches + 4 + i * EntrySize; - uint fileOffset = BinaryPrimitives.ReadUInt32LittleEndian(node.AsSpan(e + 8)); - uint fileSize = BinaryPrimitives.ReadUInt32LittleEndian(node.AsSpan(e + 12)); - if (fileSize == 0 || fileSize > (uint)maxSize) return null; - return ReadChain(fileOffset, (int)fileSize); + int mid = (lo + hi) >> 1; + if (IdAt(mid) < fileId) lo = mid + 1; else hi = mid; } - bool leaf = BinaryPrimitives.ReadUInt32LittleEndian(node) == 0; - if (leaf || i >= Branches) return null; - offset = BinaryPrimitives.ReadUInt32LittleEndian(node.AsSpan(i * 4)); + if (lo < count && IdAt(lo) == fileId) + { + var e = _node.AsSpan(EntriesOffset + lo * EntryBytes); + uint offset = BinaryPrimitives.ReadUInt32LittleEndian(e.Slice(8)); + uint size = BinaryPrimitives.ReadUInt32LittleEndian(e.Slice(12)); + if (size == 0 || size > (uint)maxSize || size > _length) return null; + var data = new byte[size]; + return ReadChain(offset, data) == data.Length ? data : null; + } + // Not in this node: a leaf (first child offset 0) ends the search; otherwise + // child `lo` holds the ids between entries lo-1 and lo. + if (BinaryPrimitives.ReadUInt32LittleEndian(_node) == 0) return null; + at = BinaryPrimitives.ReadUInt32LittleEndian(_node.AsSpan(lo * 4)); } return null; } @@ -133,41 +152,36 @@ internal sealed class AcDatFile : IDisposable } } - private static uint EntryId(byte[] node, int i) => - BinaryPrimitives.ReadUInt32LittleEndian(node.AsSpan(4 * Branches + 4 + i * EntrySize + 4)); + private uint IdAt(int i) => BinaryPrimitives.ReadUInt32LittleEndian(_node.AsSpan(EntriesOffset + i * EntryBytes + 4)); - /// A block chain: each block starts with the next block's offset (0 = last). - private byte[]? ReadChain(uint offset, int size) + // Copies the block chain at byte offset `first` into `dest`; returns the bytes + // filled (fewer than dest.Length when the chain ends first), -1 on a bad link. + private int ReadChain(uint first, Span dest) { - if ((long)offset + 4 > _fs.Length) return null; - var buffer = new byte[size]; - Span next = stackalloc byte[4]; - _fs.Seek(offset, SeekOrigin.Begin); - if (!ReadFully(_fs, next)) return null; - uint nextAddr = BinaryPrimitives.ReadUInt32LittleEndian(next); + long block = first; int done = 0; - int guard = 0; - while (done < size) + Span link = stackalloc byte[4]; + while (done < dest.Length) { - int take = Math.Min((int)_blockSize - 4, size - done); - if (!ReadFully(_fs, buffer.AsSpan(done, take))) return null; + if (block == 0) return done; + if (block + 4 > _length) return -1; + int take = Math.Min(_payload, dest.Length - done); + _fs.Position = block; + if (!ReadFully(_fs, link) || !ReadFully(_fs, dest.Slice(done, take))) return -1; done += take; - if (done >= size) break; - if (nextAddr == 0 || nextAddr >= _fs.Length || ++guard > 1_000_000) return null; - _fs.Seek(nextAddr, SeekOrigin.Begin); - if (!ReadFully(_fs, next)) return null; - nextAddr = BinaryPrimitives.ReadUInt32LittleEndian(next); + block = BinaryPrimitives.ReadUInt32LittleEndian(link); } - return buffer; + return done; } private static bool ReadFully(FileStream fs, Span dest) { - while (dest.Length > 0) + int got = 0; + while (got < dest.Length) { - int n = fs.Read(dest); + int n = fs.Read(dest.Slice(got)); if (n <= 0) return false; - dest = dest.Slice(n); + got += n; } return true; } @@ -251,7 +265,7 @@ internal static class AcIconDecoder /// /// A 0x06 Texture as RGBA, or null (not a texture id, missing, an unsupported format, larger - /// than , or short data). Layout: id u32, unknown i32, width i32, + /// than , or short data). Layout: id u32, data category u32, width i32, /// height i32, format u32, length i32, data[length], then for INDEX16/P8 a palette id u32. /// public static AcIconImage? Decode(AcDatFile dat, uint textureId) => Decode(dat, textureId, MaxSide); @@ -274,106 +288,109 @@ internal static class AcIconDecoder } } + private const uint FmtR8G8B8 = 0x14, FmtA8R8G8B8 = 0x15, FmtR5G6B5 = 0x17, FmtA4R4G4B4 = 0x1A, FmtA8 = 0x1C, + FmtP8 = 0x29, FmtIndex16 = 0x65, FmtLscapeR8G8B8 = 0xF3, FmtLscapeAlpha = 0xF4, + FmtDxt1 = 0x31545844, FmtDxt3 = 0x33545844, FmtDxt5 = 0x35545844; + /// A Texture file's bytes as RGBA (see ); loads a 0x04 palette. internal static AcIconImage? DecodeTextureFile(byte[] data, Func readPalette, int maxSide = MaxSide) { if (data.Length < 24) return null; - maxSide = Math.Clamp(maxSide, 1, MaxUiSide); - ReadOnlySpan d = data; - int w = BinaryPrimitives.ReadInt32LittleEndian(d[8..]); - int h = BinaryPrimitives.ReadInt32LittleEndian(d[12..]); - uint fmt = BinaryPrimitives.ReadUInt32LittleEndian(d[16..]); - int len = BinaryPrimitives.ReadInt32LittleEndian(d[20..]); - if (w <= 0 || h <= 0 || w > maxSide || h > maxSide || len < 0 || len > data.Length - 24) return null; - byte[] src = d.Slice(24, len).ToArray(); + var file = new ReadOnlySpan(data); + int w = BinaryPrimitives.ReadInt32LittleEndian(file.Slice(8)); + int h = BinaryPrimitives.ReadInt32LittleEndian(file.Slice(12)); + uint format = BinaryPrimitives.ReadUInt32LittleEndian(file.Slice(16)); + int length = BinaryPrimitives.ReadInt32LittleEndian(file.Slice(20)); + int limit = Math.Min(maxSide, MaxUiSide); + if (w <= 0 || h <= 0 || w > limit || h > limit) return null; + if (length < 0 || 24L + length > data.Length) return null; + var src = file.Slice(24, length); int n = w * h; - switch (fmt) + switch (format) { - case 827611204: return Dxt(src, w, h, 8, DxtUtil.DecompressDxt1); // DXT1 - case 861165636: return Dxt(src, w, h, 16, DxtUtil.DecompressDxt3); // DXT3 - case 894720068: return Dxt(src, w, h, 16, DxtUtil.DecompressDxt5); // DXT5 + case FmtDxt1: return Dxt(src, w, h, 8, DxtUtil.DecompressDxt1); + case FmtDxt3: return Dxt(src, w, h, 16, DxtUtil.DecompressDxt3); + case FmtDxt5: return Dxt(src, w, h, 16, DxtUtil.DecompressDxt5); } - var rgba = new byte[n * 4]; - void Px(int i, int r, int g, int b, int a) + var px = new byte[n * 4]; + switch (format) { - int o = i * 4; - rgba[o] = (byte)r; rgba[o + 1] = (byte)g; rgba[o + 2] = (byte)b; rgba[o + 3] = (byte)a; - } - - switch (fmt) - { - case 20: // R8G8B8, stored B, G, R - for (int i = 0; i < n && i * 3 + 2 < src.Length; i++) Px(i, src[i * 3 + 2], src[i * 3 + 1], src[i * 3], 255); + case FmtA8R8G8B8: // memory order B, G, R, A + if (length < n * 4) return null; + for (int i = 0; i < n; i++) Set(px, i, src[i * 4 + 2], src[i * 4 + 1], src[i * 4], src[i * 4 + 3]); break; - case 243: // CUSTOM_LSCAPE_R8G8B8, stored R, G, B - for (int i = 0; i < n && i * 3 + 2 < src.Length; i++) Px(i, src[i * 3], src[i * 3 + 1], src[i * 3 + 2], 255); + case FmtR8G8B8: // B, G, R + if (length < n * 3) return null; + for (int i = 0; i < n; i++) Set(px, i, src[i * 3 + 2], src[i * 3 + 1], src[i * 3], 255); break; - case 21: // A8R8G8B8, stored B, G, R, A - case 22: // X8R8G8B8 - for (int i = 0; i < n && i * 4 + 3 < src.Length; i++) - Px(i, src[i * 4 + 2], src[i * 4 + 1], src[i * 4], fmt == 22 ? 255 : src[i * 4 + 3]); + case FmtLscapeR8G8B8: // R, G, B + if (length < n * 3) return null; + for (int i = 0; i < n; i++) Set(px, i, src[i * 3], src[i * 3 + 1], src[i * 3 + 2], 255); break; - case 23: // R5G6B5 - for (int i = 0; i < n && i * 2 + 1 < src.Length; i++) - { - int v = src[i * 2] | (src[i * 2 + 1] << 8); - Px(i, ((v >> 11) & 0x1F) << 3, ((v >> 5) & 0x3F) << 2, (v & 0x1F) << 3, 255); - } - break; - case 26: // A4R4G4B4 - for (int i = 0; i < n && i * 2 + 1 < src.Length; i++) - { - int v = src[i * 2] | (src[i * 2 + 1] << 8); - Px(i, ((v >> 8) & 0xF) * 17, ((v >> 4) & 0xF) * 17, (v & 0xF) * 17, ((v >> 12) & 0xF) * 17); - } - break; - case 28: // A8 (greyscale) - case 244: // LSCAPE_ALPHA - for (int i = 0; i < n && i < src.Length; i++) Px(i, src[i], src[i], src[i], 255); - break; - case 101: // INDEX16 - case 41: // P8 - { - if (data.Length < 24 + len + 4) return null; - uint paletteId = BinaryPrimitives.ReadUInt32LittleEndian(d[(24 + len)..]); - uint[]? pal = Palette(readPalette(paletteId)); - if (pal == null || pal.Length == 0) return null; - bool p8 = fmt == 41; + case FmtR5G6B5: // top bits only, as the StatusAgent's decoder + if (length < n * 2) return null; for (int i = 0; i < n; i++) { - int idx; - if (p8) { if (i >= src.Length) break; idx = src[i]; } - else { if (i * 2 + 1 >= src.Length) break; idx = src[i * 2] | (src[i * 2 + 1] << 8); } - uint c = pal[idx % pal.Length]; - Px(i, (int)((c >> 16) & 0xFF), (int)((c >> 8) & 0xFF), (int)(c & 0xFF), (int)((c >> 24) & 0xFF)); + int v = src[i * 2] | (src[i * 2 + 1] << 8); + Set(px, i, (byte)(((v >> 11) & 0x1F) << 3), (byte)(((v >> 5) & 0x3F) << 2), (byte)((v & 0x1F) << 3), 255); + } + break; + case FmtA4R4G4B4: + if (length < n * 2) return null; + for (int i = 0; i < n; i++) + { + int v = src[i * 2] | (src[i * 2 + 1] << 8); + Set(px, i, (byte)(((v >> 8) & 0xF) * 17), (byte)(((v >> 4) & 0xF) * 17), (byte)((v & 0xF) * 17), (byte)(((v >> 12) & 0xF) * 17)); + } + break; + case FmtA8: // one byte a pixel: an opaque grey level + case FmtLscapeAlpha: + if (length < n) return null; + for (int i = 0; i < n; i++) Set(px, i, src[i], src[i], src[i], 255); + break; + case FmtP8: + case FmtIndex16: + { + int bytesPer = format == FmtP8 ? 1 : 2; + if (length < n * bytesPer || 24L + length + 4 > data.Length) return null; + uint[]? palette = Palette(readPalette(BinaryPrimitives.ReadUInt32LittleEndian(file.Slice(24 + length)))); + if (palette == null) return null; + for (int i = 0; i < n; i++) + { + int idx = bytesPer == 1 ? src[i] : src[i * 2] | (src[i * 2 + 1] << 8); + uint argb = idx < palette.Length ? palette[idx] : 0; + Set(px, i, (byte)(argb >> 16), (byte)(argb >> 8), (byte)argb, (byte)(argb >> 24)); } break; } default: - return null; // a format icons don't use + return null; // raw JPEG, anything else } - return new AcIconImage { Width = w, Height = h, Pixels = rgba }; + return new AcIconImage { Width = w, Height = h, Pixels = px }; } - private static AcIconImage? Dxt(byte[] src, int w, int h, int blockBytes, Func decompress) + private static void Set(byte[] px, int i, byte r, byte g, byte b, byte a) + { + px[i * 4] = r; px[i * 4 + 1] = g; px[i * 4 + 2] = b; px[i * 4 + 3] = a; + } + + private static AcIconImage? Dxt(ReadOnlySpan src, int w, int h, int blockBytes, Func decompress) { long need = (long)((w + 3) / 4) * ((h + 3) / 4) * blockBytes; - if (src.Length < need) return null; // DxtUtil would read past the end - byte[] rgba = decompress(src, w, h); - return rgba.Length == w * h * 4 ? new AcIconImage { Width = w, Height = h, Pixels = rgba } : null; + if (src.Length < need) return null; + return new AcIconImage { Width = w, Height = h, Pixels = decompress(src.Slice(0, (int)need).ToArray(), w, h) }; } /// Palette (0x04): id u32, count i32, count x u32 ARGB. private static uint[]? Palette(byte[]? data) { if (data == null || data.Length < 8) return null; - int n = BinaryPrimitives.ReadInt32LittleEndian(data.AsSpan(4)); - if (n <= 0 || n > 65536) return null; - n = Math.Min(n, (data.Length - 8) / 4); - var pal = new uint[n]; - for (int i = 0; i < n; i++) pal[i] = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(8 + i * 4)); - return pal; + int count = BinaryPrimitives.ReadInt32LittleEndian(data.AsSpan(4)); + if (count < 0 || 8L + count * 4L > data.Length) return null; + var colours = new uint[count]; + for (int i = 0; i < count; i++) colours[i] = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(8 + i * 4)); + return colours; } } diff --git a/src/RynthCore.PluginCore/RynthPluginBase.cs b/src/RynthCore.PluginCore/RynthPluginBase.cs index 1c3aa95..584960c 100644 --- a/src/RynthCore.PluginCore/RynthPluginBase.cs +++ b/src/RynthCore.PluginCore/RynthPluginBase.cs @@ -6,7 +6,25 @@ namespace RynthCore.PluginCore; public abstract class RynthPluginBase { - public virtual uint MinimumApiVersion => RynthCoreHost.BaselineApiVersion; + /// + /// The oldest engine API the plugin starts on (RynthPluginRuntime refuses older ones). Defaults to + /// the plugin's manifest minimum (RynthPluginMinEngineApi in its csproj, compiled in as + /// [assembly: RynthPluginManifest]) so the plugin's own check and the engine's/launcher's manifest + /// check agree; without a manifest, the SDK baseline. + /// + public virtual uint MinimumApiVersion => ManifestMinimum(GetType()) ?? RynthCoreHost.BaselineApiVersion; + + private static uint? ManifestMinimum(Type pluginType) + { + try + { + return System.Reflection.CustomAttributeExtensions.GetCustomAttribute(pluginType.Assembly)?.MinEngineApi; + } + catch + { + return null; + } + } protected RynthCoreApiNative Api { get; private set; } protected RynthCoreHost Host { get; private set; } @@ -68,4 +86,21 @@ public abstract class RynthPluginBase public virtual void OnKillNotification(string? deathMessage) { } public virtual void OnEnchantmentAdded(uint spellId, double durationSeconds) { } public virtual void OnEnchantmentRemoved(uint enchantmentId) { } + + // v77 (RynthCoreHost.HasUiHooks): the client's screens and AC's own tooltips and drag/drop. + // The plugin's exports call these through RynthPluginRuntime; an older engine never calls them. + + /// The client changed screens (): e.g. World to CharacterSelect at logout. + public virtual void OnScreenChanged(int oldMode, int newMode) { } + /// The client is shutting down and about to tear its UI down. Last chance to read AC + /// state; no ticks or events follow (Shutdown still does). + public virtual void OnClientCleanup() { } + /// AC shows a tooltip for an item (objectId) or a spell icon (spellId); both 0 for any other element. + public virtual void OnTooltipShow(uint objectId, uint spellId) { } + /// The tooltip from is gone. + public virtual void OnTooltipHide() { } + /// The player started dragging an item (objectId, its icon) or a spell (spellId) in AC's UI. + public virtual void OnDragStart(uint objectId, uint spellId, uint iconId) { } + /// AC took a dropped item or spell; targetElementId is the AC UI element it landed on. + public virtual void OnItemDropped(uint objectId, uint spellId, uint targetElementId) { } } diff --git a/src/RynthCore.PluginCore/RynthPluginRuntime.cs b/src/RynthCore.PluginCore/RynthPluginRuntime.cs index 4d84b64..12da027 100644 --- a/src/RynthCore.PluginCore/RynthPluginRuntime.cs +++ b/src/RynthCore.PluginCore/RynthPluginRuntime.cs @@ -279,6 +279,53 @@ public unsafe sealed class RynthPluginRuntime catch (Exception ex) { LogException("OnEnchantmentRemoved", ex); } } + // ── v77 UI callbacks ───────────────────────────────────────────────── + // Exports: RynthPluginOnScreenChanged(int, int), RynthPluginOnClientCleanup(), + // RynthPluginOnTooltipShow(uint, uint), RynthPluginOnTooltipHide(), + // RynthPluginOnDragStart(uint, uint, uint), RynthPluginOnItemDropped(uint, uint, uint); all cdecl. + + public void OnScreenChanged(int oldMode, int newMode) + { + if (!IsInitialized) return; + try { _plugin!.OnScreenChanged(oldMode, newMode); } + catch (Exception ex) { LogException("OnScreenChanged", ex); } + } + + public void OnClientCleanup() + { + if (!IsInitialized) return; + try { _plugin!.OnClientCleanup(); } + catch (Exception ex) { LogException("OnClientCleanup", ex); } + } + + public void OnTooltipShow(uint objectId, uint spellId) + { + if (!IsInitialized) return; + try { _plugin!.OnTooltipShow(objectId, spellId); } + catch (Exception ex) { LogException("OnTooltipShow", ex); } + } + + public void OnTooltipHide() + { + if (!IsInitialized) return; + try { _plugin!.OnTooltipHide(); } + catch (Exception ex) { LogException("OnTooltipHide", ex); } + } + + public void OnDragStart(uint objectId, uint spellId, uint iconId) + { + if (!IsInitialized) return; + try { _plugin!.OnDragStart(objectId, spellId, iconId); } + catch (Exception ex) { LogException("OnDragStart", ex); } + } + + public void OnItemDropped(uint objectId, uint spellId, uint targetElementId) + { + if (!IsInitialized) return; + try { _plugin!.OnItemDropped(objectId, spellId, targetElementId); } + catch (Exception ex) { LogException("OnItemDropped", ex); } + } + private void LogException(string method, Exception ex) { if (Interlocked.Increment(ref _exceptionCount) > MaxLoggedExceptions) diff --git a/src/RynthCore.PluginSdk/Manifest/PluginManifestReader.cs b/src/RynthCore.PluginSdk/Manifest/PluginManifestReader.cs new file mode 100644 index 0000000..7120ab8 --- /dev/null +++ b/src/RynthCore.PluginSdk/Manifest/PluginManifestReader.cs @@ -0,0 +1,196 @@ +// ============================================================================ +// RynthCore.PluginSdk - Manifest/PluginManifestReader.cs +// Reads a plugin's embedded manifest straight from the DLL file: the PE +// resource directory, RCDATA "RYNTH_PLUGIN_MANIFEST". Nothing is loaded or run, +// so the engine can refuse a plugin before LoadLibrary (a NativeAOT plugin +// can never be unloaded) and the launcher can read one it would never load. +// +// Works on NativeAOT and managed (IL) plugin DLLs, PE32 and PE32+. +// ============================================================================ + +using System; +using System.IO; +using System.Text; + +namespace RynthCore.PluginSdk.Manifest; + +public static class PluginManifestReader +{ + private const int MaxManifestBytes = 64 * 1024; + + /// + /// The plugin's manifest; null when the DLL has none (a plugin from before manifests: it + /// keeps working as before). Throws when there is one but + /// it is broken, and IO exceptions when the file can't be read. + /// + public static RynthPluginManifest? Read(string dllPath) + { + string? json = ReadJson(dllPath); + return json == null ? null : RynthPluginManifest.Parse(json); + } + + /// The embedded manifest's text, or null when the file has none. + public static string? ReadJson(string dllPath) + { + using var fs = new FileStream(dllPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); + return ReadJson(fs); + } + + /// The embedded manifest's text, or null when the image has none. + public static string? ReadJson(Stream pe) + { + byte[]? data = PeResources.Find(pe, RynthPluginManifest.ResourceType, RynthPluginManifest.ResourceName, MaxManifestBytes); + if (data == null) return null; + int start = data.Length >= 3 && data[0] == 0xEF && data[1] == 0xBB && data[2] == 0xBF ? 3 : 0; + int end = data.Length; + while (end > start && data[end - 1] == 0) end--; // UpdateResource data is exact, but tolerate padding + return Encoding.UTF8.GetString(data, start, end - start); + } +} + +/// A minimal reader for a PE file's resource directory (no Win32 calls). +public static class PeResources +{ + /// + /// The data of resource / (first language), or null + /// when the file has no such resource. Throws on a malformed image. + /// + public static byte[]? Find(Stream pe, int type, string name, int maxBytes) + { + var r = new BinaryReader(pe, Encoding.Unicode, leaveOpen: true); + long len = pe.Length; + if (len < 0x40) throw Bad("too small for a PE file"); + pe.Position = 0; + if (r.ReadUInt16() != 0x5A4D) throw Bad("no MZ header"); + pe.Position = 0x3C; + uint peOff = r.ReadUInt32(); + if (peOff > len - 24) throw Bad("PE header offset out of range"); + pe.Position = peOff; + if (r.ReadUInt32() != 0x00004550) throw Bad("no PE signature"); + r.ReadUInt16(); // machine + ushort sections = r.ReadUInt16(); + pe.Position += 12; // timestamp, symbol table, symbol count + ushort optSize = r.ReadUInt16(); + r.ReadUInt16(); // characteristics + long opt = pe.Position; + ushort magic = r.ReadUInt16(); + long dirs = magic switch + { + 0x10B => opt + 96, // PE32 + 0x20B => opt + 112, // PE32+ + _ => throw Bad($"unknown optional header magic 0x{magic:X}"), + }; + pe.Position = dirs - 4; + uint dirCount = r.ReadUInt32(); + if (dirCount < 3 || dirs + 3 * 8 > opt + optSize) return null; + pe.Position = dirs + 2 * 8; // IMAGE_DIRECTORY_ENTRY_RESOURCE + uint rsrcRva = r.ReadUInt32(); + uint rsrcSize = r.ReadUInt32(); + if (rsrcRva == 0 || rsrcSize == 0) return null; + + var table = new (uint Va, uint VSize, uint Raw, uint RawSize)[sections]; + pe.Position = opt + optSize; + for (int i = 0; i < sections; i++) + { + pe.Position += 8; // name + uint vsize = r.ReadUInt32(); + uint va = r.ReadUInt32(); + uint rawSize = r.ReadUInt32(); + uint raw = r.ReadUInt32(); + pe.Position += 16; + table[i] = (va, vsize, raw, rawSize); + } + + long ToOffset(uint rva, uint size) + { + foreach (var s in table) + { + uint span = Math.Max(s.VSize, s.RawSize); + if (rva >= s.Va && rva < s.Va + span) + { + long off = s.Raw + (long)(rva - s.Va); + if (rva - s.Va + (long)size > s.RawSize || off + size > len) throw Bad("resource data outside its section"); + return off; + } + } + throw Bad($"RVA 0x{rva:X} is in no section"); + } + + long root = ToOffset(rsrcRva, 16); + long rootEnd = root + rsrcSize; + + // Level 1: type (by id), level 2: name (by string), level 3: language (first). + long? typeDir = FindEntry(r, root, rootEnd, root, id: type, name: null); + if (typeDir is not { } td || td >= 0) { if (typeDir == null) return null; throw Bad("resource type entry is not a directory"); } + long? nameDir = FindEntry(r, root, rootEnd, root + (~td), id: -1, name: name); + if (nameDir is not { } nd) return null; + long langDir = nd < 0 ? root + (~nd) : throw Bad("resource name entry is not a directory"); + long dataEntry = FirstEntry(r, root, rootEnd, langDir); + if (dataEntry < 0) throw Bad("resource language entry is a directory"); + pe.Position = root + dataEntry; + uint dataRva = r.ReadUInt32(); + uint dataSize = r.ReadUInt32(); + if (dataSize > maxBytes) throw Bad($"resource is {dataSize} bytes (at most {maxBytes})"); + pe.Position = ToOffset(dataRva, dataSize); + byte[] data = r.ReadBytes((int)dataSize); + if (data.Length != dataSize) throw Bad("resource data truncated"); + return data; + } + + /// + /// Finds an entry in the directory at by id (or, with , + /// by name, case-insensitive). Returns the entry's OffsetToData relative to the resource root: + /// a subdirectory comes back as ~offset (negative), a data entry as the offset; null if absent. + /// + private static long? FindEntry(BinaryReader r, long root, long rootEnd, long dir, int id, string? name) + { + Stream s = r.BaseStream; + if (dir + 16 > rootEnd) throw Bad("resource directory out of range"); + s.Position = dir + 12; + int named = r.ReadUInt16(); + int ids = r.ReadUInt16(); + if (dir + 16 + (long)(named + ids) * 8 > rootEnd) throw Bad("resource directory entries out of range"); + for (int i = 0; i < named + ids; i++) + { + s.Position = dir + 16 + i * 8L; + uint nameField = r.ReadUInt32(); + uint dataField = r.ReadUInt32(); + bool isNamed = (nameField & 0x80000000) != 0; + bool match; + if (name != null) + { + if (!isNamed) continue; + long strAt = root + (nameField & 0x7FFFFFFF); + if (strAt + 2 > rootEnd) throw Bad("resource name out of range"); + s.Position = strAt; + int chars = r.ReadUInt16(); + if (strAt + 2 + chars * 2L > rootEnd) throw Bad("resource name out of range"); + string entryName = Encoding.Unicode.GetString(r.ReadBytes(chars * 2)); + match = string.Equals(entryName, name, StringComparison.OrdinalIgnoreCase); + } + else + { + match = !isNamed && (nameField & 0xFFFF) == id; + } + if (!match) continue; + long off = dataField & 0x7FFFFFFF; + return (dataField & 0x80000000) != 0 ? ~off : off; + } + return null; + } + + private static long FirstEntry(BinaryReader r, long root, long rootEnd, long dir) + { + Stream s = r.BaseStream; + if (dir + 16 > rootEnd) throw Bad("resource directory out of range"); + s.Position = dir + 12; + int count = r.ReadUInt16() + r.ReadUInt16(); + if (count == 0) throw Bad("empty resource language directory"); + s.Position = dir + 16 + 4; + uint dataField = r.ReadUInt32(); + long off = dataField & 0x7FFFFFFF; + return (dataField & 0x80000000) != 0 ? ~off : off; + } + + private static InvalidDataException Bad(string why) => new("not a readable PE file: " + why); +} diff --git a/src/RynthCore.PluginSdk/Manifest/PluginManifestResolver.cs b/src/RynthCore.PluginSdk/Manifest/PluginManifestResolver.cs new file mode 100644 index 0000000..e205bf4 --- /dev/null +++ b/src/RynthCore.PluginSdk/Manifest/PluginManifestResolver.cs @@ -0,0 +1,180 @@ +// ============================================================================ +// RynthCore.PluginSdk - Manifest/PluginManifestResolver.cs +// Decides which of a set of plugins can start on an engine, and in what order: +// - a plugin whose manifest needs a newer (or older) engine API is refused; +// - a plugin whose REQUIRED dependency is missing, too old or refused is refused +// (and so on down the chain); +// - required dependencies start before the plugins that need them. Optional +// dependencies never refuse anything and never reorder: plugins look each other +// up lazily (GetPluginInterface), and a pair of plugins that can use each other +// would otherwise form a cycle. +// A plugin without a manifest is never refused and keeps its place, so a set with no +// manifests at all comes out exactly as it went in. +// +// Pure logic, used by the engine's PluginManager and by tools\PluginManifestTests. +// ============================================================================ + +using System; +using System.Collections.Generic; + +namespace RynthCore.PluginSdk.Manifest; + +/// One plugin to consider: its path (or any key), and its manifest if it has one. +public sealed class PluginCandidate +{ + /// The DLL's version resource (ProductVersion), used when the manifest has no version or there is no manifest. + public PluginCandidate(string key, RynthPluginManifest? manifest, string? fileVersion = null) + { + Key = key; + Manifest = manifest; + Name = manifest?.Name is { Length: > 0 } n ? n : RynthPluginManifest.NameFromFile(key); + Version = manifest?.Version is { Length: > 0 } v ? v : fileVersion ?? ""; + } + + public string Key { get; } + public RynthPluginManifest? Manifest { get; } + /// The manifest name, or for a plugin without one the name from its file. + public string Name { get; } + public string Version { get; } +} + +public sealed class PluginRefusal +{ + public PluginRefusal(PluginCandidate plugin, string reason, bool engine) + { + Plugin = plugin; + Reason = reason; + IsEngineMismatch = engine; + } + + public PluginCandidate Plugin { get; } + /// One sentence, fit for chat: "RynthOracle needs a newer RynthCore (API 77)". + public string Reason { get; } + /// True for an engine API mismatch, false for a dependency problem. + public bool IsEngineMismatch { get; } +} + +public sealed class PluginResolution +{ + /// The plugins to load and start, in order. + public List Order { get; } = new(); + public List Refused { get; } = new(); + /// Things worth a log line that refuse nothing (a missing optional dependency, a dev build, a cycle). + public List Notes { get; } = new(); +} + +public static class PluginManifestResolver +{ + public static PluginResolution Resolve(IReadOnlyList candidates, uint engineApi) + { + var result = new PluginResolution(); + var refused = new Dictionary(); + + // 1. The engine API. + foreach (PluginCandidate c in candidates) + { + if (c.Manifest?.CheckEngine(engineApi) is { } why) + Refuse(result, refused, c, why, engine: true); + } + + // 2. Required dependencies, until nothing more falls. + bool changed = true; + while (changed) + { + changed = false; + foreach (PluginCandidate c in candidates) + { + if (refused.ContainsKey(c) || c.Manifest == null) continue; + foreach (RynthPluginDependency d in c.Manifest.Dependencies) + { + if (d.Optional) continue; + string? why = CheckDependency(candidates, refused, c, d); + if (why == null) continue; + Refuse(result, refused, c, why, engine: false); + changed = true; + break; + } + } + } + + // 3. Notes on optional dependencies and dev builds (refuse nothing). + foreach (PluginCandidate c in candidates) + { + if (refused.ContainsKey(c) || c.Manifest == null) continue; + foreach (RynthPluginDependency d in c.Manifest.Dependencies) + { + PluginCandidate? dep = Find(candidates, d.Name); + if (d.Optional && (dep == null || refused.ContainsKey(dep))) + result.Notes.Add($"{c.Name}: optional plugin {d.Name} is not loaded; the features that use it are off."); + else if (d.Optional && !PluginVersion.Satisfies(dep!.Version, d.MinVersion)) + result.Notes.Add($"{c.Name}: optional plugin {d.Name} is older ({dep.Version}) than it can use ({d.MinVersion})."); + else if (dep != null && d.MinVersion.Length > 0 && PluginVersion.IsDevBuild(dep.Version)) + result.Notes.Add($"{c.Name}: {d.Name} is a dev build ({dep.Version}); taken as satisfying {d.MinVersion}."); + } + } + + // 4. Order: each plugin after its required dependencies, otherwise as given. + var accepted = new List(); + foreach (PluginCandidate c in candidates) + if (!refused.ContainsKey(c)) accepted.Add(c); + + var placed = new HashSet(); + var visiting = new HashSet(); + void Place(PluginCandidate c) + { + if (placed.Contains(c)) return; + if (!visiting.Add(c)) + { + result.Notes.Add($"{c.Name}: its required dependencies form a cycle; started in list order."); + return; + } + if (c.Manifest != null) + { + foreach (RynthPluginDependency d in c.Manifest.Dependencies) + { + if (d.Optional) continue; + PluginCandidate? dep = Find(accepted, d.Name); + if (dep != null) Place(dep); + } + } + visiting.Remove(c); + if (placed.Add(c)) result.Order.Add(c); + } + foreach (PluginCandidate c in accepted) Place(c); + return result; + } + + /// + /// Null when is satisfied by a plugin in + /// (by name; a dev build satisfies any version), else why not. + /// + public static string? CheckDependency(IReadOnlyList available, IReadOnlyDictionary? refused, + PluginCandidate owner, RynthPluginDependency d) + { + PluginCandidate? dep = Find(available, d.Name); + string needs = d.MinVersion.Length > 0 ? $"{d.Name} {d.MinVersion} or newer" : $"the {d.Name} plugin"; + if (dep == null) + return $"{owner.Name} needs {needs}, which is not in the plugin list"; + if (refused != null && refused.ContainsKey(dep)) + return $"{owner.Name} needs {d.Name}, which was not loaded"; + if (!PluginVersion.Satisfies(dep.Version, d.MinVersion)) + return dep.Version.Length > 0 + ? $"{owner.Name} needs {d.Name} {d.MinVersion} or newer (this one is {dep.Version})" + : $"{owner.Name} needs {d.Name} {d.MinVersion} or newer (this one has no version)"; + return null; + } + + public static PluginCandidate? Find(IReadOnlyList list, string name) + { + foreach (PluginCandidate c in list) + if (string.Equals(c.Name, name, StringComparison.OrdinalIgnoreCase)) return c; + return null; + } + + private static void Refuse(PluginResolution result, Dictionary refused, PluginCandidate c, string why, bool engine) + { + if (refused.ContainsKey(c)) return; + refused[c] = why; + result.Refused.Add(new PluginRefusal(c, why, engine)); + } +} diff --git a/src/RynthCore.PluginSdk/Manifest/RynthPluginManifest.cs b/src/RynthCore.PluginSdk/Manifest/RynthPluginManifest.cs new file mode 100644 index 0000000..868c7bb --- /dev/null +++ b/src/RynthCore.PluginSdk/Manifest/RynthPluginManifest.cs @@ -0,0 +1,232 @@ +// ============================================================================ +// RynthCore.PluginSdk - Manifest/RynthPluginManifest.cs +// A plugin's manifest: who it is, which engine API it needs, which plugins it +// needs. Built from the plugin's csproj at build time (build\RynthCore.PluginSdk +// .targets) and embedded in the DLL as a Windows resource (RCDATA +// "RYNTH_PLUGIN_MANIFEST"), so it travels with the binary and is read without +// loading it (PluginManifestReader). +// +// Compiled into the SDK, the engine (PluginManager) and the launcher (updater); +// keep it free of anything but the BCL. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Text.Json; + +namespace RynthCore.PluginSdk.Manifest; + +/// One plugin another needs (or can use). +public sealed class RynthPluginDependency +{ + /// The other plugin's manifest name (for a plugin without a manifest: its file name without "RynthCore.Plugin." and ".dll"). + public string Name { get; set; } = ""; + /// The lowest version that will do; empty for any. + public string MinVersion { get; set; } = ""; + /// True: used when present, the plugin still runs without it. False: required, the plugin isn't started without it. + public bool Optional { get; set; } +} + +/// A plugin's manifest (schema 1). Unknown JSON fields are ignored, so later schemas can add fields. +public sealed class RynthPluginManifest +{ + /// Windows resource type the manifest is stored under (RT_RCDATA). + public const int ResourceType = 10; + /// Windows resource name the manifest is stored under. + public const string ResourceName = "RYNTH_PLUGIN_MANIFEST"; + public const int CurrentSchema = 1; + + public int Schema { get; set; } = CurrentSchema; + public string Name { get; set; } = ""; + public string Version { get; set; } = ""; + /// The oldest engine API the plugin runs on: its highest unguarded API use. + public uint MinEngineApi { get; set; } + /// The newest engine API the plugin is known to work with; 0 = no upper limit (the usual case: the table is append-only). + public uint MaxEngineApi { get; set; } + public List Dependencies { get; set; } = new(); + public string Author { get; set; } = ""; + public string Description { get; set; } = ""; + public string Homepage { get; set; } = ""; + public string License { get; set; } = ""; + + /// Parses a manifest; throws with the reason when it isn't one. + public static RynthPluginManifest Parse(string json) + { + JsonDocument doc; + try { doc = JsonDocument.Parse(json, new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip }); } + catch (JsonException ex) { throw new InvalidDataException("the plugin manifest is not valid JSON: " + ex.Message); } + + using (doc) + { + JsonElement r = doc.RootElement; + if (r.ValueKind != JsonValueKind.Object) + throw new InvalidDataException("the plugin manifest is not a JSON object"); + + var m = new RynthPluginManifest(); + if (r.TryGetProperty("schema", out JsonElement s)) + { + if (s.ValueKind != JsonValueKind.Number || !s.TryGetInt32(out int schema) || schema < 1) + throw new InvalidDataException("the plugin manifest's schema is not a positive number"); + m.Schema = schema; + } + m.Name = Str(r, "name").Trim(); + if (m.Name.Length == 0) + throw new InvalidDataException("the plugin manifest has no name"); + m.Version = Str(r, "version").Trim(); + m.MinEngineApi = Api(r, "minEngineApi"); + m.MaxEngineApi = Api(r, "maxEngineApi"); + if (m.MaxEngineApi != 0 && m.MaxEngineApi < m.MinEngineApi) + throw new InvalidDataException($"the plugin manifest's maxEngineApi ({m.MaxEngineApi}) is below its minEngineApi ({m.MinEngineApi})"); + m.Author = Str(r, "author"); + m.Description = Str(r, "description"); + m.Homepage = Str(r, "homepage"); + m.License = Str(r, "license"); + + if (r.TryGetProperty("dependencies", out JsonElement deps) && deps.ValueKind != JsonValueKind.Null) + { + if (deps.ValueKind != JsonValueKind.Array) + throw new InvalidDataException("the plugin manifest's dependencies is not an array"); + foreach (JsonElement d in deps.EnumerateArray()) + { + var dep = new RynthPluginDependency(); + if (d.ValueKind == JsonValueKind.String) + { + // Shorthand: "RynthNav" or "RynthNav@2026.10.1.1" (required). + string text = d.GetString() ?? ""; + int at = text.IndexOf('@'); + dep.Name = (at >= 0 ? text[..at] : text).Trim(); + dep.MinVersion = at >= 0 ? text[(at + 1)..].Trim() : ""; + } + else if (d.ValueKind == JsonValueKind.Object) + { + dep.Name = Str(d, "name").Trim(); + dep.MinVersion = Str(d, "minVersion").Trim(); + dep.Optional = d.TryGetProperty("optional", out JsonElement o) && o.ValueKind == JsonValueKind.True; + } + else + { + throw new InvalidDataException("a plugin manifest dependency is neither a name nor an object"); + } + if (dep.Name.Length == 0) + throw new InvalidDataException("a plugin manifest dependency has no name"); + if (dep.MinVersion.Length > 0 && !PluginVersion.TryParse(dep.MinVersion, out _)) + throw new InvalidDataException($"dependency {dep.Name}: minVersion '{dep.MinVersion}' is not a version"); + if (string.Equals(dep.Name, m.Name, StringComparison.OrdinalIgnoreCase)) + throw new InvalidDataException("the plugin manifest lists the plugin as its own dependency"); + m.Dependencies.Add(dep); + } + } + return m; + } + } + + /// Parses, or returns null with the reason in . + public static RynthPluginManifest? TryParse(string json, out string error) + { + try { error = ""; return Parse(json); } + catch (InvalidDataException ex) { error = ex.Message; return null; } + } + + /// The manifest as JSON (UTF-8, indented): what the build embeds. + public string ToJson() + { + using var ms = new MemoryStream(); + using (var w = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = true })) + { + w.WriteStartObject(); + w.WriteNumber("schema", Schema); + w.WriteString("name", Name); + if (Version.Length > 0) w.WriteString("version", Version); + w.WriteNumber("minEngineApi", MinEngineApi); + if (MaxEngineApi != 0) w.WriteNumber("maxEngineApi", MaxEngineApi); + w.WriteStartArray("dependencies"); + foreach (RynthPluginDependency d in Dependencies) + { + w.WriteStartObject(); + w.WriteString("name", d.Name); + if (d.MinVersion.Length > 0) w.WriteString("minVersion", d.MinVersion); + if (d.Optional) w.WriteBoolean("optional", true); + w.WriteEndObject(); + } + w.WriteEndArray(); + if (Author.Length > 0) w.WriteString("author", Author); + if (Description.Length > 0) w.WriteString("description", Description); + if (Homepage.Length > 0) w.WriteString("homepage", Homepage); + if (License.Length > 0) w.WriteString("license", License); + w.WriteEndObject(); + } + return Encoding.UTF8.GetString(ms.ToArray()); + } + + /// + /// Null when this engine API can run the plugin, else why not, in a form fit for chat: + /// "RynthOracle needs a newer RynthCore (API 77)". + /// + public string? CheckEngine(uint engineApi) + { + if (MinEngineApi > engineApi) + return $"{Name} needs a newer RynthCore (API {MinEngineApi})"; + if (MaxEngineApi != 0 && MaxEngineApi < engineApi) + return $"{Name} is too old for this RynthCore (it works up to API {MaxEngineApi}, this is API {engineApi})"; + return null; + } + + /// "RynthCore.Plugin.RynthNav.dll" -> "RynthNav": the name a plugin without a manifest goes by. + public static string NameFromFile(string path) + { + string name = Path.GetFileNameWithoutExtension(path) ?? ""; + const string prefix = "RynthCore.Plugin."; + return name.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) ? name[prefix.Length..] : name; + } + + private static string Str(JsonElement o, string name) => + o.TryGetProperty(name, out JsonElement e) && e.ValueKind == JsonValueKind.String ? e.GetString() ?? "" : ""; + + private static uint Api(JsonElement o, string name) + { + if (!o.TryGetProperty(name, out JsonElement e) || e.ValueKind == JsonValueKind.Null) return 0; + if (e.ValueKind == JsonValueKind.Number && e.TryGetUInt32(out uint v)) return v; + if (e.ValueKind == JsonValueKind.String && uint.TryParse(e.GetString(), out uint sv)) return sv; + throw new InvalidDataException($"the plugin manifest's {name} is not a whole number"); + } +} + +/// Plugin version strings: "2026.10.5.1", "1.2", "2026.10.5.1+8ca322f". +public static class PluginVersion +{ + /// Parses the numeric part (build metadata after '+' and a '-prerelease' tail are ignored). + public static bool TryParse(string? text, out Version version) + { + version = new Version(0, 0); + if (string.IsNullOrWhiteSpace(text)) return false; + string t = text.Trim(); + if (t.StartsWith("v", StringComparison.OrdinalIgnoreCase)) t = t[1..]; + int cut = t.IndexOfAny(new[] { '+', '-', ' ' }); + if (cut >= 0) t = t[..cut]; + if (t.Length == 0) return false; + if (!t.Contains('.')) t += ".0"; + return System.Version.TryParse(t, out version!); + } + + /// + /// An unstamped build: the SDK's default version, 1.0.0 (Deploy-RynthCore.ps1, IDE builds). + /// It satisfies any minimum version, so dev setups keep working; the engine logs it. + /// + public static bool IsDevBuild(string? text) => + TryParse(text, out Version v) && v.Major == 1 && v.Minor == 0 && v.Build <= 0 && v.Revision <= 0; + + /// True when is at least (or either is missing, or actual is a dev build). + public static bool Satisfies(string? actual, string? minimum) + { + if (string.IsNullOrWhiteSpace(minimum)) return true; + if (!TryParse(minimum, out Version min)) return true; + if (!TryParse(actual, out Version have)) return false; + if (IsDevBuild(actual)) return true; + return Normalize(have) >= Normalize(min); + } + + private static Version Normalize(Version v) => + new(v.Major, v.Minor, Math.Max(v.Build, 0), Math.Max(v.Revision, 0)); +} diff --git a/src/RynthCore.PluginSdk/Net/Messages.cs b/src/RynthCore.PluginSdk/Net/Messages.cs new file mode 100644 index 0000000..5b4023e --- /dev/null +++ b/src/RynthCore.PluginSdk/Net/Messages.cs @@ -0,0 +1,350 @@ +// ============================================================================ +// RynthCore.PluginSdk - Net/Messages.cs +// Typed, read-only parsers for server messages the engine doesn't already turn into +// plugin events: chat with sender ids (speech, ranged speech, tells, emotes, channel +// broadcasts), fellowship, friends, allegiance logins, confirmation prompts, and popup +// and transient system text. +// +// Layouts written for RynthCore from general knowledge of the AC wire format (field +// order and sizes); no generated definitions or copied code. Each TryParse takes the +// bytes after the opcode (top-level messages) or after the event type (game events), +// never throws, and returns false for data that doesn't fit the layout. Consumed +// says how many bytes the parse used, so a mismatch with the real server shows up as +// leftover bytes (the engine's /rc netmsg log reports it). +// ============================================================================ + +using System; +using System.Collections.Generic; + +namespace RynthCore.PluginSdk.Net; + +// ─── chat ─────────────────────────────────────────────────────────────────── + +/// 0x02BB: local speech. Text, sender name, sender id, chat type. +public sealed record HearSpeech(string Text, string SenderName, uint SenderId, uint ChatType) +{ + public static bool TryParse(ReadOnlySpan body, out HearSpeech msg) => TryParse(body, out msg, out _); + + public static bool TryParse(ReadOnlySpan body, out HearSpeech msg, out int consumed) + { + msg = null!; + var r = new NetReader(body); + if (!r.String16L(out string text) || !r.String16L(out string name) || + !r.U32(out uint sender) || !r.U32(out uint type)) + { + consumed = r.Position; + return false; + } + msg = new HearSpeech(text, name, sender, type); + consumed = r.Position; + return true; + } +} + +/// 0x02BC: ranged speech (shouts, NPC speech). Text, sender name, sender id, range, chat type. +public sealed record HearRangedSpeech(string Text, string SenderName, uint SenderId, float Range, uint ChatType) +{ + public static bool TryParse(ReadOnlySpan body, out HearRangedSpeech msg) => TryParse(body, out msg, out _); + + public static bool TryParse(ReadOnlySpan body, out HearRangedSpeech msg, out int consumed) + { + msg = null!; + var r = new NetReader(body); + if (!r.String16L(out string text) || !r.String16L(out string name) || + !r.U32(out uint sender) || !r.F32(out float range) || !r.U32(out uint type)) + { + consumed = r.Position; + return false; + } + msg = new HearRangedSpeech(text, name, sender, range, type); + consumed = r.Position; + return true; + } +} + +/// 0x01E0 (emote) and 0x01E2 (soul emote): sender id, sender name, text. +public sealed record HearEmote(uint SenderId, string SenderName, string Text, bool Soul) +{ + public static bool TryParse(ReadOnlySpan body, bool soul, out HearEmote msg) => TryParse(body, soul, out msg, out _); + + public static bool TryParse(ReadOnlySpan body, bool soul, out HearEmote msg, out int consumed) + { + msg = null!; + var r = new NetReader(body); + if (!r.U32(out uint sender) || !r.String16L(out string name) || !r.String16L(out string text)) + { + consumed = r.Position; + return false; + } + msg = new HearEmote(sender, name, text, soul); + consumed = r.Position; + return true; + } +} + +/// Game event 0x02BD: a tell. Text, sender name, sender id, target id, chat type, then a u32 of flags. +public sealed record HearDirectSpeech(string Text, string SenderName, uint SenderId, uint TargetId, uint ChatType, uint Flags) +{ + public static bool TryParse(ReadOnlySpan body, out HearDirectSpeech msg) => TryParse(body, out msg, out _); + + public static bool TryParse(ReadOnlySpan body, out HearDirectSpeech msg, out int consumed) + { + msg = null!; + var r = new NetReader(body); + if (!r.String16L(out string text) || !r.String16L(out string name) || !r.U32(out uint sender) || + !r.U32(out uint target) || !r.U32(out uint type) || !r.U32(out uint flags)) + { + consumed = r.Position; + return false; + } + msg = new HearDirectSpeech(text, name, sender, target, type, flags); + consumed = r.Position; + return true; + } +} + +/// Game event 0x0147: a chat channel line (allegiance, fellowship, ...). Channel id, sender name (empty for your own), text. +public sealed record ChannelBroadcast(uint Channel, string SenderName, string Text) +{ + public static bool TryParse(ReadOnlySpan body, out ChannelBroadcast msg) => TryParse(body, out msg, out _); + + public static bool TryParse(ReadOnlySpan body, out ChannelBroadcast msg, out int consumed) + { + msg = null!; + var r = new NetReader(body); + if (!r.U32(out uint channel) || !r.String16L(out string name) || !r.String16L(out string text)) + { + consumed = r.Position; + return false; + } + msg = new ChannelBroadcast(channel, name, text); + consumed = r.Position; + return true; + } +} + +/// Game events 0x0004 (popup box) and 0x02EB (transient text): one string. +public sealed record SystemText(string Text, bool Transient) +{ + public static bool TryParse(ReadOnlySpan body, bool transient, out SystemText msg) => TryParse(body, transient, out msg, out _); + + public static bool TryParse(ReadOnlySpan body, bool transient, out SystemText msg, out int consumed) + { + msg = null!; + var r = new NetReader(body); + if (!r.String16L(out string text)) + { + consumed = r.Position; + return false; + } + msg = new SystemText(text, transient); + consumed = r.Position; + return true; + } +} + +/// Game event 0x0274: a yes/no prompt (fellowship invite, swear allegiance, crafting...). Type, context id, text. +public sealed record ConfirmationRequest(uint ConfirmationType, uint ContextId, string Text) +{ + public static bool TryParse(ReadOnlySpan body, out ConfirmationRequest msg) => TryParse(body, out msg, out _); + + public static bool TryParse(ReadOnlySpan body, out ConfirmationRequest msg, out int consumed) + { + msg = null!; + var r = new NetReader(body); + if (!r.U32(out uint type) || !r.U32(out uint context) || !r.String16L(out string text)) + { + consumed = r.Position; + return false; + } + msg = new ConfirmationRequest(type, context, text); + consumed = r.Position; + return true; + } +} + +// ─── allegiance, friends ──────────────────────────────────────────────────── + +/// Game event 0x027A: an allegiance member logged in or out. Character id, logged in (u32 flag). +public sealed record AllegianceLoginNotification(uint CharacterId, bool LoggedIn) +{ + public static bool TryParse(ReadOnlySpan body, out AllegianceLoginNotification msg) => TryParse(body, out msg, out _); + + public static bool TryParse(ReadOnlySpan body, out AllegianceLoginNotification msg, out int consumed) + { + msg = null!; + var r = new NetReader(body); + if (!r.U32(out uint id) || !r.Bool32(out bool on)) + { + consumed = r.Position; + return false; + } + msg = new AllegianceLoginNotification(id, on); + consumed = r.Position; + return true; + } +} + +/// One friends-list entry: id, online, appearing offline, name, and the two id lists the server keeps with it. +public sealed record FriendData(uint Id, bool Online, bool AppearOffline, string Name, uint[] OutFriends, uint[] InFriends); + +/// Game event 0x0021: the friends list, whole or changed. A packed list of entries, then the update type. +public sealed record FriendsUpdate(IReadOnlyList Friends, uint UpdateType) +{ + public const uint Full = 0, Added = 1, Removed = 2, LoginChange = 4; + + public static bool TryParse(ReadOnlySpan body, out FriendsUpdate msg) => TryParse(body, out msg, out _); + + public static bool TryParse(ReadOnlySpan body, out FriendsUpdate msg, out int consumed) + { + msg = null!; + var r = new NetReader(body); + bool ok = r.ListCount(out int n, 4 + 4 + 4 + 4 + 4 + 4); + var list = new List(ok ? n : 0); + for (int i = 0; ok && i < n; i++) + { + if (r.U32(out uint id) && r.Bool32(out bool online) && r.Bool32(out bool appearOffline) && + r.String16L(out string name) && r.U32List(out uint[] outs) && r.U32List(out uint[] ins)) + list.Add(new FriendData(id, online, appearOffline, name, outs, ins)); + else + ok = false; + } + uint type = 0; + ok = ok && r.U32(out type); + consumed = r.Position; + if (!ok) return false; + msg = new FriendsUpdate(list, type); + return true; + } +} + +// ─── fellowship ───────────────────────────────────────────────────────────── + +/// A fellowship member: cached XP and luminance shares, level, max and current vitals, share-loot flag, name. +public sealed record Fellow(uint Id, string Name, uint Level, uint XpCached, uint LumCached, + uint MaxHealth, uint MaxStamina, uint MaxMana, uint Health, uint Stamina, uint Mana, bool ShareLoot) +{ + /// Fellow body: 9 u32 (xp, lum, level, max h/s/m, current h/s/m), u32 share-loot flag, name. + internal static bool Read(ref NetReader r, uint id, out Fellow fellow) + { + fellow = null!; + if (!r.U32(out uint xp) || !r.U32(out uint lum) || !r.U32(out uint level) || + !r.U32(out uint maxH) || !r.U32(out uint maxS) || !r.U32(out uint maxM) || + !r.U32(out uint h) || !r.U32(out uint s) || !r.U32(out uint m) || + !r.Bool32(out bool shareLoot) || !r.String16L(out string name)) + return false; + fellow = new Fellow(id, name, level, xp, lum, maxH, maxS, maxM, h, s, m, shareLoot); + return true; + } + + internal const int MinSize = 10 * 4 + 4; +} + +/// +/// Game event 0x02BE: the whole fellowship. Members (packed table id to fellow), name, +/// leader id, then four u32 flags: share XP, even XP split, open, locked. After that the +/// server sends the recently departed members and the fellowship locks; those are read +/// when they fit (), and the members are returned either way. +/// +public sealed record FellowshipFullUpdate(string Name, uint LeaderId, bool ShareXp, bool EvenXpSplit, bool Open, bool Locked, + IReadOnlyList Fellows, IReadOnlyDictionary RecentlyDeparted, IReadOnlyList LockNames, bool TailParsed) +{ + public static bool TryParse(ReadOnlySpan body, out FellowshipFullUpdate msg) => TryParse(body, out msg, out _); + + public static bool TryParse(ReadOnlySpan body, out FellowshipFullUpdate msg, out int consumed) + { + msg = null!; + var r = new NetReader(body); + bool ok = r.TableCount(out int n, 4 + Fellow.MinSize); + var fellows = new List(ok ? n : 0); + for (int i = 0; ok && i < n; i++) + { + if (r.U32(out uint id) && Fellow.Read(ref r, id, out Fellow f)) + fellows.Add(f); + else + ok = false; + } + string name = string.Empty; + uint leader = 0; + bool shareXp = false, even = false, open = false, locked = false; + ok = ok && r.String16L(out name) && r.U32(out leader) && + r.Bool32(out shareXp) && r.Bool32(out even) && r.Bool32(out open) && r.Bool32(out locked); + if (!ok) + { + consumed = r.Position; + return false; + } + + // Tail: recently departed (id -> i32), then locks (name -> 5 x u32 of lock data). + int mainEnd = r.Position; + var departed = new Dictionary(); + var locks = new List(); + bool tail = r.TableCount(out int d, 8); + for (int i = 0; tail && i < d; i++) + { + if (r.U32(out uint id) && r.I32(out int t)) + departed[id] = t; + else + tail = false; + } + int l = 0; + tail = tail && r.TableCount(out l, 4 + 20); + for (int i = 0; tail && i < l; i++) + { + if (r.String16L(out string lockName) && r.Skip(20)) + locks.Add(lockName); + else + tail = false; + } + if (!tail) + { + departed.Clear(); + locks.Clear(); + } + consumed = tail ? r.Position : mainEnd; + msg = new FellowshipFullUpdate(name, leader, shareXp, even, open, locked, fellows, departed, locks, tail); + return true; + } +} + +/// Game event 0x02C0: one member changed. Fellow id, the fellow, update type (1 full, 2 stats, 3 vitals). +public sealed record FellowshipUpdateFellow(Fellow Fellow, uint UpdateType) +{ + public static bool TryParse(ReadOnlySpan body, out FellowshipUpdateFellow msg) => TryParse(body, out msg, out _); + + public static bool TryParse(ReadOnlySpan body, out FellowshipUpdateFellow msg, out int consumed) + { + msg = null!; + var r = new NetReader(body); + Fellow f = null!; + uint type = 0; + bool ok = r.U32(out uint id) && Fellow.Read(ref r, id, out f) && r.U32(out type); + consumed = r.Position; + if (!ok) return false; + msg = new FellowshipUpdateFellow(f, type); + return true; + } +} + +/// Game events 0x00A3 (a member quit) and 0x00A4 (a member was dismissed): the member's id. +public sealed record FellowshipMemberLeft(uint FellowId, bool Dismissed) +{ + public static bool TryParse(ReadOnlySpan body, bool dismissed, out FellowshipMemberLeft msg) => TryParse(body, dismissed, out msg, out _); + + public static bool TryParse(ReadOnlySpan body, bool dismissed, out FellowshipMemberLeft msg, out int consumed) + { + msg = null!; + var r = new NetReader(body); + bool ok = r.U32(out uint id); + consumed = r.Position; + if (!ok) return false; + msg = new FellowshipMemberLeft(id, dismissed); + return true; + } +} + +/// Game event 0x02BF: the fellowship was disbanded (no body). +public sealed record FellowshipDisband +{ + public static readonly FellowshipDisband Instance = new(); +} diff --git a/src/RynthCore.PluginSdk/Net/NetMessages.cs b/src/RynthCore.PluginSdk/Net/NetMessages.cs new file mode 100644 index 0000000..0413c4e --- /dev/null +++ b/src/RynthCore.PluginSdk/Net/NetMessages.cs @@ -0,0 +1,121 @@ +// ============================================================================ +// RynthCore.PluginSdk - Net/NetMessages.cs +// One entry point over the typed parsers: which message is this, did it parse, how +// many bytes were left over, and a one-line summary. Used by the engine's +// /rc netmsg log (to check the layouts against a live server) and by the replay runner. +// ============================================================================ + +using System; +using System.Globalization; + +namespace RynthCore.PluginSdk.Net; + +/// The result of . +public readonly record struct NetMessageInfo(string Kind, bool Known, bool Parsed, int Leftover, string Summary, object? Value); + +public static class NetMessages +{ + /// + /// Parses if the SDK knows it. Leftover is the bytes the layout + /// didn't account for (non-zero means the layout and the server disagree). + /// + public static NetMessageInfo Inspect(ServerMessage m) + { + if (m.Opcode == ServerMessage.GameEventOpcode) + { + if (!m.IsGameEvent) + return new("GameEvent(short)", true, false, m.Body.Length, "", null); + return InspectEvent(m.EventType, m.EventBody); + } + + ReadOnlySpan b = m.Body; + switch (m.Opcode) + { + case ServerOpcode.HearSpeech: + { + bool ok = HearSpeech.TryParse(b, out var v, out int used); + return Done("HearSpeech", ok, b, used, ok ? $"{v.SenderName} (0x{v.SenderId:X8}) type {v.ChatType}: {v.Text}" : "", v); + } + case ServerOpcode.HearRangedSpeech: + { + bool ok = HearRangedSpeech.TryParse(b, out var v, out int used); + return Done("HearRangedSpeech", ok, b, used, ok ? $"{v.SenderName} (0x{v.SenderId:X8}) range {v.Range.ToString("0.#", CultureInfo.InvariantCulture)} type {v.ChatType}: {v.Text}" : "", v); + } + case ServerOpcode.HearEmote: + case ServerOpcode.HearSoulEmote: + { + bool soul = m.Opcode == ServerOpcode.HearSoulEmote; + bool ok = HearEmote.TryParse(b, soul, out var v, out int used); + return Done(soul ? "HearSoulEmote" : "HearEmote", ok, b, used, ok ? $"{v.SenderName} (0x{v.SenderId:X8}): {v.Text}" : "", v); + } + } + return new($"0x{m.Opcode:X4}", false, false, 0, "", null); + } + + private static NetMessageInfo InspectEvent(uint type, ReadOnlySpan b) + { + switch (type) + { + case GameEventType.HearDirectSpeech: + { + bool ok = HearDirectSpeech.TryParse(b, out var v, out int used); + return Done("HearDirectSpeech", ok, b, used, ok ? $"{v.SenderName} (0x{v.SenderId:X8}) -> 0x{v.TargetId:X8} type {v.ChatType}: {v.Text}" : "", v); + } + case GameEventType.ChannelBroadcast: + { + bool ok = ChannelBroadcast.TryParse(b, out var v, out int used); + return Done("ChannelBroadcast", ok, b, used, ok ? $"channel {v.Channel} {v.SenderName}: {v.Text}" : "", v); + } + case GameEventType.PopUpString: + case GameEventType.TransientString: + { + bool transient = type == GameEventType.TransientString; + bool ok = SystemText.TryParse(b, transient, out var v, out int used); + return Done(transient ? "TransientString" : "PopUpString", ok, b, used, ok ? v.Text : "", v); + } + case GameEventType.ConfirmationRequest: + { + bool ok = ConfirmationRequest.TryParse(b, out var v, out int used); + return Done("ConfirmationRequest", ok, b, used, ok ? $"type {v.ConfirmationType} context 0x{v.ContextId:X8}: {v.Text}" : "", v); + } + case GameEventType.AllegianceLoginNotification: + { + bool ok = AllegianceLoginNotification.TryParse(b, out var v, out int used); + return Done("AllegianceLoginNotification", ok, b, used, ok ? $"0x{v.CharacterId:X8} {(v.LoggedIn ? "logged in" : "logged out")}" : "", v); + } + case GameEventType.FriendsUpdate: + { + bool ok = FriendsUpdate.TryParse(b, out var v, out int used); + return Done("FriendsUpdate", ok, b, used, ok ? $"type {v.UpdateType}, {v.Friends.Count} friend(s){FirstFriend(v)}" : "", v); + } + case GameEventType.FellowshipFullUpdate: + { + bool ok = FellowshipFullUpdate.TryParse(b, out var v, out int used); + return Done("FellowshipFullUpdate", ok, b, used, + ok ? $"'{v.Name}' leader 0x{v.LeaderId:X8}, {v.Fellows.Count} member(s), shareXp={v.ShareXp} even={v.EvenXpSplit} open={v.Open} locked={v.Locked} tail={(v.TailParsed ? "ok" : "unread")}" : "", v); + } + case GameEventType.FellowshipUpdateFellow: + { + bool ok = FellowshipUpdateFellow.TryParse(b, out var v, out int used); + return Done("FellowshipUpdateFellow", ok, b, used, + ok ? $"{v.Fellow.Name} (0x{v.Fellow.Id:X8}) L{v.Fellow.Level} hp {v.Fellow.Health}/{v.Fellow.MaxHealth} update {v.UpdateType}" : "", v); + } + case GameEventType.FellowshipQuit: + case GameEventType.FellowshipDismiss: + { + bool dismissed = type == GameEventType.FellowshipDismiss; + bool ok = FellowshipMemberLeft.TryParse(b, dismissed, out var v, out int used); + return Done(dismissed ? "FellowshipDismiss" : "FellowshipQuit", ok, b, used, ok ? $"0x{v.FellowId:X8}" : "", v); + } + case GameEventType.FellowshipDisband: + return Done("FellowshipDisband", true, b, 0, "", FellowshipDisband.Instance); + } + return new($"GameEvent 0x{type:X4}", false, false, 0, "", null); + } + + private static string FirstFriend(FriendsUpdate v) + => v.Friends.Count == 0 ? "" : $", first {v.Friends[0].Name} online={v.Friends[0].Online}"; + + private static NetMessageInfo Done(string kind, bool ok, ReadOnlySpan body, int used, string summary, object? value) + => new(kind, true, ok, ok ? body.Length - used : body.Length, summary, ok ? value : null); +} diff --git a/src/RynthCore.PluginSdk/Net/NetReader.cs b/src/RynthCore.PluginSdk/Net/NetReader.cs new file mode 100644 index 0000000..b89107e --- /dev/null +++ b/src/RynthCore.PluginSdk/Net/NetReader.cs @@ -0,0 +1,160 @@ +// ============================================================================ +// RynthCore.PluginSdk - Net/NetReader.cs +// Bounds-checked little-endian reader for server message bodies. +// +// Every read returns false instead of throwing when the data runs out, so a parser +// given a short or unexpected message fails cleanly. Written for RynthCore (same rules +// as the engine's PropertyWire reader); also compiled into the engine. +// ============================================================================ + +using System; +using System.Buffers.Binary; +using System.Text; + +namespace RynthCore.PluginSdk.Net; + +/// Reads AC wire types from a span: u16/u32/f32/f64, 16-bit-length strings, packed lists and tables. +public ref struct NetReader +{ + private readonly ReadOnlySpan _s; + private int _pos; + + public NetReader(ReadOnlySpan data) + { + _s = data; + _pos = 0; + } + + public int Position => _pos; + public int Length => _s.Length; + public int Remaining => _s.Length - _pos; + + public bool Has(int n) => n >= 0 && _pos + n <= _s.Length && _pos + n >= _pos; + + public bool Skip(int n) + { + if (!Has(n)) return false; + _pos += n; + return true; + } + + public bool U8(out byte v) + { + v = 0; + if (!Has(1)) return false; + v = _s[_pos++]; + return true; + } + + public bool U16(out ushort v) + { + v = 0; + if (!Has(2)) return false; + v = BinaryPrimitives.ReadUInt16LittleEndian(_s.Slice(_pos)); + _pos += 2; + return true; + } + + public bool U32(out uint v) + { + v = 0; + if (!Has(4)) return false; + v = BinaryPrimitives.ReadUInt32LittleEndian(_s.Slice(_pos)); + _pos += 4; + return true; + } + + public bool I32(out int v) + { + v = 0; + if (!Has(4)) return false; + v = BinaryPrimitives.ReadInt32LittleEndian(_s.Slice(_pos)); + _pos += 4; + return true; + } + + public bool U64(out ulong v) + { + v = 0; + if (!Has(8)) return false; + v = BinaryPrimitives.ReadUInt64LittleEndian(_s.Slice(_pos)); + _pos += 8; + return true; + } + + public bool F32(out float v) + { + v = 0; + if (!Has(4)) return false; + v = BitConverter.Int32BitsToSingle(BinaryPrimitives.ReadInt32LittleEndian(_s.Slice(_pos))); + _pos += 4; + return true; + } + + public bool F64(out double v) + { + v = 0; + if (!Has(8)) return false; + v = BitConverter.Int64BitsToDouble(BinaryPrimitives.ReadInt64LittleEndian(_s.Slice(_pos))); + _pos += 8; + return true; + } + + /// A u32 used as a flag: any non-zero value is true. + public bool Bool32(out bool v) + { + v = false; + if (!U32(out uint raw)) return false; + v = raw != 0; + return true; + } + + /// + /// AC's 16-bit-length string: u16 length, that many single-byte characters, then zero + /// padding so that 2 + length is a multiple of 4. The long form (length 0xFFFF followed + /// by a u32) isn't used by the messages parsed here and is refused. + /// + public bool String16L(out string v) + { + v = string.Empty; + if (!U16(out ushort len) || len == 0xFFFF || !Has(len)) return false; + v = len == 0 ? string.Empty : Encoding.Latin1.GetString(_s.Slice(_pos, len)); + _pos += len; + return Skip((4 - ((2 + len) & 3)) & 3); + } + + /// A packed list's header: u32 count, sanity-checked against the bytes left (each item at least bytes). + public bool ListCount(out int count, int minItemSize) + { + count = 0; + if (!U32(out uint n)) return false; + if (minItemSize < 1) minItemSize = 1; + if (n > (uint)(Remaining / minItemSize)) return false; + count = (int)n; + return true; + } + + /// A packed hash table's header: u16 count, u16 bucket count (ignored), sanity-checked like . + public bool TableCount(out int count, int minEntrySize) + { + count = 0; + if (!U16(out ushort n) || !U16(out _)) return false; + if (minEntrySize < 1) minEntrySize = 1; + if (n > Remaining / minEntrySize) return false; + count = n; + return true; + } + + /// A packed list of u32 (u32 count, then the values). + public bool U32List(out uint[] values) + { + values = Array.Empty(); + if (!ListCount(out int n, 4)) return false; + if (n == 0) return true; + var a = new uint[n]; + for (int i = 0; i < n; i++) + if (!U32(out a[i])) return false; + values = a; + return true; + } +} diff --git a/src/RynthCore.PluginSdk/Net/ServerMessage.cs b/src/RynthCore.PluginSdk/Net/ServerMessage.cs new file mode 100644 index 0000000..929970a --- /dev/null +++ b/src/RynthCore.PluginSdk/Net/ServerMessage.cs @@ -0,0 +1,104 @@ +// ============================================================================ +// RynthCore.PluginSdk - Net/ServerMessage.cs +// One reassembled server-to-client message, as RynthPluginOnServerMessage gets it. +// +// Plugin side (API v78+): +// 1. In Init (or Tick), tell the engine what you want: +// Host.SetServerMessageInterest( +// new uint[] { ServerOpcode.HearEmote, ServerOpcode.HearSoulEmote }, +// new uint[] { GameEventType.FellowshipFullUpdate, GameEventType.FriendsUpdate }); +// 2. Export the callback (NativeAOT plugin): +// [UnmanagedCallersOnly(EntryPoint = "RynthPluginOnServerMessage", +// CallConvs = new[] { typeof(CallConvCdecl) })] +// static unsafe void OnServerMessage(uint opcode, byte* data, int length) +// { +// var msg = ServerMessage.FromCallback(opcode, data, length); +// if (msg.IsGameEvent && msg.EventType == GameEventType.FellowshipFullUpdate +// && FellowshipFullUpdate.TryParse(msg.EventBody, out var f)) { ... } +// } +// `data` is the message after its u32 opcode and is valid only during the call; copy +// what you keep. Messages arrive on the plugin pump, in the order they finished +// arriving, possibly before the client itself has applied them. +// ============================================================================ + +using System; +using System.Buffers.Binary; + +namespace RynthCore.PluginSdk.Net; + +/// A server message: its opcode and the bytes after the opcode. For game events (0xF7B0) also the event header. +public readonly ref struct ServerMessage +{ + public const uint GameEventOpcode = 0xF7B0; + + public uint Opcode { get; } + + /// The bytes after the u32 opcode. + public ReadOnlySpan Body { get; } + + public ServerMessage(uint opcode, ReadOnlySpan body) + { + Opcode = opcode; + Body = body; + } + + /// Wraps RynthPluginOnServerMessage's arguments (no copy). + public static unsafe ServerMessage FromCallback(uint opcode, byte* data, int length) + => new(opcode, data != null && length > 0 ? new ReadOnlySpan(data, length) : ReadOnlySpan.Empty); + + /// From a whole message as it is on the wire (u32 opcode first). + public static bool TryFromWire(ReadOnlySpan message, out ServerMessage m) + { + if (message.Length < 4) + { + m = default; + return false; + } + m = new ServerMessage(BinaryPrimitives.ReadUInt32LittleEndian(message), message.Slice(4)); + return true; + } + + /// True for a game event (opcode 0xF7B0) with its 12-byte event header. + public bool IsGameEvent => Opcode == GameEventOpcode && Body.Length >= 12; + + /// Game event: the object it is for (the player). + public uint EventObjectId => IsGameEvent ? BinaryPrimitives.ReadUInt32LittleEndian(Body) : 0; + + /// Game event: the server's per-player game event sequence. + public uint EventSequence => IsGameEvent ? BinaryPrimitives.ReadUInt32LittleEndian(Body.Slice(4)) : 0; + + /// Game event: its type (see ); 0 for other messages. + public uint EventType => IsGameEvent ? BinaryPrimitives.ReadUInt32LittleEndian(Body.Slice(8)) : 0; + + /// Game event: the bytes after the event type. + public ReadOnlySpan EventBody => IsGameEvent ? Body.Slice(12) : ReadOnlySpan.Empty; +} + +/// Top-level server message opcodes the SDK parses (and a few landmarks). +public static class ServerOpcode +{ + public const uint HearEmote = 0x01E0; + public const uint HearSoulEmote = 0x01E2; + public const uint HearSpeech = 0x02BB; + public const uint HearRangedSpeech = 0x02BC; + public const uint GameEvent = 0xF7B0; + /// Pass in the opcode list to get every message. + public const uint All = 0xFFFFFFFF; +} + +/// Game event types (inside opcode 0xF7B0) the SDK parses. +public static class GameEventType +{ + public const uint PopUpString = 0x0004; + public const uint FriendsUpdate = 0x0021; + public const uint FellowshipQuit = 0x00A3; + public const uint FellowshipDismiss = 0x00A4; + public const uint ChannelBroadcast = 0x0147; + public const uint ConfirmationRequest = 0x0274; + public const uint AllegianceLoginNotification = 0x027A; + public const uint HearDirectSpeech = 0x02BD; + public const uint FellowshipFullUpdate = 0x02BE; + public const uint FellowshipDisband = 0x02BF; + public const uint FellowshipUpdateFellow = 0x02C0; + public const uint TransientString = 0x02EB; +} diff --git a/src/RynthCore.PluginSdk/RynthCore.PluginSdk.csproj b/src/RynthCore.PluginSdk/RynthCore.PluginSdk.csproj index 1732ea6..86a949b 100644 --- a/src/RynthCore.PluginSdk/RynthCore.PluginSdk.csproj +++ b/src/RynthCore.PluginSdk/RynthCore.PluginSdk.csproj @@ -18,4 +18,16 @@ RynthCore.PluginSdk + + + + + + + + + + diff --git a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs index 018a37e..f90550d 100644 --- a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs +++ b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs @@ -153,7 +153,16 @@ public struct RynthCoreApiNative public IntPtr GetServerInfoFn; // int GetServerInfo(byte* worldName, int capacity) -> flags (bit0 Aelrynth, bit1 staging, bit2 world name known) // v76: close an external container (corpse, chest) like the client's window close public IntPtr CloseContainerFn; // int CloseContainer(uint containerId) -> 1 sent or queued - // v77: outcome of the latest merge-stack request (cdecl thunk) + // v77: the client's screen (UIFlow mode) and which UI hooks (screen, cleanup, tooltip, drag, drop) are live + public IntPtr GetScreenModeFn; // int GetScreenMode(int* previousMode) -> mode, 0 unknown + public IntPtr GetUiHookFlagsFn; // uint GetUiHookFlags(void) -> RynthUiHookFlags + // v78: reassembled server messages (RynthPluginOnServerMessage export; see Net\ServerMessage.cs) + public IntPtr SetServerMessageInterestFn; // int SetServerMessageInterest(uint* opcodes, int n, uint* gameEvents, int m) -> 1 streaming, 2 stream off, 0 no export, -1 unknown caller, -3 bad args + // v79: spending experience like the character window's "+" (see TrainingTypes.cs) + public IntPtr GetTrainingInfoFn; // int GetTrainingInfo(TrainingInfoNative* info, TrainingEntryNative* entries, int max) -> entries there are + public IntPtr RaiseFn; // int Raise(uint kind, uint stype, uint ranks, long expectedXp, long* xpSent) -> RaiseResult + public IntPtr TrainSkillFn; // int TrainSkill(uint stype, int expectedCredits) -> RaiseResult + // v80: outcome of the latest merge-stack request (cdecl thunk); was v77 on QOL-items public IntPtr GetMergeStackResultFn; // int GetMergeStackResult(uint src, uint tgt, int* amount, int* ageMs) } diff --git a/src/RynthCore.PluginSdk/RynthCoreHost.cs b/src/RynthCore.PluginSdk/RynthCoreHost.cs index 3b24926..34b6fc4 100644 --- a/src/RynthCore.PluginSdk/RynthCoreHost.cs +++ b/src/RynthCore.PluginSdk/RynthCoreHost.cs @@ -6,7 +6,13 @@ namespace RynthCore.PluginSdk; public readonly unsafe struct RynthCoreHost { - public const uint CurrentApiVersion = 77; // v77: GetMergeStackResult + /// + /// The engine API this SDK's table () covers. It is the engine's + /// own constant, compiled in from src\RynthCore.Engine\Plugins\PluginContractVersion.cs, so the + /// two can't drift (this said 68 for eight versions); tools\PluginManifestTests checks the + /// SDK's table really reaches it. + /// + public const uint CurrentApiVersion = RynthCore.Engine.Plugins.PluginContractVersion.Current; /// /// The oldest engine API a plugin built on this SDK loads on by default @@ -138,9 +144,20 @@ public readonly unsafe struct RynthCoreHost public bool HasGetServerInfo => _api.Version >= 75 && _api.GetServerInfoFn != IntPtr.Zero; /// v76: (close a corpse or chest like the client's window close). public bool HasCloseContainer => _api.Version >= 76 && _api.CloseContainerFn != IntPtr.Zero; + /// v77: , and the UI callbacks + /// (OnScreenChanged, OnClientCleanup, OnTooltipShow/Hide, OnDragStart, OnItemDropped). + public bool HasUiHooks => _api.Version >= 77 && _api.GetScreenModeFn != IntPtr.Zero && _api.GetUiHookFlagsFn != IntPtr.Zero; + + /// v78: (reassembled server messages on RynthPluginOnServerMessage). + public bool HasServerMessages => _api.Version >= 78 && _api.SetServerMessageInterestFn != IntPtr.Zero; + + /// v79: , and + /// (spend unassigned XP and skill credits like the character window). + public bool HasTraining => _api.Version >= 79 && _api.GetTrainingInfoFn != IntPtr.Zero + && _api.RaiseFn != IntPtr.Zero && _api.TrainSkillFn != IntPtr.Zero; public bool HasGetPluginExportJson => _api.Version >= 66 && _api.GetPluginExportJsonFn != IntPtr.Zero; // Version-checked first: on an older engine the field lies past the end of its API table. - public bool HasGetMergeStackResult => _api.Version >= 77 && _api.GetMergeStackResultFn != IntPtr.Zero; + public bool HasGetMergeStackResult => _api.Version >= 80 && _api.GetMergeStackResultFn != IntPtr.Zero; public bool HasGetPluginInterface => _api.Version >= 68 && _api.GetPluginInterfaceFn != IntPtr.Zero; public bool HasGetLiveObjectIds => _api.Version >= 69 && _api.GetLiveObjectIdsFn != IntPtr.Zero; public bool HasGetLastUseDone => _api.Version >= 70 && _api.GetLastUseDoneFn != IntPtr.Zero; @@ -1720,6 +1737,110 @@ public readonly unsafe struct RynthCoreHost ((delegate* unmanaged[Cdecl])_api.CloseContainerFn)(containerId) != 0; } + /// + /// v77: the client's screen, the UIFlow mode (): the world, + /// character select, the intro... before the engine + /// has seen one, and on an engine before v77 (check ). + /// is the screen before it. Any thread. + /// + public int GetScreenMode(out int previousMode) + { + previousMode = 0; + if (!HasUiHooks) return 0; + int prev = 0; + int mode = ((delegate* unmanaged[Cdecl])_api.GetScreenModeFn)(&prev); + previousMode = prev; + return mode; + } + + /// + /// v77: which UI hooks are live on this client (), i.e. which of + /// the v77 callbacks can arrive. on an engine before v77. + /// Any thread. + /// + public RynthUiHookFlags GetUiHookFlags() + => HasUiHooks ? (RynthUiHookFlags)((delegate* unmanaged[Cdecl])_api.GetUiHookFlagsFn)() : RynthUiHookFlags.None; + + // ─── Spending experience (API v79) ───────────────────────────────────── + // See TrainingTypes.cs. The engine reads the player's numbers on AC's main thread every + // 2 s while a plugin keeps asking (TryGetTrainingInfo), and raises only against numbers + // at most info.StaleAfterMs old: a Stale result means "ask again in a moment". + + /// + /// v79: unassigned XP, credits and, in (may be null), one entry per + /// attribute, vital and skill with the XP for +1 and +10. = the + /// entries there are (at most entries.Length are written). False on an engine before v79 or + /// while there are no numbers yet (not in the world, or the first read is still coming). + /// Any thread. + /// + public bool TryGetTrainingInfo(out TrainingInfoNative info, TrainingEntryNative[]? entries, out int entryCount) + { + info = default; + entryCount = 0; + if (!HasTraining) return false; + TrainingInfoNative raw = default; + raw.Size = (uint)sizeof(TrainingInfoNative); + var fn = (delegate* unmanaged[Cdecl])_api.GetTrainingInfoFn; + int n; + if (entries is { Length: > 0 }) + fixed (TrainingEntryNative* p = entries) n = fn(&raw, p, entries.Length); + else + n = fn(&raw, null, 0); + info = raw; + entryCount = Math.Max(0, n); + return raw.Size >= 8 && (raw.Flags & TrainingInfoFlags.HaveNumbers) != 0 && n > 0; + } + + /// + /// v79: raise one attribute (1..6), vital (1 health, 3 stamina, 5 mana) or trained/specialized + /// skill by (1..100) with unassigned XP, like the character window's + /// "+". is the cost the user confirmed (the entry's CostOne / + /// CostTen); the engine refuses with when the cost now + /// differs (0 skips that check). = the XP sent. Any thread. + /// + public RaiseResult Raise(TrainingKind kind, uint stype, uint ranks, long expectedXp, out long xpSent) + { + xpSent = 0; + if (!HasTraining) return RaiseResult.EngineTooOld; + long sent = 0; + int r = ((delegate* unmanaged[Cdecl])_api.RaiseFn)((uint)kind, stype, ranks, expectedXp, &sent); + xpSent = sent; + return (RaiseResult)r; + } + + /// + /// v79: train an untrained skill with skill credits (exactly the entry's TrainCredits, which + /// the caller passes as ; 0 skips that check). Any thread. + /// + public RaiseResult TrainSkill(uint stype, int expectedCredits) + => HasTraining + ? (RaiseResult)((delegate* unmanaged[Cdecl])_api.TrainSkillFn)(stype, expectedCredits) + : RaiseResult.EngineTooOld; + + /// + /// v78: which reassembled server messages this plugin wants on its + /// RynthPluginOnServerMessage(uint opcode, byte* data, int length) export (Cdecl; + /// see for the export and / + /// for the ids the SDK parses). Replaces the previous set; + /// two empty lists turn it off. : top-level opcodes, 0xF7B0 for + /// every game event, for everything. + /// : single game event types. Call from Init, Tick or an event + /// handler (the engine identifies the plugin by the call). Returns 1 streaming, 2 accepted + /// but the engine's stream is switched off, 0 no export, -1 unknown caller, -3 bad + /// arguments, -4 engine predates v78. Check . + /// + public int SetServerMessageInterest(ReadOnlySpan opcodes, ReadOnlySpan gameEvents) + { + if (!HasServerMessages) + return -4; + fixed (uint* ops = opcodes) + fixed (uint* evs = gameEvents) + { + return ((delegate* unmanaged[Cdecl])_api.SetServerMessageInterestFn)( + ops, opcodes.Length, evs, gameEvents.Length); + } + } + /// /// v71: submits this plugin's complete set of script windows (display-list format 1, /// RynthSuite Docs/RYNTHLUA_WINDOWS_DESIGN.md §4.2). Call only from the plugin's own tick or diff --git a/src/RynthCore.PluginSdk/RynthPluginManifestAttribute.cs b/src/RynthCore.PluginSdk/RynthPluginManifestAttribute.cs new file mode 100644 index 0000000..5fbb62e --- /dev/null +++ b/src/RynthCore.PluginSdk/RynthPluginManifestAttribute.cs @@ -0,0 +1,18 @@ +using System; + +namespace RynthCore.PluginSdk; + +/// +/// The plugin's manifest minimum, as an assembly attribute: build\RynthCore.PluginSdk.targets adds +/// it from RynthPluginMinEngineApi alongside the embedded manifest. RynthPluginBase.MinimumApiVersion +/// defaults to it, so the plugin's own check (which also guards engines from before manifests) and +/// the engine's/launcher's manifest check use the same number. Works under NativeAOT. +/// +[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)] +public sealed class RynthPluginManifestAttribute : Attribute +{ + public RynthPluginManifestAttribute(uint minEngineApi) => MinEngineApi = minEngineApi; + + /// The manifest's minEngineApi. + public uint MinEngineApi { get; } +} diff --git a/src/RynthCore.PluginSdk/TrainingTypes.cs b/src/RynthCore.PluginSdk/TrainingTypes.cs new file mode 100644 index 0000000..ad6e493 --- /dev/null +++ b/src/RynthCore.PluginSdk/TrainingTypes.cs @@ -0,0 +1,158 @@ +using System; +using System.Runtime.InteropServices; + +namespace RynthCore.PluginSdk; + +// ─── Spending experience (engine API v79) ────────────────────────────────── +// What the retail character window's "+" does: raise an attribute, a vital or a +// trained skill with unassigned XP, or train an untrained skill with credits. +// RynthCoreHost.TryGetTrainingInfo reports the numbers and costs; Raise / TrainSkill +// send the client's own CM_Train game actions on AC's main thread. +// +// if (Host.HasTraining && Host.TryGetTrainingInfo(out var info, entries, out int n)) +// { +// var focus = Array.Find(entries, e => e.Kind == TrainingKind.Attribute && e.Stype == 5); +// if (focus.CostOne > 0 && focus.CostOne <= info.UnassignedXp) +// Host.Raise(TrainingKind.Attribute, 5, 1, focus.CostOne, out long sent); +// } +// +// Pass the cost the user saw as expectedXp: the engine works the XP out again from +// fresh numbers and refuses (CostChanged) when they differ, so a stale screen never +// spends a different amount. Spent XP can't be taken back. + +/// What a raise targets (the API's kind numbers). +public enum TrainingKind : uint +{ + /// Strength 1, Endurance 2, Quickness 3, Coordination 4, Focus 5, Self 6. + Attribute = 1, + /// A vital's maximum: 1 health, 3 stamina, 5 mana. + Vital = 2, + /// A skill by its id (trained or specialized to raise; untrained to train). + Skill = 3, +} + +/// The engine's answer to / . +public enum RaiseResult +{ + /// Sent, or queued for AC's main thread. The new numbers follow within a second or two. + Sent = 1, + /// The client's raise (or train) sender isn't bound on this client build. + Unavailable = 0, + NotInWorld = -1, + BadArguments = -2, + /// No numbers yet (the engine is reading them); try again in a second. + NotReady = -3, + /// The numbers were too old; a fresh read was asked for. Try again in a moment. + Stale = -4, + /// The cost isn't the one the caller passed: something changed. Refresh and confirm again. + CostChanged = -5, + /// Not enough unassigned XP (or skill credits). + NotEnough = -6, + /// At the top rank, an untrained skill (raise), an already trained skill (train), or no price. + NotRaisable = -7, + /// An earlier raise or train hasn't shown up in the numbers yet (up to 5 s). + Busy = -8, + /// The send failed or the engine's action queue was full. + SendFailed = -9, + /// The engine predates API v79 (SDK-side; the engine never returns it). + EngineTooOld = -100, +} + +/// v79 bits. +public static class TrainingInfoFlags +{ + public const uint InWorld = 1u << 0; + /// The attribute, vital and skill raise senders are bound. + public const uint RaiseBound = 1u << 1; + /// The train-with-credits sender is bound. + public const uint TrainBound = 1u << 2; + /// The player's numbers have been read (entries follow). + public const uint HaveNumbers = 1u << 3; + /// The portal SkillTable and XpTable are loaded. + public const uint HaveTables = 1u << 4; + /// A raise or train from the API hasn't landed yet. + public const uint Busy = 1u << 5; +} + +/// v79 bits. +public static class TrainingEntryFlags +{ + /// Can be raised with XP (attribute, vital, trained or specialized skill below the top). + public const uint Raisable = 1u << 0; + public const uint AtTop = 1u << 1; + /// Skills: usable untrained. + public const uint UsableUntrained = 1u << 2; + /// Skills: untrained and trainable with credits. + public const uint Trainable = 1u << 3; +} + +/// +/// v79 GetTrainingInfo header (Pack 4, 64 bytes; later versions only append). +/// Mirrors RynthCore.Engine/Plugins/PluginContract.cs TrainingInfoNative exactly. +/// +[StructLayout(LayoutKind.Sequential, Pack = 4)] +public unsafe struct TrainingInfoNative +{ + /// In: sizeof(TrainingInfoNative). Out: bytes the engine wrote. + public uint Size; + /// . + public uint Flags; + /// Changes whenever any number changes. + public uint SnapshotVersion; + /// Milliseconds since the numbers were read; 0xFFFFFFFF = never. + public uint AgeMs; + /// -1 when unknown. + public long UnassignedXp; + /// -1 when unknown. + public long TotalXp; + public int Level; + /// -1 when unknown. + public int SkillCredits; + public int EntryCount; + /// Raise refuses numbers older than this (). + public int StaleAfterMs; + public fixed uint Reserved[4]; + + public readonly bool InWorld => (Flags & TrainingInfoFlags.InWorld) != 0; + public readonly bool RaiseBound => (Flags & TrainingInfoFlags.RaiseBound) != 0; + public readonly bool TrainBound => (Flags & TrainingInfoFlags.TrainBound) != 0; + public readonly bool HaveNumbers => (Flags & TrainingInfoFlags.HaveNumbers) != 0; + public readonly bool Busy => (Flags & TrainingInfoFlags.Busy) != 0; +} + +/// +/// v79 GetTrainingInfo entry: one attribute, vital or skill (Pack 4, 64 bytes; later +/// versions only append). Mirrors the engine's TrainingEntryNative exactly. +/// +[StructLayout(LayoutKind.Sequential, Pack = 4)] +public struct TrainingEntryNative +{ + /// 1 attribute, 2 vital, 3 skill (). + public TrainingKind Kind; + /// Attribute 1..6, vital maximum 1 / 3 / 5, skill id. + public uint Stype; + /// Skills: 0 not in the table, 1 untrained, 2 trained, 3 specialized. 0 otherwise. + public uint Class; + public uint Ranks; + public uint XpSpent; + /// The innate (starting) level. + public uint Innate; + /// Without enchantments (a vital's maximum). + public int Base; + public int Buffed; + /// XP for one more rank; -1 at the top or not raisable. + public long CostOne; + /// XP for ten more ranks; -1 when fewer than ten are left or not raisable. + public long CostTen; + public int RanksLeft; + /// Ranks in a row the unassigned XP buys now. + public int Affordable; + /// Untrained skills: the credits to train it (0 = not trainable from the client). + public int TrainCredits; + /// . + public uint Flags; + + public readonly bool Raisable => (Flags & TrainingEntryFlags.Raisable) != 0; + public readonly bool AtTop => (Flags & TrainingEntryFlags.AtTop) != 0; + public readonly bool Trainable => (Flags & TrainingEntryFlags.Trainable) != 0; +} diff --git a/src/RynthCore.PluginSdk/UiTypes.cs b/src/RynthCore.PluginSdk/UiTypes.cs new file mode 100644 index 0000000..d35b6b2 --- /dev/null +++ b/src/RynthCore.PluginSdk/UiTypes.cs @@ -0,0 +1,59 @@ +using System; + +namespace RynthCore.PluginSdk; + +// ─── The client's screens and UI hooks (engine API v77) ───────────────────── +// RynthCoreHost.GetScreenMode / GetUiHookFlags, and the callbacks +// RynthPluginBase.OnScreenChanged, OnClientCleanup, OnTooltipShow, OnTooltipHide, +// OnDragStart and OnItemDropped. Check RynthCoreHost.HasUiHooks first: an engine +// before v77 has neither the functions nor the callbacks. + +/// The client's screen: its UIFlow mode (the client's own ids). +public static class RynthScreenMode +{ + /// Not known yet (or an engine before v77). + public const int Unknown = 0; + public const int Intro = 0x10000001; + public const int Disconnected = 0x10000002; + public const int DataPatch = 0x10000003; + public const int Credits = 0x10000005; + /// The world: the character is logged in. + public const int World = 0x10000008; + public const int Epilogue = 0x10000009; + public const int CharacterSelect = 0x1000000A; + public const int CharacterCreation = 0x1000000B; + + /// A short name for logs. + public static string Name(int mode) => mode switch + { + Unknown => "unknown", + Intro => "Intro", + Disconnected => "Disconnected", + DataPatch => "DataPatch", + Credits => "Credits", + World => "World", + Epilogue => "Epilogue", + CharacterSelect => "CharacterSelect", + CharacterCreation => "CharacterCreation", + _ => $"0x{mode:X8}", + }; +} + +/// Which UI hooks are live (RynthCoreHost.GetUiHookFlags), so which callbacks can arrive. +[Flags] +public enum RynthUiHookFlags : uint +{ + None = 0, + /// OnScreenChanged comes from the screen-change hook, as it happens. + ScreenHook = 1u << 0, + /// OnScreenChanged comes from the engine's mode poll instead (a tick late). + ScreenPoll = 1u << 1, + /// OnClientCleanup will come when the client shuts down. + ClientCleanup = 1u << 2, + TooltipShow = 1u << 3, + TooltipHide = 1u << 4, + DragStart = 1u << 5, + ItemDropped = 1u << 6, + /// The client's cleanup has started: no more ticks or events. + CleanupStarted = 1u << 7, +} diff --git a/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets b/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets new file mode 100644 index 0000000..b3336b7 --- /dev/null +++ b/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets @@ -0,0 +1,259 @@ + + + + + + 80 + <_RynthPluginManifestOn Condition="'$(RynthPluginMinEngineApi)' != '' and '$(RynthPluginManifest)' != 'false'">true + + + + $([System.Text.RegularExpressions.Regex]::Replace('$(AssemblyName)', '^RynthCore\.Plugin\.', '')) + $(Authors) + $(Company) + $(Description) + $(PackageProjectUrl) + $(PackageLicenseExpression) + <_RynthPluginManifestJson>$(IntermediateOutputPath)rynth-plugin.json + <_RynthPluginManifestEmbedded>$(IntermediateOutputPath)rynth-plugin.embedded + <_RynthPluginInfoSource>$(IntermediateOutputPath)RynthPluginInfo.g.cs + + + + + + <_Parameter1>$(RynthPluginMinEngineApi) + <_Parameter1_IsLiteral>true + + + + + + sdk) + { Log.LogError("RynthPluginMinEngineApi {0} is newer than this SDK's engine API ({1}): update RynthCore.PluginSdk.", min, sdk); return false; } + if (!string.IsNullOrWhiteSpace(MaxEngineApi) && (!uint.TryParse(MaxEngineApi.Trim(), out max) || max < min)) + { Log.LogError("RynthPluginMaxEngineApi '{0}' must be a whole number no lower than RynthPluginMinEngineApi ({1}).", MaxEngineApi, min); return false; } + if (Name.Trim().Length == 0) { Log.LogError("RynthPluginName is empty."); return false; } + + var sb = new StringBuilder(); + sb.Append("{\n"); + sb.Append(" \"schema\": 1,\n"); + sb.Append(" \"name\": ").Append(Q(Name.Trim())).Append(",\n"); + if (!string.IsNullOrWhiteSpace(Version)) sb.Append(" \"version\": ").Append(Q(Version.Trim())).Append(",\n"); + sb.Append(" \"minEngineApi\": ").Append(min).Append(",\n"); + if (max != 0) sb.Append(" \"maxEngineApi\": ").Append(max).Append(",\n"); + sb.Append(" \"dependencies\": ["); + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + bool first = true; + foreach (ITaskItem d in Dependencies ?? new ITaskItem[0]) + { + string dn = d.ItemSpec.Trim(); + if (dn.Length == 0 || !seen.Add(dn)) continue; + if (string.Equals(dn, Name.Trim(), StringComparison.OrdinalIgnoreCase)) + { Log.LogError("RynthPluginDependency '{0}' is the plugin itself.", dn); return false; } + string mv = (d.GetMetadata("MinVersion") ?? "").Trim(); + bool opt = string.Equals((d.GetMetadata("Optional") ?? "").Trim(), "true", StringComparison.OrdinalIgnoreCase); + sb.Append(first ? "\n" : ",\n"); + first = false; + sb.Append(" { \"name\": ").Append(Q(dn)); + if (mv.Length > 0) sb.Append(", \"minVersion\": ").Append(Q(mv)); + if (opt) sb.Append(", \"optional\": true"); + sb.Append(" }"); + } + sb.Append(first ? "]" : "\n ]"); + AppendOpt(sb, "author", Author); + AppendOpt(sb, "description", Description); + AppendOpt(sb, "homepage", Homepage); + AppendOpt(sb, "license", License); + sb.Append("\n}\n"); + WriteIfChanged(JsonPath, sb.ToString()); + + string ns = string.IsNullOrWhiteSpace(RootNamespace) ? "" : RootNamespace.Trim(); + var cs = new StringBuilder(); + cs.Append("// RynthCore.PluginSdk.targets, from the csproj's plugin manifest properties.\n"); + if (ns.Length > 0) cs.Append("namespace ").Append(ns).Append(";\n\n"); + cs.Append("/// This plugin's manifest (embedded in the DLL as RYNTH_PLUGIN_MANIFEST).\n"); + cs.Append("internal static class RynthPluginInfo\n{\n"); + cs.Append(" public const string Name = ").Append(Q(Name.Trim())).Append(";\n"); + cs.Append(" public const string Version = ").Append(Q((Version ?? "").Trim())).Append(";\n"); + cs.Append(" /// The oldest engine API this plugin runs on (its manifest's minEngineApi).\n"); + cs.Append(" public const uint MinEngineApi = ").Append(min).Append(";\n"); + cs.Append("}\n"); + WriteIfChanged(InfoSourcePath, cs.ToString()); + return !Log.HasLoggedErrors; + } + + private static void AppendOpt(StringBuilder sb, string key, string value) + { + if (string.IsNullOrWhiteSpace(value)) return; + sb.Append(",\n ").Append(Q(key)).Append(": ").Append(Q(value.Trim())); + } + + private static void WriteIfChanged(string path, string text) + { + if (File.Exists(path) && File.ReadAllText(path) == text) return; + Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))); + File.WriteAllText(path, text, new UTF8Encoding(false)); + } + + private static string Q(string s) + { + var sb = new StringBuilder("\""); + foreach (char c in s) + { + switch (c) + { + case '"': sb.Append("\\\""); break; + case '\\': sb.Append("\\\\"); break; + case '\n': sb.Append("\\n"); break; + case '\r': sb.Append("\\r"); break; + case '\t': sb.Append("\\t"); break; + default: + if (c < 0x20) sb.Append("\\u").Append(((int)c).ToString("x4")); + else sb.Append(c); + break; + } + } + return sb.Append('"').ToString(); + } +} +]]> + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/RynthCore.StatusAgent/AgentConfig.cs b/src/RynthCore.StatusAgent/AgentConfig.cs index d48e310..b0ed556 100644 --- a/src/RynthCore.StatusAgent/AgentConfig.cs +++ b/src/RynthCore.StatusAgent/AgentConfig.cs @@ -105,6 +105,14 @@ internal sealed class AgentConfig /// /maps returns an empty list and /map 404s — no other feature is affected. [JsonPropertyName("MapsDirectory")] public string MapsDirectory { get; set; } = Path.Combine(RynthInstallPaths.RynthAiDir, "Maps"); + /// cell.dat the landscape map (GET /worldmap) is drawn from, once, then cached as worldmap-v1.jpg in + /// . Absent = no world map (capabilities.worldMap false); nothing else changes. + [JsonPropertyName("CellDatPath")] public string CellDatPath { get; set; } = @"C:\Games\RynthCore\AcClient\client_cell_1.dat"; + + /// RynthNav's Atlas (NavData\locations.json), searched by GET /nav/search for the phone's Travel tab. + /// Absent = no travel (capabilities.travel false). The travel itself also needs EnableRemoteControl. + [JsonPropertyName("NavAtlasPath")] public string NavAtlasPath { get; set; } = @"C:\Games\RynthCore\NavData\locations.json"; + public static string DefaultConfigPath => Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RynthCore", "statusagent.json"); diff --git a/src/RynthCore.StatusAgent/Dat/DatDatabase.cs b/src/RynthCore.StatusAgent/Dat/DatDatabase.cs index c26c1e1..62e1b59 100644 --- a/src/RynthCore.StatusAgent/Dat/DatDatabase.cs +++ b/src/RynthCore.StatusAgent/Dat/DatDatabase.cs @@ -1,41 +1,89 @@ +// ============================================================================ +// RynthCore.StatusAgent - Dat/DatDatabase.cs +// Read-only access to Asheron's Call .dat archives (the agent reads item +// icons from client_portal.dat). Written for RynthCore (MIT) on 2026-10-05; +// the same design as RynthSuite's Shared/RynthCore.TerrainData/DatDatabase.cs. +// +// Written from the dat container format as it is publicly documented, with +// Chorizite's DatReaderWriter (MIT, notice below) used as the format reference: +// - file header at byte 0x140: magic, block size, file size, data set, +// subset, free head / tail / count, then the byte offset of the root +// B-tree node (all little-endian uint32); +// - storage is fixed-size blocks; a block's first uint32 is the byte offset +// of the next block of the same chain (0 ends the chain), the remaining +// BlockSize - 4 bytes are payload; +// - the directory is a B-tree whose nodes are stored as block chains: 62 +// uint32 child offsets, a uint32 entry count (at most 61), then the +// entries, 24 bytes each: flags/version, id, byte offset of the file's +// first block, size, timestamp, iteration. Entries are sorted by id, +// child i holds the ids between entry i-1 and entry i, and a node whose +// first child offset is 0 is a leaf. +// +// Lookups descend the tree from the root; interior nodes are kept once read +// and leaves go through a small LRU. Every call takes one lock, so a database +// can be shared between threads. +// +// Chorizite DatReaderWriter notice (format reference): +// Copyright 2024 ACClientLib +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: The above copyright notice and this permission +// notice shall be included in all copies or substantial portions of the +// Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. +// ============================================================================ + using System; +using System.Buffers.Binary; using System.Collections.Generic; using System.IO; namespace RynthCore2.TerrainData; /// -/// AC .dat file reader — ported directly from ACEmulator's DatLoader. -/// -/// Key format details (from ACE source): -/// - Header at file offset 0x140 -/// - Block chain: FIRST 4 bytes of each block = next block address (byte offset) -/// Remaining (BlockSize - 4) bytes = data -/// - B-tree node (DatDirectoryHeader): 62 branches, entry count, 61 entries × 24 bytes = 1716 total -/// - All pointers (BTree root, chain pointers, file offsets) are byte offsets +/// A read-only .dat archive. reads the header, checks the +/// root directory node and counts the files; files are then found by id by +/// searching the on-disk B-tree. Methods return null / empty when the database +/// isn't open or the file isn't there; nothing throws for a damaged file. /// public class DatDatabase : IDisposable { - private FileStream? _stream; - private readonly object _lock = new(); + private const long HeaderOffset = 0x140; + private const int HeaderBytes = 9 * 4; // magic .. root offset + private const int ChildSlots = 62; + private const int MaxEntriesPerNode = 61; + private const int EntryBytes = 24; + private const int CountOffset = ChildSlots * 4; // 248 + private const int EntriesOffset = CountOffset + 4; // 252 + private const int NodeBytes = EntriesOffset + MaxEntriesPerNode * EntryBytes; // 1716 + private const int DepthLimit = 16; // real trees are 4 deep; stops a looping child pointer + private const int LeafLruSize = 128; + private const int InteriorCap = 4096; - private const uint DAT_HEADER_OFFSET = 0x140; + private readonly object _gate = new(); + private FileStream? _file; + private long _length; + private readonly byte[] _nodeBuf = new byte[NodeBytes]; + private readonly Dictionary _interior = new(); + private readonly Dictionary> _leafMap = new(); + private readonly LinkedList<(uint At, Node Node)> _leafOrder = new(); - // B-tree geometry (from ACE DatDirectoryHeader.cs): - // 0x3E (62) branches, 0x3D (61) max entries, each entry = 6 × uint32 = 24 bytes - // ObjectSize = (4 * 62) + 4 + (24 * 61) = 248 + 4 + 1464 = 1716 - private const int BTREE_BRANCH_COUNT = 0x3E; // 62 - private const int BTREE_MAX_ENTRIES = 0x3D; // 61 - private const int BTREE_ENTRY_SIZE = 24; // 6 × uint32 - private const int BTREE_NODE_SIZE = (4 * BTREE_BRANCH_COUNT) + 4 + (BTREE_ENTRY_SIZE * BTREE_MAX_ENTRIES); // 1716 - - /// Dat header FileType field. + /// Header word at 0x140 (the dat magic). public uint FileType { get; private set; } /// Block size in bytes (typical: 1024). public uint BlockSize { get; private set; } - /// Total file size from header. + /// File size recorded in the header. public uint FileSize { get; private set; } - /// DataSet field from header. + /// The header's data set (database type) word. public uint DataSet { get; private set; } /// Byte offset of the root B-tree node. public uint BTreeRoot { get; private set; } @@ -44,326 +92,75 @@ public class DatDatabase : IDisposable public bool IsLoaded { get; private set; } /// Source file path passed to . public string? FilePath { get; private set; } - /// Number of files indexed from the B-tree. + /// Number of files in the dat (counted at ). public int RecordCount { get; private set; } - // All files indexed by ObjectId (populated during Open) - private readonly Dictionary _allFiles = new(); - /// Most-recent diagnostic messages (capped at 100). public List DiagLog { get; } = new(); + private sealed class Node + { + public uint[]? Children; // entry count + 1 offsets; null for a leaf + public DatBTreeEntry[] Entries = []; // ascending ObjectId + } + + // ---------------------------------------------------------------- open / close + /// - /// Opens the .dat file at for read-only random access and - /// indexes every entry in the B-tree. Returns false on any failure. + /// Opens the .dat file at for read-only random access. + /// Returns false on any failure. /// public bool Open(string path) { - try + lock (_gate) { - if (!File.Exists(path)) - { - Log($"File not found: {path}"); - return false; - } - + CloseLocked(); FilePath = path; - // Plugin init runs *before* acclient.exe opens its own DAT files, - // so our handle is the first one Windows sees on the file. Our - // share-mode dictates what AC's subsequent open can request — if - // we omit FileShare.Delete, AC's open (which needs delete-rename - // semantics for DDD/patcher) fails with a sharing violation and - // the AC client errors out with "cannot access the data files." - // - // FileShare.ReadWrite | FileShare.Delete = permit other openers - // to read, write, and delete-mark the file. RandomAccess hint + - // 4 KB buffer keeps the .dat B-tree reads efficient. - _stream = new FileStream( - path, - FileMode.Open, - FileAccess.Read, - FileShare.ReadWrite | FileShare.Delete, - bufferSize: 4096, - options: FileOptions.RandomAccess); - - Log($"File: {Path.GetFileName(path)}, Size: {_stream.Length:N0} bytes"); - - if (!ReadHeader()) + try { - Close(); + if (!File.Exists(path)) { Log($"Not found: {path}"); return false; } + + // AC keeps its own handles on its dats: share everything, + // including delete (the client's own open asks for it). + _file = new FileStream(path, FileMode.Open, FileAccess.Read, + FileShare.ReadWrite | FileShare.Delete, 4096, FileOptions.RandomAccess); + _length = _file.Length; + + Span h = stackalloc byte[HeaderBytes]; + if (!ReadAt(HeaderOffset, h)) { Log("Header is short"); CloseLocked(); return false; } + FileType = BinaryPrimitives.ReadUInt32LittleEndian(h); + BlockSize = BinaryPrimitives.ReadUInt32LittleEndian(h.Slice(4)); + FileSize = BinaryPrimitives.ReadUInt32LittleEndian(h.Slice(8)); + DataSet = BinaryPrimitives.ReadUInt32LittleEndian(h.Slice(12)); + BTreeRoot = BinaryPrimitives.ReadUInt32LittleEndian(h.Slice(32)); + + if (BlockSize <= 4 || BlockSize > 0x10000) { Log($"Bad block size {BlockSize}"); CloseLocked(); return false; } + if (BTreeRoot == 0 || BTreeRoot >= _length) { Log($"Bad root offset 0x{BTreeRoot:X8}"); CloseLocked(); return false; } + + IsLoaded = true; + if (GetNode(BTreeRoot) == null) + { + Log($"Root node at 0x{BTreeRoot:X8} doesn't parse"); + CloseLocked(); + return false; + } + RecordCount = CountUnder(BTreeRoot, 0); + Log($"Opened {Path.GetFileName(path)}: {RecordCount} files, block size {BlockSize}"); + return true; + } + catch (Exception ex) + { + Log($"Open failed: {ex.Message}"); + CloseLocked(); return false; } - - // Read the entire B-tree directory and index all files - ReadDirectory(BTreeRoot); - - RecordCount = _allFiles.Count; - IsLoaded = true; - - Log($"SUCCESS: {RecordCount} files indexed, BlockSize={BlockSize}, Root=0x{BTreeRoot:X8}"); - - return true; - } - catch (Exception ex) - { - Log($"Error: {ex.Message}"); - Close(); - return false; } } - /// - /// Reads the dat header from offset 0x140. - /// Format matches ACE's DatDatabaseHeader.Unpack(). - /// - private bool ReadHeader() - { - if (_stream == null) return false; - if (_stream.Length < DAT_HEADER_OFFSET + 64) - { - Log("File too small"); - return false; - } - - _stream.Seek(DAT_HEADER_OFFSET, SeekOrigin.Begin); - using (var reader = new BinaryReader(_stream, System.Text.Encoding.Default, true)) - { - FileType = reader.ReadUInt32(); - BlockSize = reader.ReadUInt32(); - FileSize = reader.ReadUInt32(); - DataSet = reader.ReadUInt32(); - _ = reader.ReadUInt32(); // dataSubset (unused) - - _ = reader.ReadUInt32(); // freeHead (unused) - _ = reader.ReadUInt32(); // freeTail (unused) - _ = reader.ReadUInt32(); // freeCount (unused) - BTreeRoot = reader.ReadUInt32(); - } - - Log($"FileType=0x{FileType:X8}, BlockSize={BlockSize}, DataSet={DataSet}, BTree=0x{BTreeRoot:X8}"); - - if (BlockSize == 0 || BTreeRoot == 0 || BTreeRoot >= (uint)_stream.Length) - { - Log("Invalid header values"); - return false; - } - - return true; - } - - /// - /// Reads data from the dat file following the block chain. - /// Matches ACE's DatReader.ReadDat() exactly. - /// - /// Block format: - /// [4 bytes: next block address] [BlockSize - 4 bytes: data] - /// - /// The FIRST 4 bytes of each block are the chain pointer (next block address). - /// If 0, this is the last block. - /// - private byte[]? ReadDatData(uint offset, int size) - { - if (_stream == null) return null; - if (offset + BlockSize > (uint)_stream.Length || size <= 0) - return null; - - byte[] buffer = new byte[size]; - - _stream.Seek(offset, SeekOrigin.Begin); - - // Read first 4 bytes = next block address - byte[] addrBuf = new byte[4]; - _ = _stream.Read(addrBuf, 0, 4); - uint nextAddress = BitConverter.ToUInt32(addrBuf, 0); - - int bufferOffset = 0; - int remaining = size; - - while (remaining > 0) - { - if (nextAddress == 0) - { - // Last block — read remaining data directly - int toRead = Math.Min(remaining, (int)(_stream.Length - _stream.Position)); - if (toRead <= 0) break; - _ = _stream.Read(buffer, bufferOffset, toRead); - remaining = 0; - } - else - { - // Read data portion of this block (BlockSize - 4 bytes) - int dataInBlock = (int)BlockSize - 4; - int toRead = Math.Min(dataInBlock, remaining); - _ = _stream.Read(buffer, bufferOffset, toRead); - bufferOffset += toRead; - remaining -= toRead; - - if (remaining > 0) - { - // Follow chain to next block - if (nextAddress >= (uint)_stream.Length) break; - _stream.Seek(nextAddress, SeekOrigin.Begin); - - // Read next block's chain pointer - _ = _stream.Read(addrBuf, 0, 4); - nextAddress = BitConverter.ToUInt32(addrBuf, 0); - } - } - } - - return buffer; - } - - /// - /// Recursively reads the B-tree directory and indexes all files. - /// Matches ACE's DatDirectory.Read() + AddFilesToList(). - /// - private void ReadDirectory(uint sectorOffset) - { - if (_stream == null) return; - if (sectorOffset == 0 || sectorOffset >= (uint)_stream.Length) - return; - - // Read the directory header (B-tree node) - byte[]? nodeData; - lock (_lock) - { - nodeData = ReadDatData(sectorOffset, BTREE_NODE_SIZE); - } - - if (nodeData == null || nodeData.Length < BTREE_NODE_SIZE) - return; - - // Parse branches (62 × uint32) - uint[] branches = new uint[BTREE_BRANCH_COUNT]; - for (int i = 0; i < BTREE_BRANCH_COUNT; i++) - branches[i] = BitConverter.ToUInt32(nodeData, i * 4); - - // Parse entry count - int countOffset = BTREE_BRANCH_COUNT * 4; // 248 - uint entryCount = BitConverter.ToUInt32(nodeData, countOffset); - - if (entryCount > BTREE_MAX_ENTRIES) - return; // Invalid node - - // Parse entries - int entriesOffset = countOffset + 4; // 252 - var entries = new DatBTreeEntry[entryCount]; - - for (int i = 0; i < entryCount; i++) - { - int eOff = entriesOffset + i * BTREE_ENTRY_SIZE; - entries[i] = new DatBTreeEntry - { - BitFlags = BitConverter.ToUInt32(nodeData, eOff), - ObjectId = BitConverter.ToUInt32(nodeData, eOff + 4), - FileOffset = BitConverter.ToUInt32(nodeData, eOff + 8), - FileSize = BitConverter.ToUInt32(nodeData, eOff + 12), - }; - } - - // Recurse into child directories (if branches[0] != 0, node has children) - if (branches[0] != 0) - { - for (int i = 0; i < entryCount + 1 && i < BTREE_BRANCH_COUNT; i++) - { - if (branches[i] != 0) - ReadDirectory(branches[i]); - } - } - - // Add entries to the file index - for (int i = 0; i < entryCount; i++) - { - if (entries[i].ObjectId != 0) - _allFiles[entries[i].ObjectId] = entries[i]; - } - } - - /// - /// Finds a file by ID. O(1) lookup from the pre-built index. - /// - public DatBTreeEntry? FindFile(uint fileId) - { - if (!IsLoaded) return null; - _allFiles.TryGetValue(fileId, out var entry); - return entry; - } - - /// - /// Reads file data for a given entry. - /// - public byte[]? ReadFileData(DatBTreeEntry? entry) - { - if (!IsLoaded || entry == null || entry.FileSize == 0 || _stream == null) - return null; - - lock (_lock) - { - return ReadDatData(entry.FileOffset, (int)entry.FileSize); - } - } - - /// Convenience: find by id then read. - public byte[]? GetFileData(uint fileId) - { - var entry = FindFile(fileId); - return entry != null ? ReadFileData(entry) : null; - } - - /// Returns (fileId, storedSize) for every indexed file whose id is in [lo, hi], sorted by size desc. - public List<(uint id, uint size)> EntriesInRange(uint lo, uint hi) - { - var list = new List<(uint, uint)>(); - if (!IsLoaded) return list; - foreach (var kv in _allFiles) - if (kv.Key >= lo && kv.Key <= hi) - list.Add((kv.Key, kv.Value.FileSize)); - list.Sort((a, b) => b.Item2.CompareTo(a.Item2)); - return list; - } - - /// - /// Returns all interior cell IDs (0x0100–0xFFFD) for a given landblock from the dat index. - /// This avoids the sequential scan gap cutoff that misses cells in large dungeons. - /// - public List GetLandblockCellIds(uint landblockKey) - { - var cellIds = new List(); - if (!IsLoaded) return cellIds; - - uint prefix = landblockKey << 16; - foreach (var id in _allFiles.Keys) - { - if ((id & 0xFFFF0000) != prefix) continue; - uint cell = id & 0xFFFF; - if (cell >= 0x0100 && cell <= 0xFFFD) - cellIds.Add(id); - } - return cellIds; - } - - /// - /// Returns sample file IDs from the index for diagnostics. - /// - public List GetSampleIds(int maxCount = 20) - { - var ids = new List(); - foreach (var kvp in _allFiles) - { - ids.Add(kvp.Key); - if (ids.Count >= maxCount) break; - } - return ids; - } - - /// Closes the underlying file handle and clears the index. + /// Closes the underlying file handle and drops the cached directory nodes. public void Close() { - _stream?.Dispose(); - _stream = null; - IsLoaded = false; - _allFiles.Clear(); + lock (_gate) CloseLocked(); } /// @@ -373,15 +170,266 @@ public class DatDatabase : IDisposable GC.SuppressFinalize(this); } + private void CloseLocked() + { + IsLoaded = false; + _file?.Dispose(); + _file = null; + _length = 0; + RecordCount = 0; + _interior.Clear(); + _leafMap.Clear(); + _leafOrder.Clear(); + } + + // ---------------------------------------------------------------- lookups + + /// The directory entry for , or null. + public DatBTreeEntry? FindFile(uint fileId) + { + lock (_gate) + { + if (!IsLoaded) return null; + uint at = BTreeRoot; + for (int depth = 0; depth < DepthLimit && at != 0; depth++) + { + Node? n = GetNode(at); + if (n == null) return null; + int i = LowerBound(n.Entries, fileId); + if (i < n.Entries.Length && n.Entries[i].ObjectId == fileId) return n.Entries[i]; + if (n.Children == null) return null; + at = n.Children[i]; + } + return null; + } + } + + /// The bytes of the file describes, or null. + public byte[]? ReadFileData(DatBTreeEntry? entry) + { + if (entry == null) return null; + lock (_gate) + { + if (!IsLoaded) return null; + if (entry.FileSize > _length) { Log($"0x{entry.ObjectId:X8}: size {entry.FileSize} exceeds the file"); return null; } + var data = new byte[entry.FileSize]; + if (ReadChain(entry.FileOffset, data) != data.Length) + { + Log($"0x{entry.ObjectId:X8}: block chain at 0x{entry.FileOffset:X8} is broken"); + return null; + } + return data; + } + } + + /// Convenience: find by id then read. + public byte[]? GetFileData(uint fileId) => ReadFileData(FindFile(fileId)); + + /// + /// (fileId, storedSize) for every file whose id is in [lo, hi], largest first + /// (ties by ascending id). + /// + public List<(uint id, uint size)> EntriesInRange(uint lo, uint hi) + { + var found = new List(); + lock (_gate) + { + if (IsLoaded && lo <= hi) Collect(BTreeRoot, lo, hi, found, 0); + } + var result = new List<(uint id, uint size)>(found.Count); + foreach (var e in found) result.Add((e.ObjectId, e.FileSize)); + result.Sort((a, b) => a.size != b.size ? b.size.CompareTo(a.size) : a.id.CompareTo(b.id)); + return result; + } + + /// + /// The interior (EnvCell) ids 0xXXYY0100-0xXXYYFFFD of landblock + /// (0xXXYY), ascending. + /// + public List GetLandblockCellIds(uint landblockKey) + { + var found = new List(); + lock (_gate) + { + if (IsLoaded) Collect(BTreeRoot, (landblockKey << 16) | 0x0100, (landblockKey << 16) | 0xFFFD, found, 0); + } + var ids = new List(found.Count); + foreach (var e in found) ids.Add(e.ObjectId); + return ids; + } + + /// The lowest file ids in the dat (up to ), for diagnostics. + public List GetSampleIds(int maxCount = 20) + { + var ids = new List(); + if (maxCount <= 0) return ids; + var found = new List(); + lock (_gate) + { + if (IsLoaded) Collect(BTreeRoot, 0, uint.MaxValue, found, 0, maxCount); + } + foreach (var e in found) ids.Add(e.ObjectId); + return ids; + } + + // In-order walk of the subtree at `at`, adding the entries with ids in + // [lo, hi] (stops once `into` holds `limit`). Caller holds _gate. + private void Collect(uint at, uint lo, uint hi, List into, int depth, int limit = int.MaxValue) + { + if (at == 0 || depth >= DepthLimit || into.Count >= limit) return; + Node? n = GetNode(at); + if (n == null) return; + var e = n.Entries; + for (int i = 0; i <= e.Length; i++) + { + if (n.Children != null) + { + // Child i holds the ids between e[i-1] and e[i]. + bool aboveLo = i == e.Length || e[i].ObjectId > lo; + bool belowHi = i == 0 || e[i - 1].ObjectId < hi; + if (aboveLo && belowHi) Collect(n.Children[i], lo, hi, into, depth + 1, limit); + } + if (i == e.Length || into.Count >= limit) break; + uint id = e[i].ObjectId; + if (id > hi) break; + if (id >= lo) into.Add(e[i]); + } + } + + // ---------------------------------------------------------------- nodes + + private static int LowerBound(DatBTreeEntry[] e, uint id) + { + int a = 0, b = e.Length; + while (a < b) + { + int m = (a + b) >> 1; + if (e[m].ObjectId < id) a = m + 1; else b = m; + } + return a; + } + + // Cached node: interior nodes kept (capped), leaves in a small LRU. Caller holds _gate. + private Node? GetNode(uint at) + { + if (_interior.TryGetValue(at, out Node? n)) return n; + if (_leafMap.TryGetValue(at, out var hit)) + { + _leafOrder.Remove(hit); + _leafOrder.AddFirst(hit); + return hit.Value.Node; + } + n = ParseNode(at); + if (n == null) return null; + if (n.Children != null) + { + if (_interior.Count < InteriorCap) _interior[at] = n; + } + else + { + if (_leafMap.Count >= LeafLruSize && _leafOrder.Last != null) + { + _leafMap.Remove(_leafOrder.Last.Value.At); + _leafOrder.RemoveLast(); + } + _leafMap[at] = _leafOrder.AddFirst((at, n)); + } + return n; + } + + private Node? ParseNode(uint at) + { + int got = ReadChain(at, _nodeBuf); + if (got < EntriesOffset) return null; + ReadOnlySpan s = _nodeBuf; + int count = BinaryPrimitives.ReadInt32LittleEndian(s.Slice(CountOffset)); + if (count < 0 || count > MaxEntriesPerNode || got < EntriesOffset + count * EntryBytes) return null; + + var entries = new DatBTreeEntry[count]; + for (int i = 0; i < count; i++) + { + var r = s.Slice(EntriesOffset + i * EntryBytes, EntryBytes); + entries[i] = new DatBTreeEntry + { + BitFlags = BinaryPrimitives.ReadUInt32LittleEndian(r), + ObjectId = BinaryPrimitives.ReadUInt32LittleEndian(r.Slice(4)), + FileOffset = BinaryPrimitives.ReadUInt32LittleEndian(r.Slice(8)), + FileSize = BinaryPrimitives.ReadUInt32LittleEndian(r.Slice(12)), + }; + } + uint[]? children = null; + if (BinaryPrimitives.ReadUInt32LittleEndian(s) != 0) + { + children = new uint[count + 1]; + for (int i = 0; i <= count; i++) children[i] = BinaryPrimitives.ReadUInt32LittleEndian(s.Slice(i * 4)); + } + return new Node { Children = children, Entries = entries }; + } + + // Entry counts under `at`, reading only each node's child table and count. Caller holds _gate. + private int CountUnder(uint at, int depth) + { + if (at == 0 || depth >= DepthLimit) return 0; + Span head = stackalloc byte[EntriesOffset]; + if (ReadChain(at, head) != EntriesOffset) return 0; + int count = BinaryPrimitives.ReadInt32LittleEndian(head.Slice(CountOffset)); + if (count < 0 || count > MaxEntriesPerNode) return 0; + int total = count; + if (BinaryPrimitives.ReadUInt32LittleEndian(head) != 0) + { + Span kids = stackalloc uint[count + 1]; + for (int i = 0; i <= count; i++) kids[i] = BinaryPrimitives.ReadUInt32LittleEndian(head.Slice(i * 4)); + for (int i = 0; i <= count; i++) total += CountUnder(kids[i], depth + 1); + } + return total; + } + + // ---------------------------------------------------------------- blocks + + // Copies the block chain starting at byte offset `first` into `dest` and + // returns how many bytes it filled: dest.Length, or less when the chain + // ends (a 0 link) first; -1 when a link points outside the file. + private int ReadChain(uint first, Span dest) + { + int payload = (int)BlockSize - 4; + long block = first; + int done = 0; + Span link = stackalloc byte[4]; + while (done < dest.Length) + { + if (block == 0) return done; + if (block + 4 > _length) return -1; + int take = Math.Min(payload, dest.Length - done); + if (!ReadAt(block, link) || !ReadAt(block + 4, dest.Slice(done, take))) return -1; + done += take; + block = BinaryPrimitives.ReadUInt32LittleEndian(link); + } + return done; + } + + private bool ReadAt(long offset, Span into) + { + if (_file == null || offset < 0 || offset + into.Length > _length) return false; + _file.Position = offset; + int got = 0; + while (got < into.Length) + { + int n = _file.Read(into.Slice(got)); + if (n <= 0) return false; + got += n; + } + return true; + } + private void Log(string msg) { - string line = $"[DatDB] {msg}"; + string line = "[DatDB] " + msg; System.Diagnostics.Debug.WriteLine(line); if (DiagLog.Count < 100) DiagLog.Add(line); } } -/// Indexed B-tree entry for one file inside a .dat archive. +/// One directory entry of a .dat archive. public class DatBTreeEntry { /// Raw flag bits from the B-tree. diff --git a/src/RynthCore.StatusAgent/Dat/DxtUtil.cs b/src/RynthCore.StatusAgent/Dat/DxtUtil.cs index fbb97eb..c5b1f87 100644 --- a/src/RynthCore.StatusAgent/Dat/DxtUtil.cs +++ b/src/RynthCore.StatusAgent/Dat/DxtUtil.cs @@ -1,442 +1,172 @@ -// #region License -// /* -// Microsoft Public License (Ms-PL) -// MonoGame - Copyright © 2009 The MonoGame Team -// -// All rights reserved. -// -// This license governs use of the accompanying software. If you use the software, you accept this license. If you do not -// accept the license, do not use the software. -// -// 1. Definitions -// The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under -// U.S. copyright law. -// -// A "contribution" is the original software, or any additions or changes to the software. -// A "contributor" is any person that distributes its contribution under this license. -// "Licensed patents" are a contributor's patent claims that read directly on its contribution. -// -// 2. Grant of Rights -// (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, -// each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create. -// (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, -// each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software. -// -// 3. Conditions and Limitations -// (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks. -// (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, -// your patent license from such contributor to the software ends automatically. -// (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution -// notices that are present in the software. -// (D) If you distribute any portion of the software in source code form, you may do so only under this license by including -// a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object -// code form, you may only do so under a license that complies with this license. -// (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees -// or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent -// permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular -// purpose and non-infringement. -// */ -// #endregion License +// ============================================================================ +// RynthCore.StatusAgent - Dat/DxtUtil.cs +// DXT1 / DXT3 / DXT5 (BC1 / BC2 / BC3) block decompression to RGBA bytes. +// Written for RynthCore (MIT) on 2026-10-05 from the public S3TC / DirectX +// block-compression format description: // +// Images are stored as 4 x 4 pixel blocks, left to right, top to bottom. +// Colour block (8 bytes, the whole of a DXT1 block and the second half of +// a DXT3/DXT5 block): two RGB565 end-point colours c0, c1 (uint16 each), +// then 16 two-bit indices, one per pixel, row by row, low bits first. +// DXT1, c0 > c1: index 2 = (2*c0 + c1) / 3, index 3 = (c0 + 2*c1) / 3 +// DXT1, c0 <= c1: index 2 = (c0 + c1) / 2, index 3 = transparent black +// DXT3 / DXT5 always use the four-colour form. +// DXT3 alpha (first 8 bytes): 16 explicit four-bit alphas, low nibble first. +// DXT5 alpha (first 8 bytes): end points a0, a1 (one byte each), then 16 +// three-bit indices (48 bits, little-endian, low bits first): +// a0 > a1: indices 2..7 = 6 interpolated values between a0 and a1 +// a0 <= a1: indices 2..5 = 4 interpolated values, 6 = 0, 7 = 255 +// +// Used by the agent's IconDecoder and, linked, by the engine's +// UI/ScriptWindows/AcIconDecoder.cs (and RynthSuite's ScriptWindows tests). +// ============================================================================ -namespace ACE.DatLoader +using System; +using System.IO; + +namespace RynthCore.Imaging { - using System.IO; - + /// DXT1/3/5 decompression; output is width * height * 4 bytes, R, G, B, A. public static class DxtUtil { - internal static byte[] DecompressDxt1(byte[] imageData, int width, int height) + internal static byte[] DecompressDxt1(byte[] imageData, int width, int height) => + Decompress(imageData, width, height, BlockKind.Dxt1); + + internal static byte[] DecompressDxt1(Stream imageStream, int width, int height) => + DecompressDxt1(ReadAll(imageStream), width, height); + + internal static byte[] DecompressDxt3(byte[] imageData, int width, int height) => + Decompress(imageData, width, height, BlockKind.Dxt3); + + internal static byte[] DecompressDxt3(Stream imageStream, int width, int height) => + DecompressDxt3(ReadAll(imageStream), width, height); + + internal static byte[] DecompressDxt5(byte[] imageData, int width, int height) => + Decompress(imageData, width, height, BlockKind.Dxt5); + + internal static byte[] DecompressDxt5(Stream imageStream, int width, int height) => + DecompressDxt5(ReadAll(imageStream), width, height); + + private enum BlockKind { Dxt1, Dxt3, Dxt5 } + + private static byte[] ReadAll(Stream s) { - using (MemoryStream imageStream = new MemoryStream(imageData)) - return DecompressDxt1(imageStream, width, height); + using var ms = new MemoryStream(); + s.CopyTo(ms); + return ms.ToArray(); } - internal static byte[] DecompressDxt1(Stream imageStream, int width, int height) + private static byte[] Decompress(byte[] src, int width, int height, BlockKind kind) { - byte[] imageData = new byte[width * height * 4]; + if (width <= 0 || height <= 0) return Array.Empty(); + var rgba = new byte[width * height * 4]; + int blockBytes = kind == BlockKind.Dxt1 ? 8 : 16; + int blocksX = (width + 3) / 4, blocksY = (height + 3) / 4; - using (BinaryReader imageReader = new BinaryReader(imageStream)) + Span palette = stackalloc byte[16]; // 4 colours x RGBA + Span alpha = stackalloc byte[16]; // per pixel (DXT3/5) + Span alphaTable = stackalloc byte[8]; // DXT5 end points + interpolated + int at = 0; + for (int by = 0; by < blocksY; by++) { - int blockCountX = (width + 3) / 4; - int blockCountY = (height + 3) / 4; - - for (int y = 0; y < blockCountY; y++) + for (int bx = 0; bx < blocksX; bx++, at += blockBytes) { - for (int x = 0; x < blockCountX; x++) + if (at + blockBytes > src.Length) return rgba; // short data: the rest stays clear + int colourAt = at; + bool hasAlphaBlock = kind != BlockKind.Dxt1; + if (kind == BlockKind.Dxt3) { - DecompressDxt1Block(imageReader, x, y, blockCountX, width, height, imageData); - } - } - } - - return imageData; - } - - private static void DecompressDxt1Block(BinaryReader imageReader, int x, int y, int blockCountX, int width, int height, byte[] imageData) - { - ushort c0 = imageReader.ReadUInt16(); - ushort c1 = imageReader.ReadUInt16(); - - byte r0, g0, b0; - byte r1, g1, b1; - ConvertRgb565ToRgb888(c0, out r0, out g0, out b0); - ConvertRgb565ToRgb888(c1, out r1, out g1, out b1); - - uint lookupTable = imageReader.ReadUInt32(); - - for (int blockY = 0; blockY < 4; blockY++) - { - for (int blockX = 0; blockX < 4; blockX++) - { - byte r = 0, g = 0, b = 0, a = 255; - uint index = (lookupTable >> 2 * (4 * blockY + blockX)) & 0x03; - - if (c0 > c1) - { - switch (index) + for (int i = 0; i < 16; i++) { - case 0: - r = r0; - g = g0; - b = b0; - break; - case 1: - r = r1; - g = g1; - b = b1; - break; - case 2: - r = (byte)((2 * r0 + r1) / 3); - g = (byte)((2 * g0 + g1) / 3); - b = (byte)((2 * b0 + b1) / 3); - break; - case 3: - r = (byte)((r0 + 2 * r1) / 3); - g = (byte)((g0 + 2 * g1) / 3); - b = (byte)((b0 + 2 * b1) / 3); - break; + int nibble = (src[at + (i >> 1)] >> ((i & 1) * 4)) & 0xF; + alpha[i] = (byte)(nibble * 17); } + colourAt += 8; + } + else if (kind == BlockKind.Dxt5) + { + byte a0 = src[at], a1 = src[at + 1]; + alphaTable[0] = a0; + alphaTable[1] = a1; + if (a0 > a1) + { + for (int i = 1; i <= 6; i++) alphaTable[i + 1] = (byte)(((7 - i) * a0 + i * a1) / 7); + } + else + { + for (int i = 1; i <= 4; i++) alphaTable[i + 1] = (byte)(((5 - i) * a0 + i * a1) / 5); + alphaTable[6] = 0; + alphaTable[7] = 255; + } + ulong bits = 0; + for (int i = 0; i < 6; i++) bits |= (ulong)src[at + 2 + i] << (8 * i); + for (int i = 0; i < 16; i++) alpha[i] = alphaTable[(int)((bits >> (3 * i)) & 7)]; + colourAt += 8; + } + + ushort c0 = (ushort)(src[colourAt] | (src[colourAt + 1] << 8)); + ushort c1 = (ushort)(src[colourAt + 2] | (src[colourAt + 3] << 8)); + Expand565(c0, palette.Slice(0, 4)); + Expand565(c1, palette.Slice(4, 4)); + if (kind != BlockKind.Dxt1 || c0 > c1) + { + for (int ch = 0; ch < 3; ch++) + { + palette[8 + ch] = (byte)((2 * palette[ch] + palette[4 + ch]) / 3); + palette[12 + ch] = (byte)((palette[ch] + 2 * palette[4 + ch]) / 3); + } + palette[11] = 255; + palette[15] = 255; } else { - switch (index) + for (int ch = 0; ch < 3; ch++) { - case 0: - r = r0; - g = g0; - b = b0; - break; - case 1: - r = r1; - g = g1; - b = b1; - break; - case 2: - r = (byte)((r0 + r1) / 2); - g = (byte)((g0 + g1) / 2); - b = (byte)((b0 + b1) / 2); - break; - case 3: - r = 0; - g = 0; - b = 0; - a = 0; - break; + palette[8 + ch] = (byte)((palette[ch] + palette[4 + ch]) / 2); + palette[12 + ch] = 0; + } + palette[11] = 255; + palette[15] = 0; + } + + uint indices = (uint)(src[colourAt + 4] | (src[colourAt + 5] << 8) | (src[colourAt + 6] << 16) | (src[colourAt + 7] << 24)); + for (int py = 0; py < 4; py++) + { + int y = by * 4 + py; + if (y >= height) break; + for (int px = 0; px < 4; px++) + { + int x = bx * 4 + px; + if (x >= width) continue; + int p = py * 4 + px; + int idx = (int)((indices >> (2 * p)) & 3); + int o = (y * width + x) * 4; + rgba[o] = palette[idx * 4]; + rgba[o + 1] = palette[idx * 4 + 1]; + rgba[o + 2] = palette[idx * 4 + 2]; + rgba[o + 3] = hasAlphaBlock ? alpha[p] : palette[idx * 4 + 3]; } } - - int px = (x << 2) + blockX; - int py = (y << 2) + blockY; - if ((px < width) && (py < height)) - { - int offset = ((py * width) + px) << 2; - imageData[offset] = r; - imageData[offset + 1] = g; - imageData[offset + 2] = b; - imageData[offset + 3] = a; - } } } + return rgba; } - internal static byte[] DecompressDxt3(byte[] imageData, int width, int height) + // RGB565 to 8-bit channels: v * 255 / max, rounded with the (t + t / 2^n) / 2^n + // approximation (t = v * 255 + 2^(n-1)), so the output matches, bit for bit, + // the decoder this file replaced. + private static void Expand565(ushort c, Span rgba) { - using (MemoryStream imageStream = new MemoryStream(imageData)) - return DecompressDxt3(imageStream, width, height); + rgba[0] = Scale((c >> 11) & 0x1F, 5); + rgba[1] = Scale((c >> 5) & 0x3F, 6); + rgba[2] = Scale(c & 0x1F, 5); + rgba[3] = 255; } - internal static byte[] DecompressDxt3(Stream imageStream, int width, int height) + private static byte Scale(int v, int bits) { - byte[] imageData = new byte[width * height * 4]; - - using (BinaryReader imageReader = new BinaryReader(imageStream)) - { - int blockCountX = (width + 3) / 4; - int blockCountY = (height + 3) / 4; - - for (int y = 0; y < blockCountY; y++) - { - for (int x = 0; x < blockCountX; x++) - { - DecompressDxt3Block(imageReader, x, y, blockCountX, width, height, imageData); - } - } - } - - return imageData; - } - - private static void DecompressDxt3Block(BinaryReader imageReader, int x, int y, int blockCountX, int width, int height, byte[] imageData) - { - byte a0 = imageReader.ReadByte(); - byte a1 = imageReader.ReadByte(); - byte a2 = imageReader.ReadByte(); - byte a3 = imageReader.ReadByte(); - byte a4 = imageReader.ReadByte(); - byte a5 = imageReader.ReadByte(); - byte a6 = imageReader.ReadByte(); - byte a7 = imageReader.ReadByte(); - - ushort c0 = imageReader.ReadUInt16(); - ushort c1 = imageReader.ReadUInt16(); - - byte r0, g0, b0; - byte r1, g1, b1; - ConvertRgb565ToRgb888(c0, out r0, out g0, out b0); - ConvertRgb565ToRgb888(c1, out r1, out g1, out b1); - - uint lookupTable = imageReader.ReadUInt32(); - - int alphaIndex = 0; - for (int blockY = 0; blockY < 4; blockY++) - { - for (int blockX = 0; blockX < 4; blockX++) - { - byte r = 0, g = 0, b = 0, a = 0; - - uint index = (lookupTable >> 2 * (4 * blockY + blockX)) & 0x03; - - switch (alphaIndex) - { - case 0: - a = (byte)((a0 & 0x0F) | ((a0 & 0x0F) << 4)); - break; - case 1: - a = (byte)((a0 & 0xF0) | ((a0 & 0xF0) >> 4)); - break; - case 2: - a = (byte)((a1 & 0x0F) | ((a1 & 0x0F) << 4)); - break; - case 3: - a = (byte)((a1 & 0xF0) | ((a1 & 0xF0) >> 4)); - break; - case 4: - a = (byte)((a2 & 0x0F) | ((a2 & 0x0F) << 4)); - break; - case 5: - a = (byte)((a2 & 0xF0) | ((a2 & 0xF0) >> 4)); - break; - case 6: - a = (byte)((a3 & 0x0F) | ((a3 & 0x0F) << 4)); - break; - case 7: - a = (byte)((a3 & 0xF0) | ((a3 & 0xF0) >> 4)); - break; - case 8: - a = (byte)((a4 & 0x0F) | ((a4 & 0x0F) << 4)); - break; - case 9: - a = (byte)((a4 & 0xF0) | ((a4 & 0xF0) >> 4)); - break; - case 10: - a = (byte)((a5 & 0x0F) | ((a5 & 0x0F) << 4)); - break; - case 11: - a = (byte)((a5 & 0xF0) | ((a5 & 0xF0) >> 4)); - break; - case 12: - a = (byte)((a6 & 0x0F) | ((a6 & 0x0F) << 4)); - break; - case 13: - a = (byte)((a6 & 0xF0) | ((a6 & 0xF0) >> 4)); - break; - case 14: - a = (byte)((a7 & 0x0F) | ((a7 & 0x0F) << 4)); - break; - case 15: - a = (byte)((a7 & 0xF0) | ((a7 & 0xF0) >> 4)); - break; - } - ++alphaIndex; - - switch (index) - { - case 0: - r = r0; - g = g0; - b = b0; - break; - case 1: - r = r1; - g = g1; - b = b1; - break; - case 2: - r = (byte)((2 * r0 + r1) / 3); - g = (byte)((2 * g0 + g1) / 3); - b = (byte)((2 * b0 + b1) / 3); - break; - case 3: - r = (byte)((r0 + 2 * r1) / 3); - g = (byte)((g0 + 2 * g1) / 3); - b = (byte)((b0 + 2 * b1) / 3); - break; - } - - int px = (x << 2) + blockX; - int py = (y << 2) + blockY; - if ((px < width) && (py < height)) - { - int offset = ((py * width) + px) << 2; - imageData[offset] = r; - imageData[offset + 1] = g; - imageData[offset + 2] = b; - imageData[offset + 3] = a; - } - } - } - } - - internal static byte[] DecompressDxt5(byte[] imageData, int width, int height) - { - using (MemoryStream imageStream = new MemoryStream(imageData)) - return DecompressDxt5(imageStream, width, height); - } - - internal static byte[] DecompressDxt5(Stream imageStream, int width, int height) - { - byte[] imageData = new byte[width * height * 4]; - - using (BinaryReader imageReader = new BinaryReader(imageStream)) - { - int blockCountX = (width + 3) / 4; - int blockCountY = (height + 3) / 4; - - for (int y = 0; y < blockCountY; y++) - { - for (int x = 0; x < blockCountX; x++) - { - DecompressDxt5Block(imageReader, x, y, blockCountX, width, height, imageData); - } - } - } - - return imageData; - } - - private static void DecompressDxt5Block(BinaryReader imageReader, int x, int y, int blockCountX, int width, int height, byte[] imageData) - { - byte alpha0 = imageReader.ReadByte(); - byte alpha1 = imageReader.ReadByte(); - - ulong alphaMask = (ulong)imageReader.ReadByte(); - alphaMask += (ulong)imageReader.ReadByte() << 8; - alphaMask += (ulong)imageReader.ReadByte() << 16; - alphaMask += (ulong)imageReader.ReadByte() << 24; - alphaMask += (ulong)imageReader.ReadByte() << 32; - alphaMask += (ulong)imageReader.ReadByte() << 40; - - ushort c0 = imageReader.ReadUInt16(); - ushort c1 = imageReader.ReadUInt16(); - - byte r0, g0, b0; - byte r1, g1, b1; - ConvertRgb565ToRgb888(c0, out r0, out g0, out b0); - ConvertRgb565ToRgb888(c1, out r1, out g1, out b1); - - uint lookupTable = imageReader.ReadUInt32(); - - for (int blockY = 0; blockY < 4; blockY++) - { - for (int blockX = 0; blockX < 4; blockX++) - { - byte r = 0, g = 0, b = 0, a = 255; - uint index = (lookupTable >> 2 * (4 * blockY + blockX)) & 0x03; - - uint alphaIndex = (uint)((alphaMask >> 3 * (4 * blockY + blockX)) & 0x07); - if (alphaIndex == 0) - { - a = alpha0; - } - else if (alphaIndex == 1) - { - a = alpha1; - } - else if (alpha0 > alpha1) - { - a = (byte)(((8 - alphaIndex) * alpha0 + (alphaIndex - 1) * alpha1) / 7); - } - else if (alphaIndex == 6) - { - a = 0; - } - else if (alphaIndex == 7) - { - a = 0xff; - } - else - { - a = (byte)(((6 - alphaIndex) * alpha0 + (alphaIndex - 1) * alpha1) / 5); - } - - switch (index) - { - case 0: - r = r0; - g = g0; - b = b0; - break; - case 1: - r = r1; - g = g1; - b = b1; - break; - case 2: - r = (byte)((2 * r0 + r1) / 3); - g = (byte)((2 * g0 + g1) / 3); - b = (byte)((2 * b0 + b1) / 3); - break; - case 3: - r = (byte)((r0 + 2 * r1) / 3); - g = (byte)((g0 + 2 * g1) / 3); - b = (byte)((b0 + 2 * b1) / 3); - break; - } - - int px = (x << 2) + blockX; - int py = (y << 2) + blockY; - if ((px < width) && (py < height)) - { - int offset = ((py * width) + px) << 2; - imageData[offset] = r; - imageData[offset + 1] = g; - imageData[offset + 2] = b; - imageData[offset + 3] = a; - } - } - } - } - - private static void ConvertRgb565ToRgb888(ushort color, out byte r, out byte g, out byte b) - { - int temp; - - temp = (color >> 11) * 255 + 16; - r = (byte)((temp / 32 + temp) / 32); - temp = ((color & 0x07E0) >> 5) * 255 + 32; - g = (byte)((temp / 64 + temp) / 64); - temp = (color & 0x001F) * 255 + 16; - b = (byte)((temp / 32 + temp) / 32); + int t = v * 255 + (1 << (bits - 1)); + return (byte)(((t >> bits) + t) >> bits); } } } diff --git a/src/RynthCore.StatusAgent/Dat/IconDecoder.cs b/src/RynthCore.StatusAgent/Dat/IconDecoder.cs index 0b7577c..0822a41 100644 --- a/src/RynthCore.StatusAgent/Dat/IconDecoder.cs +++ b/src/RynthCore.StatusAgent/Dat/IconDecoder.cs @@ -1,14 +1,26 @@ -using ACE.DatLoader; +// ============================================================================ +// RynthCore.StatusAgent - Dat/IconDecoder.cs +// An item icon (a 0x06 Texture in client_portal.dat) as RGBA pixels, for the +// phone remote. Written for RynthCore (MIT) on 2026-10-05. +// +// Written from the Texture file layout as Chorizite's DatReaderWriter (MIT, +// see the notice in Dat/DatDatabase.cs) describes it (RenderSurface and +// Palette) and the Direct3D pixel-format definitions: +// Texture 0x06: id u32, data category u32, width i32, height i32, +// format u32, length i32, data[length], and for the palette +// formats (P8, INDEX16) the default palette id u32. +// Palette 0x04: id u32, colour count i32, colours (u32 A8R8G8B8 each). +// Formats in the retail portal dat: A8R8G8B8, R8G8B8, R5G6B5, A4R4G4B4, A8, +// P8, INDEX16, the landscape R8G8B8 / alpha customs and DXT1/3/5 (DxtUtil.cs). +// Raw JPEG textures are not decoded. +// ============================================================================ + +using RynthCore.Imaging; using RynthCore2.TerrainData; namespace RynthCore.StatusAgent; -/// -/// Decodes an AC item ICON to RGBA pixels. An item's icon DID (PWD _iconID, range 0x06xxxxxx) points -/// straight at a 0x06 Texture in portal.dat, so this is the Texture path only — trimmed from -/// AcClientReborn's AcTextureDecoder (no Surface/SurfaceTexture/clothing). Format byte-layout + the -/// format constants are ported verbatim from ACEmulator's DatLoader. -/// +/// Decodes an AC item icon (a 0x06 Texture in portal.dat) to RGBA pixels. internal sealed class IconDecoder { private readonly DatDatabase _portal; @@ -22,94 +34,113 @@ internal sealed class IconDecoder public byte[] Pixels = System.Array.Empty(); } - // Palette (0x04): Id(u32), Colors(List: i32 count + u32[] ARGB). - private uint[]? LoadPalette(uint paletteId) - { - byte[]? data = _portal.GetFileData(paletteId); - if (data == null || data.Length < 8) return null; - using var ms = new MemoryStream(data); - using var r = new BinaryReader(ms); - r.ReadUInt32(); - int n = r.ReadInt32(); - if (n <= 0 || n > 100000) return null; - var pal = new uint[n]; - for (int i = 0; i < n; i++) - { - if (ms.Position + 4 > ms.Length) { System.Array.Resize(ref pal, i); break; } - pal[i] = r.ReadUInt32(); - } - return pal; - } + private const uint A8R8G8B8 = 0x15, R8G8B8 = 0x14, R5G6B5 = 0x17, A4R4G4B4 = 0x1A, A8 = 0x1C, + P8 = 0x29, Index16 = 0x65, LscapeR8G8B8 = 0xF3, LscapeAlpha = 0xF4, + Dxt1 = 0x31545844, Dxt3 = 0x33545844, Dxt5 = 0x35545844; - // Texture (0x06): Id(u32),Unknown(i32),Width(i32),Height(i32),Format(u32),Length(i32),Source[Length], - // if INDEX16/P8: DefaultPaletteId(u32). + /// The texture as RGBA, or null (missing, unsupported or damaged). public Rgba? Decode(uint textureId) { - byte[]? data = _portal.GetFileData(textureId); - if (data == null || data.Length < 24) return null; - using var ms = new MemoryStream(data); - using var r = new BinaryReader(ms); - r.ReadUInt32(); r.ReadInt32(); - int w = r.ReadInt32(), h = r.ReadInt32(); - uint fmt = r.ReadUInt32(); - int len = r.ReadInt32(); - if (w <= 0 || h <= 0 || w > 4096 || h > 4096 || len < 0 || ms.Position + len > ms.Length) return null; - byte[] src = r.ReadBytes(len); - uint defPal = 0; - if (fmt == 101 /*INDEX16*/ || fmt == 41 /*P8*/) { if (ms.Position + 4 <= ms.Length) defPal = r.ReadUInt32(); } - - var rgba = new byte[w * h * 4]; - void Px(int i, int rr, int gg, int bb, int aa) { int o = i * 4; rgba[o] = (byte)rr; rgba[o + 1] = (byte)gg; rgba[o + 2] = (byte)bb; rgba[o + 3] = (byte)aa; } - - switch (fmt) + try { - case 827611204: return Wrap(DxtUtil.DecompressDxt1(src, w, h), w, h); // DXT1 - case 861165636: return Wrap(DxtUtil.DecompressDxt3(src, w, h), w, h); // DXT3 - case 894720068: return Wrap(DxtUtil.DecompressDxt5(src, w, h), w, h); // DXT5 - case 20: // R8G8B8 (stored B,G,R) - for (int i = 0; i < w * h && i * 3 + 2 < src.Length; i++) Px(i, src[i * 3 + 2], src[i * 3 + 1], src[i * 3], 255); - break; - case 243: // CUSTOM_LSCAPE_R8G8B8 (stored R,G,B) - for (int i = 0; i < w * h && i * 3 + 2 < src.Length; i++) Px(i, src[i * 3], src[i * 3 + 1], src[i * 3 + 2], 255); - break; - case 21: // A8R8G8B8 - case 22: // X8R8G8B8 - for (int i = 0; i < w * h && i * 4 + 3 < src.Length; i++) - { int b = src[i * 4], g = src[i * 4 + 1], rr = src[i * 4 + 2], a = fmt == 22 ? 255 : src[i * 4 + 3]; Px(i, rr, g, b, a); } - break; - case 23: // R5G6B5 - for (int i = 0; i < w * h && i * 2 + 1 < src.Length; i++) - { ushort v = (ushort)(src[i * 2] | (src[i * 2 + 1] << 8)); Px(i, ((v >> 11) & 0x1F) << 3, ((v >> 5) & 0x3F) << 2, (v & 0x1F) << 3, 255); } - break; - case 26: // A4R4G4B4 - for (int i = 0; i < w * h && i * 2 + 1 < src.Length; i++) - { ushort v = (ushort)(src[i * 2] | (src[i * 2 + 1] << 8)); Px(i, ((v >> 8) & 0xF) * 17, ((v >> 4) & 0xF) * 17, (v & 0xF) * 17, ((v >> 12) & 0xF) * 17); } - break; - case 28: // A8 (greyscale) - case 244: // LSCAPE_ALPHA - for (int i = 0; i < w * h && i < src.Length; i++) Px(i, src[i], src[i], src[i], 255); - break; - case 101: // INDEX16 - case 41: // P8 + byte[]? file = _portal.GetFileData(textureId); + if (file == null || file.Length < 24) return null; + var r = new ReadOnlySpan(file); + int w = I32(r, 8), h = I32(r, 12); + uint format = U32(r, 16); + int length = I32(r, 20); + if (w <= 0 || h <= 0 || w > 4096 || h > 4096 || length < 0 || 24L + length > file.Length) return null; + var src = r.Slice(24, length); + int n = w * h; + + switch (format) { - uint[]? pal = LoadPalette(defPal); - if (pal == null || pal.Length == 0) return null; - bool p8 = fmt == 41; - for (int i = 0; i < w * h; i++) - { - int idx; - if (p8) { if (i >= src.Length) break; idx = src[i]; } - else { if (i * 2 + 1 >= src.Length) break; idx = (ushort)(src[i * 2] | (src[i * 2 + 1] << 8)); } - uint cc = pal[idx % pal.Length]; - Px(i, (int)((cc >> 16) & 0xFF), (int)((cc >> 8) & 0xFF), (int)(cc & 0xFF), (int)((cc >> 24) & 0xFF)); - } - break; + case Dxt1: return Make(w, h, DxtUtil.DecompressDxt1(src.ToArray(), w, h)); + case Dxt3: return Make(w, h, DxtUtil.DecompressDxt3(src.ToArray(), w, h)); + case Dxt5: return Make(w, h, DxtUtil.DecompressDxt5(src.ToArray(), w, h)); } - default: - return null; // unhandled format + + var px = new byte[n * 4]; + switch (format) + { + case A8R8G8B8: // B, G, R, A in memory + if (length < n * 4) return null; + for (int i = 0; i < n; i++) Put(px, i, src[i * 4 + 2], src[i * 4 + 1], src[i * 4], src[i * 4 + 3]); + break; + case R8G8B8: // B, G, R + if (length < n * 3) return null; + for (int i = 0; i < n; i++) Put(px, i, src[i * 3 + 2], src[i * 3 + 1], src[i * 3], 255); + break; + case LscapeR8G8B8: // R, G, B + if (length < n * 3) return null; + for (int i = 0; i < n; i++) Put(px, i, src[i * 3], src[i * 3 + 1], src[i * 3 + 2], 255); + break; + case R5G6B5: + if (length < n * 2) return null; + for (int i = 0; i < n; i++) + { + int v = src[i * 2] | (src[i * 2 + 1] << 8); + // Top bits only (low bits left 0), as the decoder this replaced did. + Put(px, i, (byte)(((v >> 11) & 0x1F) << 3), (byte)(((v >> 5) & 0x3F) << 2), (byte)((v & 0x1F) << 3), 255); + } + break; + case A4R4G4B4: + if (length < n * 2) return null; + for (int i = 0; i < n; i++) + { + int v = src[i * 2] | (src[i * 2 + 1] << 8); + Put(px, i, (byte)(((v >> 8) & 0xF) * 17), (byte)(((v >> 4) & 0xF) * 17), (byte)((v & 0xF) * 17), (byte)(((v >> 12) & 0xF) * 17)); + } + break; + case A8: // one byte a pixel, shown as an opaque grey level + case LscapeAlpha: + if (length < n) return null; + for (int i = 0; i < n; i++) Put(px, i, src[i], src[i], src[i], 255); + break; + case P8: + case Index16: + { + int bpp = format == P8 ? 1 : 2; + if (length < n * bpp || 24L + length + 4 > file.Length) return null; + uint[]? palette = LoadPalette(U32(r, 24 + length)); + if (palette == null) return null; + for (int i = 0; i < n; i++) + { + int idx = bpp == 1 ? src[i] : src[i * 2] | (src[i * 2 + 1] << 8); + uint argb = idx < palette.Length ? palette[idx] : 0; + Put(px, i, (byte)(argb >> 16), (byte)(argb >> 8), (byte)argb, (byte)(argb >> 24)); + } + break; + } + default: + return null; + } + return Make(w, h, px); + } + catch + { + return null; } - return new Rgba { Width = w, Height = h, Pixels = rgba }; } - private static Rgba Wrap(byte[] rgba, int w, int h) => new Rgba { Width = w, Height = h, Pixels = rgba }; // DxtUtil already RGBA + // A 0x04 Palette's colours (A8R8G8B8), or null. + private uint[]? LoadPalette(uint paletteId) + { + byte[]? file = _portal.GetFileData(paletteId); + if (file == null || file.Length < 8) return null; + int count = I32(file, 4); + if (count < 0 || 8L + count * 4L > file.Length) return null; + var colours = new uint[count]; + for (int i = 0; i < count; i++) colours[i] = U32(file, 8 + i * 4); + return colours; + } + + private static void Put(byte[] px, int i, byte r, byte g, byte b, byte a) + { + px[i * 4] = r; px[i * 4 + 1] = g; px[i * 4 + 2] = b; px[i * 4 + 3] = a; + } + + private static Rgba Make(int w, int h, byte[] rgba) => new() { Width = w, Height = h, Pixels = rgba }; + private static int I32(ReadOnlySpan s, int at) => System.Buffers.Binary.BinaryPrimitives.ReadInt32LittleEndian(s.Slice(at)); + private static uint U32(ReadOnlySpan s, int at) => System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(s.Slice(at)); } diff --git a/src/RynthCore.StatusAgent/LocalStatusServer.cs b/src/RynthCore.StatusAgent/LocalStatusServer.cs index 746db68..59b7442 100644 --- a/src/RynthCore.StatusAgent/LocalStatusServer.cs +++ b/src/RynthCore.StatusAgent/LocalStatusServer.cs @@ -28,6 +28,11 @@ internal sealed class LocalStatusServer : IDisposable private readonly string? _statusDir; // GET /inventory reads RynthCore..inventory.json from here private readonly IconService? _icons; // GET /icon?did=N (portal.dat → PNG); null = disabled private readonly MapService? _maps; // GET /maps + /map?lb&layer (baked dungeon .bin → PNG); null = disabled + private readonly WorldMapService? _worldMap; // GET /worldmap (landscape map from cell.dat, JPEG); null = disabled + private readonly NavAtlasService? _navAtlas; // GET /nav/search (RynthNav's Atlas, the Travel tab); null = disabled + // pid -> the plugin reports raiseXp, from the last status cycle (UpdateRaiseClients). A raise is accepted only + // for a client in here (POST /command action "raise"); everything else ignores it. + private volatile IReadOnlyDictionary _raiseClients = new Dictionary(); private volatile byte[] _latest = Encoding.UTF8.GetBytes("{\"schema\":\"rynthcore.status-agent/1\",\"clientCount\":0,\"clients\":[]}"); private CancellationTokenSource? _cts; @@ -43,7 +48,8 @@ internal sealed class LocalStatusServer : IDisposable bool enableStream = false, int streamQuality = 55, int streamIntervalMs = 400, WebRtcVideoService? video = null, VideoSocketService? videoSocket = null, RunArchive? runArchive = null, string? statusDirectory = null, - IconService? icons = null, MapService? maps = null) + IconService? icons = null, MapService? maps = null, WorldMapService? worldMap = null, + NavAtlasService? navAtlas = null) { _prefix = prefix.EndsWith('/') ? prefix : prefix + "/"; _token = string.IsNullOrWhiteSpace(token) ? null : token; @@ -57,6 +63,8 @@ internal sealed class LocalStatusServer : IDisposable _statusDir = string.IsNullOrWhiteSpace(statusDirectory) ? null : statusDirectory; _icons = icons; _maps = maps; + _worldMap = worldMap; + _navAtlas = navAtlas; _listener.Prefixes.Add(_prefix); } @@ -73,6 +81,15 @@ internal sealed class LocalStatusServer : IDisposable } } + /// The clients the last cycle read, and which take the raise command (thread-safe swap). + public void UpdateRaiseClients(IEnumerable clients) + { + var map = new Dictionary(); + foreach (var c in clients) + if (c.Pid > 0 && c.Source == "status-file" && c.State != "dead") map[c.Pid] = c.RaiseXp; + _raiseClients = map; + } + public bool TryStart(out string error) { // Never serve without a token, loopback included: every route but /healthz is behind it. @@ -285,7 +302,8 @@ internal sealed class LocalStatusServer : IDisposable foreach (var e in entries) payload.Maps.Add(new MapEntryDto { - Landblock = e.Landblock.ToString("X8"), + // Full "XXYY0000" form: what DrakRemote matches a client's landblock against. + Landblock = RemoteParity.LandblockFull(e.Landblock.ToString("X8")), Layer = e.Layer, Bytes = e.Bytes, Mtime = e.MtimeUtc, W = e.W, H = e.H, XMin = e.XMin, YMin = e.YMin, Name = "Dungeon " + (e.Landblock & 0xFFFF).ToString("X4"), @@ -380,8 +398,8 @@ internal sealed class LocalStatusServer : IDisposable { Write(res, 405, "application/json", "{\"error\":\"method not allowed\"}"u8.ToArray()); return; } if (_token != null && !Authorized(req)) { Write(res, 401, "application/json", "{\"error\":\"unauthorized\"}"u8.ToArray()); return; } - if (!uint.TryParse(req.QueryString["lb"], System.Globalization.NumberStyles.HexNumber, - System.Globalization.CultureInfo.InvariantCulture, out uint lb) + // lb in either form: "00005A48" (the file name) or "5A480000" (what /maps lists and the app sends). + if (!RemoteParity.TryLandblockShort(req.QueryString["lb"], out uint lb) || !int.TryParse(req.QueryString["layer"], out int layer)) { Write(res, 400, "application/json", "{\"error\":\"lb (hex) and layer required\"}"u8.ToArray()); return; } var r = _maps?.GetPng(lb, layer); @@ -402,6 +420,68 @@ internal sealed class LocalStatusServer : IDisposable return; } + // ── Character sheet: GET /character?pid=N — attributes, vitals, skills (the phone's Skills tab) ── + if (path == "/character" || path == "/character.json") + { + if (!string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase)) + { Write(res, 405, "application/json", "{\"error\":\"method not allowed\"}"u8.ToArray()); return; } + if (_token != null && !Authorized(req)) + { Write(res, 401, "application/json", "{\"error\":\"unauthorized\"}"u8.ToArray()); return; } + int cpid = int.TryParse(req.QueryString["pid"], out int cp) ? cp : 0; + if (cpid <= 0) + { Write(res, 400, "application/json", "{\"error\":\"pid required\"}"u8.ToArray()); return; } + byte[]? sheet = ReadClientFile(cpid, "character"); + if (sheet == null) + { Write(res, 404, "application/json", "{\"error\":\"no character sheet from that client yet (needs the RynthRemote plugin 0.3)\"}"u8.ToArray()); return; } + res.Headers["Cache-Control"] = "no-cache"; + Write(res, 200, "application/json", sheet); + return; + } + + // ── Travel search: GET /nav/search?q=&type=&ns=&ew=&max= — RynthNav's Atlas, best matches first ── + if (path == "/nav/search") + { + if (!string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase)) + { Write(res, 405, "application/json", "{\"error\":\"method not allowed\"}"u8.ToArray()); return; } + if (_token != null && !Authorized(req)) + { Write(res, 401, "application/json", "{\"error\":\"unauthorized\"}"u8.ToArray()); return; } + if (_navAtlas == null || !_navAtlas.Available) + { Write(res, 404, "application/json", "{\"error\":\"RynthNav's Atlas (NavData locations.json) isn't on this PC\"}"u8.ToArray()); return; } + var ci = System.Globalization.CultureInfo.InvariantCulture; + double? fromNs = double.TryParse(req.QueryString["ns"], System.Globalization.NumberStyles.Float, ci, out double fn) ? fn : null; + double? fromEw = double.TryParse(req.QueryString["ew"], System.Globalization.NumberStyles.Float, ci, out double fe) ? fe : null; + int max = ClampQuery(req, "max", 40, 1, 100); + Write(res, 200, "application/json", _navAtlas.SearchJson(req.QueryString["q"] ?? "", req.QueryString["type"], fromNs, fromEw, max)); + return; + } + + // ── Landscape map: GET /worldmap — Dereth from cell.dat, 2040 px square, 24 units a pixel, north up ── + if (path == "/worldmap" || path == "/worldmap.jpg") + { + if (!string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase)) + { Write(res, 405, "application/json", "{\"error\":\"method not allowed\"}"u8.ToArray()); return; } + if (_token != null && !Authorized(req)) + { Write(res, 401, "application/json", "{\"error\":\"unauthorized\"}"u8.ToArray()); return; } + if (_worldMap == null || !_worldMap.Available) + { Write(res, 404, "application/json", "{\"error\":\"world map unavailable (no cell.dat on this PC)\"}"u8.ToArray()); return; } + byte[]? jpg = _worldMap.GetJpeg(); + if (jpg == null) + { + res.Headers["Retry-After"] = "5"; + Write(res, 503, "application/json", Encoding.UTF8.GetBytes("{\"error\":\"world map " + _worldMap.State + ", try again shortly\"}")); + return; + } + string wmTag = "\"worldmap-v1-" + jpg.Length + "\""; + res.Headers["X-Map-Size"] = WorldMapService.Size.ToString(System.Globalization.CultureInfo.InvariantCulture); + res.Headers["X-Map-Units-Per-Pixel"] = WorldMapService.UnitsPerPixel.ToString(System.Globalization.CultureInfo.InvariantCulture); + if (string.Equals(req.Headers["If-None-Match"], wmTag, StringComparison.Ordinal)) + { res.Headers["ETag"] = wmTag; Write(res, 304, "image/jpeg", Array.Empty()); return; } + res.Headers["Cache-Control"] = "public, max-age=604800"; + res.Headers["ETag"] = wmTag; + Write(res, 200, "image/jpeg", jpg); + return; + } + if (!string.Equals(method, "GET", StringComparison.OrdinalIgnoreCase)) { Write(res, 405, "application/json", "{\"error\":\"method not allowed\"}"u8.ToArray()); @@ -431,10 +511,14 @@ internal sealed class LocalStatusServer : IDisposable "navProfile", "lootProfile", "metaProfile", "settingsProfile", "forceRebuff", "cancelRebuff", "clearBusy", "hideUi", "sendChat", "moveStart", "moveStop", + "moveKeepAlive", // hold-to-move protocol 2 (RynthRemote 0.4+): {"dirs":[...]} every ~200 ms while held "setSetting", // change ONE advanced setting (value = {"key":..,"value":..}); RynthAi clamps + persists "click", // mouse click in the stream (value = {"u":..,"v":..,"button":..}); handled by the agent (PostMessage) + "travel", // RynthNav: go somewhere (value = {"name":..,"ns":..,"ew":..}); the plugin sends /rnav go + "travelStop", // RynthNav: stop travelling (/rnav stop) "assess", // request an Assess/Identify of one item (value = item id) — fills inventory appraisal + "raise", // spend XP / skill credits (value = {"kind","id","count","cost","nonce"}); known raise-capable pid only "closeClient", }; @@ -488,12 +572,33 @@ internal sealed class LocalStatusServer : IDisposable } } catch { } - bool clicked = ScreenCapture.TryClick(pid, u, v, button); - Write(res, clicked ? 202 : 503, "application/json", - clicked ? "{\"ok\":true}"u8.ToArray() : "{\"error\":\"click failed (window missing or minimized)\"}"u8.ToArray()); + var click = ScreenCapture.TryClick(pid, u, v, button); + // One line per tap (no token, no query string): which window, where, and what happened, so a + // tap that does nothing in game can be told apart from one that never reached the window. + AgentLog.Info($"click pid={pid} u={u:0.###} v={v:0.###} {button} -> {click.Result} at {click.X},{click.Y} of {click.Width}x{click.Height}"); + if (click.Result == ScreenCapture.ClickResult.Posted) + Write(res, 202, "application/json", Encoding.UTF8.GetBytes( + "{\"ok\":true,\"x\":" + click.X + ",\"y\":" + click.Y + ",\"w\":" + click.Width + ",\"h\":" + click.Height + "}")); + else + Write(res, 503, "application/json", Encoding.UTF8.GetBytes("{\"error\":\"click failed: " + click.Reason + "\"}")); return; } + // Raise spends experience, which can't be undone: only for a client this agent reads whose plugin + // takes it, and only in the fixed shape (the plugin and the engine check it all again). + if (string.Equals(action, "raise", StringComparison.OrdinalIgnoreCase)) + { + int code = RemoteParity.CheckRaise(pid, value, _raiseClients, out string normalized, out string why); + if (code != 202) + { + AgentLog.Warn($"raise refused: pid={pid} {why}"); + Write(res, code, "application/json", Encoding.UTF8.GetBytes("{\"error\":\"" + why + "\"}")); + return; + } + action = "raise"; + value = normalized; + } + Directory.CreateDirectory(_commandDir!); PruneStaleCommands(); @@ -507,7 +612,11 @@ internal sealed class LocalStatusServer : IDisposable File.WriteAllText(tmp, payload, Encoding.UTF8); File.Move(tmp, dest, overwrite: true); - AgentLog.Info($"command queued: pid={pid} {action}={value}"); + // Keep-alives arrive ~5 a second per held client: debug only, so the log keeps the presses and releases. + if (string.Equals(action, "moveKeepAlive", StringComparison.OrdinalIgnoreCase)) + AgentLog.Debug($"command queued: pid={pid} {action}={value}"); + else + AgentLog.Info($"command queued: pid={pid} {action}={value}"); Write(res, 202, "application/json", "{\"ok\":true}"u8.ToArray()); } catch (Exception ex) @@ -571,7 +680,7 @@ internal sealed class LocalStatusServer : IDisposable { string path = Path.Combine(_statusDir, $"RynthCore.{pid}.inventory.json"); if (!File.Exists(path)) return EmptyInventory; - byte[] bytes = File.ReadAllBytes(path); + byte[] bytes = StatusFileCache.ReadAllBytesShared(path); // let the plugin replace it meanwhile return bytes.Length >= 2 ? bytes : EmptyInventory; } catch { return EmptyInventory; } @@ -586,12 +695,26 @@ internal sealed class LocalStatusServer : IDisposable { string path = Path.Combine(_statusDir, $"RynthCore.{pid}.settings.json"); if (!File.Exists(path)) return "{}"u8.ToArray(); - byte[] bytes = File.ReadAllBytes(path); + byte[] bytes = StatusFileCache.ReadAllBytesShared(path); // let the plugin replace it meanwhile return bytes.Length >= 2 ? bytes : "{}"u8.ToArray(); } catch { return "{}"u8.ToArray(); } } + /// Read RynthCore...json (written atomically by the RynthRemote plugin); null when absent. + private byte[]? ReadClientFile(int pid, string kind) + { + if (_statusDir == null) return null; + try + { + string path = Path.Combine(_statusDir, $"RynthCore.{pid}.{kind}.json"); + if (!File.Exists(path)) return null; + byte[] bytes = StatusFileCache.ReadAllBytesShared(path); // let the plugin replace it meanwhile + return bytes.Length >= 2 ? bytes : null; + } + catch { return null; } + } + private static int ClampQuery(HttpListenerRequest req, string key, int def, int lo, int hi) => int.TryParse(req.QueryString[key], out int v) ? Math.Clamp(v, lo, hi) : def; diff --git a/src/RynthCore.StatusAgent/Models.cs b/src/RynthCore.StatusAgent/Models.cs index cfb3aa2..3d19d06 100644 --- a/src/RynthCore.StatusAgent/Models.cs +++ b/src/RynthCore.StatusAgent/Models.cs @@ -40,6 +40,107 @@ internal sealed class StatusFileModel [JsonPropertyName("lastIssue")] public string? LastIssue { get; set; } [JsonPropertyName("lastIssueAgeSec")] public long LastIssueAgeSec { get; set; } = -1; [JsonPropertyName("bot")] public BotSnapshot? Bot { get; set; } + // Added by the RynthRemote plugin 0.3 (DrakRemote parity): the player's enchantments (ids + seconds + // left; the agent adds names/icons from portal.dat) and where the character stands, outdoors too. + [JsonPropertyName("enchantments")] public List? Enchantments { get; set; } + [JsonPropertyName("opos")] public PositionIn? Opos { get; set; } + // RynthRemote 0.3: the last travel the phone asked RynthNav for (destination, what the plugin did). + [JsonPropertyName("travel")] public TravelIn? Travel { get; set; } + // RynthRemote 0.4: the phone may raise attributes, vitals and skills on this client (engine API v79, + // the client's raise senders bound, in the world). The costs ride the character sheet. + [JsonPropertyName("raiseXp")] public bool RaiseXp { get; set; } + // RynthRemote 0.4: the hold-to-move protocol it speaks (2 = moveStart {"dir","deadmanMs"} + moveKeepAlive). + [JsonPropertyName("moveProto")] public int MoveProto { get; set; } +} + +/// The plugin's record of the last phone travel: where to, and "sent" / "stopped" / "refused". +internal sealed class TravelIn +{ + [JsonPropertyName("dest")] public string Dest { get; set; } = ""; + [JsonPropertyName("ns")] public double? Ns { get; set; } + [JsonPropertyName("ew")] public double? Ew { get; set; } + [JsonPropertyName("state")] public string State { get; set; } = ""; + [JsonPropertyName("detail")] public string Detail { get; set; } = ""; + [JsonPropertyName("sentAt")] public DateTimeOffset? SentAt { get; set; } +} + +/// The phone's travel status: the plugin's record, RynthNav's latest chat note, and how far is left. +internal sealed class TravelOut +{ + [JsonPropertyName("dest")] public string Dest { get; set; } = ""; + [JsonPropertyName("ns")] public double? Ns { get; set; } + [JsonPropertyName("ew")] public double? Ew { get; set; } + /// sent | arrived | stopped | refused (and "unavailable" when RynthNav isn't loaded). + [JsonPropertyName("state")] public string State { get; set; } = ""; + [JsonPropertyName("detail")] public string Detail { get; set; } = ""; + [JsonPropertyName("sentAt")] public DateTimeOffset? SentAt { get; set; } + /// RynthNav's latest "[RynthNav] ..." chat line, without the tag ("walking to Holtburg — ..."). + [JsonPropertyName("note")] public string Note { get; set; } = ""; + /// Straight-line distance left in RynthNav's units (yd); null indoors or with no target position. + [JsonPropertyName("distance")] public double? Distance { get; set; } +} + +/// One enchantment as the plugin writes it: spell id + seconds left (-1 = never lapses). +internal sealed class EnchantmentIn +{ + [JsonPropertyName("spellId")] public uint SpellId { get; set; } + [JsonPropertyName("secondsRemaining")] public double SecondsRemaining { get; set; } +} + +/// Where the character stands (plugin "opos"): absolute world units, the dungeon-map frame. +internal sealed class PositionIn +{ + [JsonPropertyName("cell")] public string Cell { get; set; } = ""; + [JsonPropertyName("indoor")] public bool Indoor { get; set; } + [JsonPropertyName("wx")] public double Wx { get; set; } + [JsonPropertyName("wy")] public double Wy { get; set; } + [JsonPropertyName("z")] public double Z { get; set; } + [JsonPropertyName("heading")] public double? Heading { get; set; } +} + +/// One enchantment as the phone reads it (DrakBot Remote's "enchantments" entry). +internal sealed class EnchantmentOut +{ + [JsonPropertyName("spellId")] public uint SpellId { get; set; } + [JsonPropertyName("name")] public string Name { get; set; } = ""; + [JsonPropertyName("family")] public uint Family { get; set; } + [JsonPropertyName("tier")] public int Tier { get; set; } + [JsonPropertyName("secondsRemaining")] public double SecondsRemaining { get; set; } + [JsonPropertyName("beneficial")] public bool Beneficial { get; set; } = true; + [JsonPropertyName("school")] public uint School { get; set; } + [JsonPropertyName("iconId")] public uint IconId { get; set; } +} + +/// +/// What this agent can actually do, sent as "capabilities" so the phone hides what doesn't work here +/// (without it the app assumes everything the old agent offered). Same names as DrakBot Remote's, plus +/// "character" (GET /character, the Skills tab) and "worldMap" (GET /worldmap, the landscape map). +/// +internal sealed class AgentCapabilities +{ + [JsonPropertyName("inventory")] public bool Inventory { get; set; } + [JsonPropertyName("settings")] public bool Settings { get; set; } + [JsonPropertyName("movement")] public bool Movement { get; set; } + [JsonPropertyName("chat")] public bool Chat { get; set; } + [JsonPropertyName("icons")] public bool Icons { get; set; } + [JsonPropertyName("closeClient")] public bool CloseClient { get; set; } + [JsonPropertyName("video")] public bool Video { get; set; } + [JsonPropertyName("videoMinimized")] public bool VideoMinimized { get; set; } + [JsonPropertyName("videoHd")] public bool VideoHd { get; set; } + [JsonPropertyName("click")] public bool Click { get; set; } + [JsonPropertyName("runs")] public bool Runs { get; set; } + [JsonPropertyName("maps")] public bool Maps { get; set; } + [JsonPropertyName("dungeon")] public bool Dungeon { get; set; } + [JsonPropertyName("act")] public bool Act { get; set; } + [JsonPropertyName("nearby")] public bool Nearby { get; set; } + [JsonPropertyName("pick")] public bool Pick { get; set; } + [JsonPropertyName("character")] public bool Character { get; set; } + [JsonPropertyName("worldMap")] public bool WorldMap { get; set; } + /// GET /nav/search + the travel / travelStop commands (RynthNav through the RynthRemote plugin). + [JsonPropertyName("travel")] public bool Travel { get; set; } + /// The raise command: spend unassigned XP (and skill credits) from the Skills tab. Needs remote + /// control and a client whose RynthRemote plugin reports raiseXp (engine API v79). + [JsonPropertyName("raiseXp")] public bool RaiseXp { get; set; } } /// The subset of the RynthAi snapshot the agent surfaces. @@ -228,6 +329,17 @@ internal sealed class ClientStatus [JsonPropertyName("recentChat")] public List? RecentChat { get; set; } [JsonPropertyName("lastIssue")] public string? LastIssue { get; set; } [JsonPropertyName("lastIssueAgeSec")] public long LastIssueAgeSec { get; set; } = -1; + /// Every enchantment on the character, soonest to lapse first (null = the plugin doesn't say). + [JsonPropertyName("enchantments")] public List? Enchantments { get; set; } + /// Facing in degrees (0 = north, clockwise) when the plugin reports it, for the map's arrow. + [JsonPropertyName("heading")] public double? Heading { get; set; } + /// The last phone travel and how it stands (null when none this session). + [JsonPropertyName("travel")] public TravelOut? Travel { get; set; } + /// This client takes the raise command (its plugin says so and remote control is on). + [JsonPropertyName("raiseXp")] public bool RaiseXp { get; set; } + /// The hold-to-move protocol this client's plugin speaks: 2 = keep-alives and a dead-man + /// (the phone then sends moveKeepAlive), 0 = the old repeated moveStart. + [JsonPropertyName("moveProto")] public int MoveProto { get; set; } } internal sealed class AggregatePayload @@ -237,6 +349,7 @@ internal sealed class AggregatePayload [JsonPropertyName("agentVersion")] public string AgentVersion { get; set; } = ""; [JsonPropertyName("generatedAtUtc")] public DateTimeOffset GeneratedAtUtc { get; set; } [JsonPropertyName("clientCount")] public int ClientCount { get; set; } + [JsonPropertyName("capabilities")] public AgentCapabilities? Capabilities { get; set; } [JsonPropertyName("clients")] public List Clients { get; set; } = new(); } diff --git a/src/RynthCore.StatusAgent/NavAtlasService.cs b/src/RynthCore.StatusAgent/NavAtlasService.cs new file mode 100644 index 0000000..efce42a --- /dev/null +++ b/src/RynthCore.StatusAgent/NavAtlasService.cs @@ -0,0 +1,218 @@ +using System.Globalization; +using System.Text; +using System.Text.Json; + +namespace RynthCore.StatusAgent; + +/// +/// The phone's destination search (GET /nav/search) over RynthNav's own Atlas file, NavData\locations.json +/// (towns, dungeons, portals, lifestones, NPCs, vendors...), read here rather than copied: one file, the +/// one the in-game Atlas searches. Ranking is RynthNav's (Atlas.MatchScore / TypeRank, copied), so the phone +/// lists places in the order the in-game search does; "area" is the nearest town for a place on the map. +/// Reloaded when the file changes (NavData updates). The travel itself goes to RynthNav as a /rnav "go" +/// through the RynthRemote plugin - the agent never touches RynthNav. +/// +internal sealed class NavAtlasService +{ + /// RynthNav's NavCoords.UnitsPerDegree: one degree of N/S or E/W is 240 units ("yd"). + public const double UnitsPerDegree = 240.0; + + internal sealed record Place(int Id, string Name, string Type, string Where, bool OnMap, double Ns, double Ew, string Area, + bool Closed, bool Quest, int MinLevel, string DestName); + + private readonly string _path; + private readonly object _gate = new(); + private List? _places; + private DateTime _loadedMtime; + private string _generated = ""; + + public NavAtlasService(string path) => _path = path; + + public bool Available => File.Exists(_path); + + // ── loading ───────────────────────────────────────────────────────────── + + private List Places() + { + lock (_gate) + { + DateTime mtime; + try { mtime = File.GetLastWriteTimeUtc(_path); } catch { mtime = default; } + if (_places != null && mtime == _loadedMtime) return _places; + try + { + var (places, generated) = Parse(File.ReadAllText(_path)); + _places = places; _generated = generated; _loadedMtime = mtime; + AgentLog.Info($"[nav] Atlas read: {places.Count:N0} places ({generated})."); + } + catch (Exception ex) + { + AgentLog.Warn($"[nav] Atlas unreadable ({_path}): {ex.GetType().Name}: {ex.Message}"); + _places ??= new List(); + } + return _places; + } + } + + /// locations.json -> places, each on-map one with its nearest town as the area. + internal static (List Places, string Generated) Parse(string json) + { + using var doc = JsonDocument.Parse(json); + var root = doc.RootElement; + string generated = root.TryGetProperty("generated", out var g) && g.ValueKind == JsonValueKind.String ? g.GetString() ?? "" : ""; + var raw = new List<(int Id, string Name, string Type, string Where, bool OnMap, double Ns, double Ew, bool Closed, bool Quest, int MinLevel, string Dest)>(); + if (root.TryGetProperty("locations", out var arr) && arr.ValueKind == JsonValueKind.Array) + { + foreach (var e in arr.EnumerateArray()) + { + bool onMap = TryNum(e, "ns", out double ns) & TryNum(e, "ew", out double ew); + string dest = e.TryGetProperty("dest", out var d) && d.ValueKind == JsonValueKind.Object ? Str(d, "name") : ""; + raw.Add((Int(e, "id"), Str(e, "name"), Str(e, "type"), Str(e, "place"), onMap, ns, ew, Bool(e, "closed"), Bool(e, "quest"), Int(e, "minLevel"), dest)); + } + } + var towns = raw.Where(r => r.OnMap && r.Type == "Town").ToList(); + var places = new List(raw.Count); + foreach (var r in raw) + { + string area = ""; + if (r.OnMap && towns.Count > 0) + { + var near = towns.MinBy(t => Distance(r.Ns, r.Ew, t.Ns, t.Ew)); + double dist = Distance(r.Ns, r.Ew, near.Ns, near.Ew); + area = r.Type == "Town" && near.Name == r.Name ? "" : dist < 1200 ? "near " + near.Name : ""; + } + places.Add(new Place(r.Id, r.Name, r.Type, r.Where, r.OnMap, r.Ns, r.Ew, area, r.Closed, r.Quest, r.MinLevel, r.Dest)); + } + return (places, generated); + } + + // ── search ────────────────────────────────────────────────────────────── + + /// RynthNav's Atlas.MatchScore: 0 = not a match. + public static int MatchScore(string name, string q) + { + if (q.Length == 0) return 1; + if (name.Equals(q, StringComparison.OrdinalIgnoreCase)) return 100; + int at = name.IndexOf(q, StringComparison.OrdinalIgnoreCase); + if (at == 0) return 80; + if (at > 0) return char.IsLetterOrDigit(name[at - 1]) ? 40 : 60; + string[] words = q.Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (words.Length < 2) return 0; + foreach (string w in words) + if (name.IndexOf(w, StringComparison.OrdinalIgnoreCase) < 0) return 0; + return 30; + } + + /// RynthNav's Atlas.TypeRank: places before people. + public static int TypeRank(string type) => type switch + { + "Town" => 0, "Dungeon" => 1, "Landmark" => 2, "Lifestone" => 3, "Bindstone" => 4, + "Portal" => 5, "Vendor" => 6, "NPC" => 7, _ => 8, + }; + + public static double Distance(double ns1, double ew1, double ns2, double ew2) + { + double dn = (ns2 - ns1) * UnitsPerDegree, de = (ew2 - ew1) * UnitsPerDegree; + return Math.Sqrt(dn * dn + de * de); + } + + /// + /// The best matches for (at least 2 characters), optionally of one type: best name + /// match, then type, then nearest to (, ) when given, + /// then name. At most . + /// + internal static List<(Place Place, double? Distance)> Search(IReadOnlyList places, string query, string? type, double? fromNs, double? fromEw, int max) + { + string q = (query ?? "").Trim(); + var hits = new List<(Place P, int S, double? D)>(); + if (q.Length < 2) return new(); + foreach (var p in places) + { + if (!string.IsNullOrEmpty(type) && !p.Type.Equals(type, StringComparison.OrdinalIgnoreCase)) continue; + int s = MatchScore(p.Name, q); + if (s == 0) continue; + double? d = p.OnMap && fromNs is double fn && fromEw is double fe ? Distance(fn, fe, p.Ns, p.Ew) : null; + hits.Add((p, s, d)); + } + hits.Sort((a, b) => + { + int c = b.S.CompareTo(a.S); + if (c != 0) return c; + c = TypeRank(a.P.Type).CompareTo(TypeRank(b.P.Type)); + if (c != 0) return c; + c = (a.D ?? double.MaxValue).CompareTo(b.D ?? double.MaxValue); + return c != 0 ? c : string.Compare(a.P.Name, b.P.Name, StringComparison.OrdinalIgnoreCase); + }); + return hits.Take(Math.Clamp(max, 1, 100)).Select(h => (h.P, h.D)).ToList(); + } + + /// GET /nav/search's body (schema rynthcore.nav-search/1). + public byte[] SearchJson(string query, string? type, double? fromNs, double? fromEw, int max) + { + var places = Places(); + var hits = Search(places, query, type, fromNs, fromEw, max); + return Encoding.UTF8.GetBytes(SearchJson(hits, query, places.Count, _generated)); + } + + internal static string SearchJson(List<(Place Place, double? Distance)> hits, string query, int atlasCount, string generated) + { + var ci = CultureInfo.InvariantCulture; + using var ms = new MemoryStream(); + using (var w = new Utf8JsonWriter(ms)) + { + w.WriteStartObject(); + w.WriteString("schema", "rynthcore.nav-search/1"); + w.WriteString("query", query ?? ""); + w.WriteNumber("atlasCount", atlasCount); + w.WriteString("generated", generated); + w.WriteNumber("count", hits.Count); + w.WriteStartArray("results"); + foreach (var (p, d) in hits) + { + w.WriteStartObject(); + w.WriteNumber("id", p.Id); + w.WriteString("name", p.Name); + w.WriteString("type", p.Type); + w.WriteString("area", p.Area); + w.WriteString("where", p.Where); + w.WriteBoolean("onMap", p.OnMap); + if (p.OnMap) + { + w.WriteNumber("ns", Math.Round(p.Ns, 2)); + w.WriteNumber("ew", Math.Round(p.Ew, 2)); + w.WriteString("coords", Fmt(p.Ns, p.Ew)); + } + if (d is double dist) w.WriteNumber("distance", Math.Round(dist)); + if (p.DestName.Length > 0) w.WriteString("dest", p.DestName); + if (p.MinLevel > 0) w.WriteNumber("minLevel", p.MinLevel); + if (p.Quest) w.WriteBoolean("quest", true); + if (p.Closed) w.WriteBoolean("closed", true); + // RynthNav walks only to places with a map position; a place inside a dungeon has none. + w.WriteBoolean("canTravel", p.OnMap && !p.Closed); + w.WriteEndObject(); + } + w.WriteEndArray(); + w.WriteEndObject(); + } + return Encoding.UTF8.GetString(ms.ToArray()); + } + + /// RynthNav's NavCoords.Fmt: "42.1N, 33.6E". + public static string Fmt(double ns, double ew) + { + var ci = CultureInfo.InvariantCulture; + return Math.Abs(ns).ToString("F1", ci) + (ns >= 0 ? "N" : "S") + ", " + Math.Abs(ew).ToString("F1", ci) + (ew >= 0 ? "E" : "W"); + } + + /// The status frame's absolute world units to map coordinates (RynthNav's own conversion). + public static (double Ns, double Ew) FromWorld(double wx, double wy) => ((wy / 24.0 - 1019.5) / 10.0, (wx / 24.0 - 1019.5) / 10.0); + + private static string Str(JsonElement e, string n) => e.TryGetProperty(n, out var v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : ""; + private static int Int(JsonElement e, string n) => e.TryGetProperty(n, out var v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out int i) ? i : 0; + private static bool Bool(JsonElement e, string n) => e.TryGetProperty(n, out var v) && v.ValueKind == JsonValueKind.True; + private static bool TryNum(JsonElement e, string n, out double d) + { + d = 0; + return e.TryGetProperty(n, out var v) && v.ValueKind == JsonValueKind.Number && v.TryGetDouble(out d); + } +} diff --git a/src/RynthCore.StatusAgent/Program.cs b/src/RynthCore.StatusAgent/Program.cs index 3d43b25..0d00005 100644 --- a/src/RynthCore.StatusAgent/Program.cs +++ b/src/RynthCore.StatusAgent/Program.cs @@ -53,6 +53,13 @@ if (publisher.Enabled) else AgentLog.Info("No endpoint configured -> LOCAL PRINT-ONLY mode (nothing is sent anywhere)."); +// The client's spell table (portal.dat), loaded once in the background: names + icons for the Buffs tab. +var spells = new SpellTableService(cfg.IconDatPath); +// The landscape map (cell.dat -> one cached JPEG), rendered on the first /worldmap request. +var worldMap = new WorldMapService(cfg.CellDatPath, cfg.StatusDirectory); +// RynthNav's Atlas (NavData\locations.json), searched for the phone's Travel tab. +var navAtlas = new NavAtlasService(cfg.NavAtlasPath); + // Opt-in pull endpoint: an app can fetch status with no backend. LocalStatusServer? server = null; WebRtcVideoService? video = null; // HD WebRTC video mode (opt-in); disposed in finally @@ -80,7 +87,7 @@ else if (cfg.ServeHttp) MapService maps = new MapService(cfg.MapsDirectory); server = new LocalStatusServer(cfg.ServePrefix, cfg.ServeToken, commandDir, cfg.EnableScreenStream, cfg.StreamQuality, cfg.StreamIntervalMs, video, videoSocket, - runArchive, cfg.StatusDirectory, icons, maps); + runArchive, cfg.StatusDirectory, icons, maps, worldMap, navAtlas); if (server.TryStart(out string serveErr)) { AgentLog.Info($"Serving status at {cfg.ServePrefix}status (GET){(string.IsNullOrEmpty(cfg.ServeToken) ? "" : ", token required")}."); @@ -159,7 +166,7 @@ return 0; // One status cycle: read all client status, roll it up, and serve / file / POST it. async Task RunCycleAsync() { - List clients = StatusReader.ReadAll(cfg); + List clients = StatusReader.ReadAll(cfg, spells); runArchive.Observe(clients); // fold this cycle into per-session run history (started/updated/finished) var payload = new AggregatePayload { @@ -167,6 +174,14 @@ async Task RunCycleAsync() AgentVersion = version, GeneratedAtUtc = DateTimeOffset.UtcNow, ClientCount = clients.Count, + // What works on this PC, so the phone stops assuming DrakBot-era "everything". + Capabilities = RemoteParity.Capabilities(cfg, + iconDat: File.Exists(cfg.IconDatPath), + dungeonMaps: Directory.Exists(cfg.MapsDirectory), + worldMap: worldMap.Available, + characterSheets: clients.Any(c => File.Exists(Path.Combine(cfg.StatusDirectory, $"RynthCore.{c.Pid}.character.json"))), + navAtlas: navAtlas.Available, + raiseXp: clients.Any(c => c.RaiseXp)), Clients = clients, }; @@ -178,6 +193,7 @@ async Task RunCycleAsync() AgentLog.Debug(System.Text.Encoding.UTF8.GetString(bytes)); server?.UpdateLatest(bytes); + server?.UpdateRaiseClients(clients); if (cfg.WriteAggregateFile) { diff --git a/src/RynthCore.StatusAgent/RemoteParity.cs b/src/RynthCore.StatusAgent/RemoteParity.cs new file mode 100644 index 0000000..e4eff7e --- /dev/null +++ b/src/RynthCore.StatusAgent/RemoteParity.cs @@ -0,0 +1,223 @@ +using System.Globalization; + +namespace RynthCore.StatusAgent; + +/// +/// The pieces that make a RynthCore client look to DrakRemote the way a DrakBot client does +/// (2026-10-05 parity work): landblock ids in the form the app matches on, the capabilities block, +/// enchantments with names and icons, and the tap-to-click coordinate mapping. Pure functions, so the +/// agent tests (tools\StatusAgentTests) cover them without a game running. +/// +internal static class RemoteParity +{ + // ── landblocks ────────────────────────────────────────────────────────── + + /// + /// A landblock as DrakRemote matches it: the full cell-style id "XXYY0000". The engine (and the baked + /// floor-plan file names) write the short form "0000XXYY"; DrakBot writes the full one, and since + /// DrakRemote f87130c the app reads a short map id as full (shifts it) but takes the client's id as + /// written - so a RynthCore client never matched its own dungeon's maps. Writing both full fixes it + /// for the phone already installed. Empty or unparseable stays as it was. + /// + public static string LandblockFull(string? landblock) + { + if (string.IsNullOrWhiteSpace(landblock)) return ""; + if (!uint.TryParse(landblock.Trim(), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint v)) return landblock; + if (v == 0) return ""; + uint full = v <= 0xFFFF ? v << 16 : v & 0xFFFF0000u; + return full.ToString("X8", CultureInfo.InvariantCulture); + } + + /// The short landblock (0xXXYY) from either form ("5A48", "00005A48", "5A480000", "5A48013F"). + public static bool TryLandblockShort(string? s, out uint lb) + { + lb = 0; + if (string.IsNullOrWhiteSpace(s) + || !uint.TryParse(s.Trim(), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint v)) return false; + lb = v > 0xFFFF ? v >> 16 : v; + return lb != 0; + } + + // ── capabilities ──────────────────────────────────────────────────────── + + /// What the agent offers, from its config and what is on this box. act / nearby / pick / + /// dungeon are DrakBot's (no RynthCore route for them yet), and a scraped window has no picture while + /// minimized, so those stay off. + public static AgentCapabilities Capabilities(AgentConfig cfg, bool iconDat, bool dungeonMaps, bool worldMap, bool characterSheets, bool navAtlas = false, bool raiseXp = false) + { + bool control = cfg.EnableRemoteControl; + return new AgentCapabilities + { + Inventory = true, + Settings = true, + Movement = control, + Chat = true, + Icons = iconDat, + CloseClient = control, + Video = cfg.EnableScreenStream, + VideoMinimized = false, + VideoHd = cfg.EnableVideoStream, + Click = control && cfg.EnableScreenStream, + Runs = true, + Maps = dungeonMaps || worldMap, + Dungeon = false, + Act = false, + Nearby = false, + Pick = false, + Character = characterSheets, + WorldMap = worldMap, + // Searching needs the Atlas; going needs the command channel the travel rides on. + Travel = navAtlas && control, + // Spending XP rides the command channel and needs a client whose plugin can (engine API v79). + RaiseXp = raiseXp && control && characterSheets, + }; + } + + // ── raise (spend XP / skill credits from the Skills tab) ──────────────── + + /// + /// Checks a phone raise before it becomes a command file and rewrites the value in a fixed shape: + /// {"kind":"attribute|vital|skill|train","id":N or "health|stamina|mana","count":1..100,"cost":N,"nonce":".."}. + /// The pid must be a client this agent reads whose plugin reports raiseXp (: + /// pid -> raiseXp). Returns the HTTP status to answer with (202 = write the command) and why not. + /// The plugin and the engine check everything again (the engine against fresh numbers and the cost). + /// + public static int CheckRaise(int pid, string? value, IReadOnlyDictionary raiseClients, out string normalized, out string error) + { + normalized = ""; + error = ""; + if (!raiseClients.TryGetValue(pid, out bool can)) { error = "unknown client"; return 404; } + if (!can) { error = "raising isn't available on that client (needs the RynthRemote plugin 0.4 and a RynthCore engine with plugin API 79)"; return 409; } + if (string.IsNullOrWhiteSpace(value)) { error = "bad raise"; return 400; } + try + { + using var doc = System.Text.Json.JsonDocument.Parse(value); + var r = doc.RootElement; + if (r.ValueKind != System.Text.Json.JsonValueKind.Object) { error = "bad raise"; return 400; } + string kind = r.TryGetProperty("kind", out var k) && k.ValueKind == System.Text.Json.JsonValueKind.String ? (k.GetString() ?? "").ToLowerInvariant() : ""; + if (kind is not ("attribute" or "vital" or "skill" or "train")) { error = "bad raise kind"; return 400; } + + string id; + if (!r.TryGetProperty("id", out var idEl)) { error = "bad raise id"; return 400; } + if (idEl.ValueKind == System.Text.Json.JsonValueKind.Number && idEl.TryGetInt32(out int n)) + { + bool ok = kind switch { "attribute" => n is >= 1 and <= 6, "vital" => n is 1 or 3 or 5, _ => n is >= 1 and <= 54 }; + if (!ok) { error = "bad raise id"; return 400; } + id = n.ToString(CultureInfo.InvariantCulture); + } + else if (kind == "vital" && idEl.ValueKind == System.Text.Json.JsonValueKind.String + && (idEl.GetString() ?? "").ToLowerInvariant() is "health" or "stamina" or "mana") + id = "\"" + idEl.GetString()!.ToLowerInvariant() + "\""; + else { error = "bad raise id"; return 400; } + + int count = 1; + if (kind != "train" && r.TryGetProperty("count", out var c) + && (c.ValueKind != System.Text.Json.JsonValueKind.Number || !c.TryGetInt32(out count) || count < 1 || count > 100)) + { error = "bad raise count"; return 400; } + + if (!r.TryGetProperty("cost", out var costEl) || costEl.ValueKind != System.Text.Json.JsonValueKind.Number + || !costEl.TryGetInt64(out long cost) || cost <= 0 || cost > uint.MaxValue) + { error = "a raise needs the confirmed cost"; return 400; } + + string nonce = ""; + if (r.TryGetProperty("nonce", out var nEl) && nEl.ValueKind == System.Text.Json.JsonValueKind.String) + foreach (char ch in nEl.GetString() ?? "") + if (nonce.Length < 40 && (char.IsAsciiLetterOrDigit(ch) || ch == '-' || ch == '_')) nonce += ch; + + normalized = "{\"kind\":\"" + kind + "\",\"id\":" + id + + ",\"count\":" + count.ToString(CultureInfo.InvariantCulture) + + ",\"cost\":" + cost.ToString(CultureInfo.InvariantCulture) + + ",\"nonce\":\"" + nonce + "\"}"; + return 202; + } + catch (System.Text.Json.JsonException) { error = "bad raise"; return 400; } + } + + // ── travel ────────────────────────────────────────────────────────────── + + private const string NavTag = "[RynthNav] "; + + /// + /// The phone's travel status: the plugin's record of what it sent, RynthNav's latest chat note (its + /// "[RynthNav] ..." lines reach the status's recent chat), "arrived" when that note says so, and the + /// straight-line distance left while outdoors. RynthNav's own progress line and ETA are not reachable + /// from another plugin (its status export isn't a RynthPluginGet*Json), so the note stands in for them. + /// + public static TravelOut? Travel(TravelIn? t, IReadOnlyList? recentChat, bool indoor, double wx, double wy) + { + if (t == null || string.IsNullOrEmpty(t.State)) return null; + string note = ""; + if (recentChat != null) + for (int i = recentChat.Count - 1; i >= 0; i--) + { + string line = recentChat[i].Text ?? ""; + if (line.StartsWith(NavTag, StringComparison.Ordinal)) { note = line[NavTag.Length..].Trim(); break; } + } + string state = t.State; + if (state == "sent" && note.StartsWith("Arrived at ", StringComparison.Ordinal) + && (t.Dest.Length == 0 || note.Contains(t.Dest, StringComparison.OrdinalIgnoreCase))) + state = "arrived"; + double? left = null; + if (!indoor && (wx != 0 || wy != 0) && t.Ns is double dns && t.Ew is double dew) + { + var (ns, ew) = NavAtlasService.FromWorld(wx, wy); + left = Math.Round(NavAtlasService.Distance(ns, ew, dns, dew)); + } + return new TravelOut { Dest = t.Dest, Ns = t.Ns, Ew = t.Ew, State = state, Detail = t.Detail, SentAt = t.SentAt, Note = note, Distance = left }; + } + + // ── enchantments ──────────────────────────────────────────────────────── + + /// The plugin's bare enchantments with the spell table's name, family, tier, school, + /// beneficial flag and icon; "Spell N" (beneficial, no icon) for one the table doesn't know. + public static List? Enchantments(List? input, Func lookup) + { + if (input == null) return null; + var list = new List(input.Count); + foreach (var e in input) + { + if (e.SpellId == 0) continue; + var info = lookup(e.SpellId); + string name = info is { Name.Length: > 0 } i ? i.Name : "Spell " + e.SpellId.ToString(CultureInfo.InvariantCulture); + list.Add(new EnchantmentOut + { + SpellId = e.SpellId, + Name = name, + Family = info?.Category ?? 0, + Tier = SpellTableService.TierFromName(name), + SecondsRemaining = double.IsFinite(e.SecondsRemaining) ? e.SecondsRemaining : -1, + Beneficial = info?.Beneficial ?? true, + School = info?.School ?? 0, + IconId = info?.Icon ?? 0, + }); + } + // Soonest first; the never-lapsing ones (-1) last, as DrakBot orders them for the countdown. + list.Sort(static (a, b) => + { + bool ap = a.SecondsRemaining < 0, bp = b.SecondsRemaining < 0; + if (ap != bp) return ap ? 1 : -1; + int c = a.SecondsRemaining.CompareTo(b.SecondsRemaining); + return c != 0 ? c : a.SpellId.CompareTo(b.SpellId); + }); + return list; + } + + // ── tap-to-click ──────────────────────────────────────────────────────── + + /// + /// The client-area pixel a phone tap lands on: (u, v) in 0..1 of the frame the stream shows (the + /// window's client area, origin top-left, same aspect - a downscaled stream keeps it), so x = u * (w-1), + /// y = v * (h-1), clamped. The app has already taken the letterbox out (rynthTap.normalize). + /// + public static (int X, int Y) ClickPoint(double u, double v, int clientWidth, int clientHeight) + { + if (!double.IsFinite(u)) u = 0; + if (!double.IsFinite(v)) v = 0; + int x = (int)Math.Round(Math.Clamp(u, 0, 1) * Math.Max(0, clientWidth - 1)); + int y = (int)Math.Round(Math.Clamp(v, 0, 1) * Math.Max(0, clientHeight - 1)); + return (x, y); + } + + /// A mouse message's lParam: y in the high word, x in the low. + public static IntPtr MouseLParam(int x, int y) => (IntPtr)unchecked((int)(((uint)(y & 0xFFFF) << 16) | (uint)(x & 0xFFFF))); +} diff --git a/src/RynthCore.StatusAgent/ScreenCapture.cs b/src/RynthCore.StatusAgent/ScreenCapture.cs index 6873012..abfb3aa 100644 --- a/src/RynthCore.StatusAgent/ScreenCapture.cs +++ b/src/RynthCore.StatusAgent/ScreenCapture.cs @@ -123,26 +123,49 @@ internal static class ScreenCapture /// Device::WndProc dispatches WM_LBUTTONDOWN/etc by lParam, never GetCursorPos), so this drives both the /// 2D UI and 3D-world hit-test WITHOUT moving the real cursor or stealing focus, even when the window is /// backgrounded/occluded — multibox-safe. Returns false if the window is missing or minimized. - public static bool TryClick(int pid, double u, double v, string? button) + public enum ClickResult { Posted, NotFound, Minimized, NoClientArea, PostFailed } + + /// What one tap did: where it went in the client area (and how big that is), or why not. + public readonly record struct ClickOutcome(ClickResult Result, int X, int Y, int Width, int Height) + { + public string Reason => Result switch + { + ClickResult.Posted => "posted", + ClickResult.NotFound => "no game window for that pid", + ClickResult.Minimized => "the game window is minimized", + ClickResult.NoClientArea => "the game window has no client area", + _ => "PostMessage failed", + }; + } + + // Give the game a frame between the move and the press, and between press and release: RynthCore + // can throttle a background client (Background FPS, 5..60), and a move + press + release that all land + // inside one frame can read to AC as a press at the old cursor spot, or as nothing at all. + private const int MoveSettleMs = 60; + private const int PressHoldMs = 90; + + public static ClickOutcome TryClick(int pid, double u, double v, string? button) { EnsureDpiAware(); - if (!TryFindWindow(pid, out IntPtr hwnd, out bool minimized) || minimized || hwnd == IntPtr.Zero) return false; - if (!GetClientRect(hwnd, out RECT cr)) return false; + if (!TryFindWindow(pid, out IntPtr hwnd, out bool minimized) || hwnd == IntPtr.Zero) + return new ClickOutcome(minimized ? ClickResult.Minimized : ClickResult.NotFound, 0, 0, 0, 0); + if (!GetClientRect(hwnd, out RECT cr)) return new ClickOutcome(ClickResult.NoClientArea, 0, 0, 0, 0); int cw = cr.Right - cr.Left, ch = cr.Bottom - cr.Top; - if (cw < 2 || ch < 2) return false; - int x = (int)Math.Round(Math.Clamp(u, 0, 1) * (cw - 1)); - int y = (int)Math.Round(Math.Clamp(v, 0, 1) * (ch - 1)); - IntPtr lParam = (IntPtr)unchecked((uint)((y << 16) | (x & 0xFFFF))); + if (cw < 2 || ch < 2) return new ClickOutcome(ClickResult.NoClientArea, 0, 0, cw, ch); + var (x, y) = RemoteParity.ClickPoint(u, v, cw, ch); + IntPtr lParam = RemoteParity.MouseLParam(x, y); bool right = string.Equals(button, "right", StringComparison.OrdinalIgnoreCase); + IntPtr held = (IntPtr)(right ? MK_RBUTTON : MK_LBUTTON); try { - PostMessage(hwnd, WM_MOUSEMOVE, IntPtr.Zero, lParam); - PostMessage(hwnd, right ? WM_RBUTTONDOWN : WM_LBUTTONDOWN, (IntPtr)(right ? 0x0002 : 0x0001), lParam); - System.Threading.Thread.Sleep(80); // brief down→up so AC registers a click, not a drag + if (!PostMessage(hwnd, WM_MOUSEMOVE, IntPtr.Zero, lParam)) return new ClickOutcome(ClickResult.PostFailed, x, y, cw, ch); + System.Threading.Thread.Sleep(MoveSettleMs); + PostMessage(hwnd, right ? WM_RBUTTONDOWN : WM_LBUTTONDOWN, held, lParam); + System.Threading.Thread.Sleep(PressHoldMs); // down→up apart so AC registers a click, not a drag PostMessage(hwnd, right ? WM_RBUTTONUP : WM_LBUTTONUP, IntPtr.Zero, lParam); - return true; + return new ClickOutcome(ClickResult.Posted, x, y, cw, ch); } - catch { return false; } + catch { return new ClickOutcome(ClickResult.PostFailed, x, y, cw, ch); } } /// Pick the game window for this pid: the largest visible, non-minimized acclient-class window. The @@ -198,6 +221,7 @@ internal static class ScreenCapture [DllImport("user32.dll")] private static extern bool GetClientRect(IntPtr hWnd, out RECT r); [DllImport("user32.dll")] private static extern bool PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam); private const uint WM_MOUSEMOVE = 0x0200, WM_LBUTTONDOWN = 0x0201, WM_LBUTTONUP = 0x0202, WM_RBUTTONDOWN = 0x0204, WM_RBUTTONUP = 0x0205; + private const int MK_LBUTTON = 0x0001, MK_RBUTTON = 0x0002; [DllImport("user32.dll")] private static extern bool ClientToScreen(IntPtr hWnd, ref POINT p); private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam); [DllImport("user32.dll")] private static extern bool EnumWindows(EnumWindowsProc cb, IntPtr lParam); diff --git a/src/RynthCore.StatusAgent/SpellTableService.cs b/src/RynthCore.StatusAgent/SpellTableService.cs new file mode 100644 index 0000000..d4faca2 --- /dev/null +++ b/src/RynthCore.StatusAgent/SpellTableService.cs @@ -0,0 +1,150 @@ +using RynthCore2.TerrainData; + +namespace RynthCore.StatusAgent; + +/// +/// The client's spell table (portal.dat file 0x0E00000E), read once in the background so the agent can +/// turn the plugin's bare enchantment ids into what the phone's Buffs tab shows: name, family (category), +/// tier, school, beneficial or not, and the spell's icon. Same layout and parse as the engine's +/// RynthCore.Engine/ImGui/MonsterHud/PortalSpellTable.cs (ACE.DatLoader SpellTable/SpellBase); this +/// copy keeps every spell, not just the debuffs. Until it is loaded (or if portal.dat is missing) a +/// lookup misses and the agent writes "Spell N" with no icon - the countdown still works. +/// +internal sealed class SpellTableService +{ + private const uint SpellTableFileId = 0x0E00000E; + private const uint FlagBeneficial = 0x4; + private const uint MetaEnchantment = 1, MetaPortalSummon = 7, MetaFellowEnchantment = 12; + + internal readonly record struct SpellInfo(uint Id, string Name, uint School, uint Icon, uint Category, uint Flags) + { + public bool Beneficial => (Flags & FlagBeneficial) != 0; + } + + private readonly string _datPath; + private volatile Dictionary? _table; + private int _queued; + + public SpellTableService(string portalDatPath) => _datPath = portalDatPath; + + public bool Ready => _table != null; + + /// A spell by id, once the table is in; queues the one-time load on first use. Any thread. + public bool TryGet(uint spellId, out SpellInfo info) + { + var t = _table; + if (t == null) + { + EnsureLoadQueued(); + info = default; + return false; + } + return t.TryGetValue(spellId, out info); + } + + public void EnsureLoadQueued() + { + if (_table != null || Interlocked.Exchange(ref _queued, 1) == 1) return; + _ = Task.Run(Load); + } + + private void Load() + { + try + { + if (!File.Exists(_datPath)) { AgentLog.Warn($"[spells] portal.dat not found at '{_datPath}'; buff names fall back to spell ids."); return; } + using var db = new DatDatabase(); + if (!db.Open(_datPath)) { AgentLog.Warn($"[spells] could not open '{_datPath}'."); return; } + byte[]? raw = db.GetFileData(SpellTableFileId); + if (raw == null) { AgentLog.Warn("[spells] spell table 0x0E00000E not in portal.dat."); return; } + var t = Parse(raw, out int total); + _table = t; + AgentLog.Info($"[spells] spell table read: {t.Count:N0} of {total:N0} spells."); + } + catch (Exception ex) { AgentLog.Warn($"[spells] spell table read failed: {ex.GetType().Name}: {ex.Message}"); } + } + + /// Parse the SpellTable file. Public for the agent tests (a hand-built table). + internal static Dictionary Parse(byte[] raw, out int total) + { + var t = new Dictionary(); + var r = new SpanReader(raw); + r.U32(); // file id + total = r.U16(); + r.U16(); // bucket count + for (int i = 0; i < total && r.Ok; i++) + { + uint id = r.U32(); + string name = r.ObfuscatedString(); + r.ObfuscatedString(); // description + uint school = r.U32(); + uint icon = r.U32(); + uint category = r.U32(); + uint flags = r.U32(); + r.U32(); // base mana + r.Skip(8); // range constant, range mod + r.U32(); // power + r.Skip(12); // economy mod, formula version, component loss + uint meta = r.U32(); + r.U32(); // meta spell id + if (meta == MetaEnchantment || meta == MetaFellowEnchantment) r.Skip(16); // duration f64, degrade mod, degrade limit + else if (meta == MetaPortalSummon) r.Skip(8); // portal lifetime + r.Skip(8 * 4 + 12 + 8 + 4 + 12); // components, effects, recovery, display order, target type, mana mod + if (!r.Ok) break; + t[id] = new SpellInfo(id, name, school, icon, category, flags); + } + return t; + } + + /// The spell's level 1-8 from its name: a Roman suffix ("... VII"), "Incantation of" = 8, + /// otherwise 0 (unknown). Matches RynthAi's SpellInfo.ComputeLevel closely enough for display. + internal static int TierFromName(string name) + { + if (string.IsNullOrEmpty(name)) return 0; + if (name.StartsWith("Incantation of ", StringComparison.OrdinalIgnoreCase)) return 8; + int sp = name.LastIndexOf(' '); + string last = sp >= 0 ? name[(sp + 1)..] : name; + return last switch + { + "I" => 1, "II" => 2, "III" => 3, "IV" => 4, "V" => 5, "VI" => 6, "VII" => 7, "VIII" => 8, + _ => 0, + }; + } + + /// Bounds-checked little-endian reader; Ok turns false on overrun. + private ref struct SpanReader + { + private readonly ReadOnlySpan _b; + private int _p; + public bool Ok; + + public SpanReader(byte[] b) { _b = b; _p = 0; Ok = true; } + + private bool Has(int n) + { + if (Ok && _p + n <= _b.Length) return true; + Ok = false; + return false; + } + + public uint U32() { if (!Has(4)) return 0; uint v = BitConverter.ToUInt32(_b.Slice(_p, 4)); _p += 4; return v; } + public ushort U16() { if (!Has(2)) return 0; ushort v = BitConverter.ToUInt16(_b.Slice(_p, 2)); _p += 2; return v; } + public void Skip(int n) { if (Has(n)) _p += n; } + + /// u16 length + bytes with nibbles swapped, then aligned to 4 from the file start (as ACE does). + public string ObfuscatedString() + { + int n = U16(); + if (!Has(n)) return ""; + var chars = new char[n]; + for (int i = 0; i < n; i++) + { + byte x = _b[_p + i]; + chars[i] = (char)(byte)((x >> 4) | (x << 4)); // Latin-1: byte == code point + } + _p += n; + _p = (_p + 3) & ~3; + return new string(chars); + } + } +} diff --git a/src/RynthCore.StatusAgent/StatusFileCache.cs b/src/RynthCore.StatusAgent/StatusFileCache.cs new file mode 100644 index 0000000..69f9d08 --- /dev/null +++ b/src/RynthCore.StatusAgent/StatusFileCache.cs @@ -0,0 +1,75 @@ +using System.Collections.Concurrent; +using System.Text; + +namespace RynthCore.StatusAgent; + +/// +/// Reading the per-client files the RynthRemote plugin rewrites several times a second, without ever +/// dropping a client from a snapshot. +/// +/// Before (2026-10-05): while the agent was reading a status file, the plugin's atomic replace +/// (File.Move over it) failed (Windows won't replace an open file), and RynthRemote 0.3 then fell back to +/// overwriting the file in place; the next read caught it empty or half-written and the parse failed. +/// That client was left out of that one snapshot (StatusAgent.log: "1 client(s)" for ~60 ms, several +/// times a minute), and the phone's open deck for it unmounted and came back: the screen flashed and +/// scrolled to the top. RynthRemote 0.4 skips such a write instead of overwriting in place. +/// +/// Here: a status file that can't be read or parsed is answered with the last good parse of that +/// file for up to (its own timestamp stays in the model, so its age still shows +/// honestly), and files are read with ReadWrite|Delete sharing so a reader never makes a writer fail. +/// +internal static class StatusFileCache +{ + public static readonly TimeSpan KeepLastGood = TimeSpan.FromSeconds(3); + + private static readonly ConcurrentDictionary LastGood = new(StringComparer.OrdinalIgnoreCase); + + /// Read a whole file while letting the writer replace or rewrite it underneath. + public static byte[] ReadAllBytesShared(string path) + { + using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 4096, FileOptions.SequentialScan); + using var ms = new MemoryStream(fs.CanSeek ? (int)Math.Min(fs.Length, int.MaxValue) : 4096); + fs.CopyTo(ms); + return ms.ToArray(); + } + + public static string ReadAllTextShared(string path) => Encoding.UTF8.GetString(ReadAllBytesShared(path)).TrimStart(''); + + /// + /// Parse with ; on any read or parse failure (or a null + /// parse) answer the last good result for that path if it is younger than . + /// is the file reader (tests pass their own). + /// + public static T? Read(string path, Func parse, DateTime nowUtc, Func? read = null) where T : class + { + try + { + T? model = parse((read ?? ReadAllTextShared)(path)); + if (model != null) + { + LastGood[path] = (model, nowUtc); + return model; + } + } + catch (Exception ex) + { + AgentLog.Debug($"status file '{path}' unreadable: {ex.GetType().Name}: {ex.Message}"); + } + if (LastGood.TryGetValue(path, out var lg) && nowUtc - lg.AtUtc <= KeepLastGood && lg.Model is T t) + return t; + return null; + } + + /// Drop what is remembered for a file that is gone (a retired dead client) or for every file + /// not in . + public static void Forget(string path) => LastGood.TryRemove(path, out _); + + public static void ForgetAllBut(IReadOnlyCollection keep) + { + var set = new HashSet(keep, StringComparer.OrdinalIgnoreCase); + foreach (var k in LastGood.Keys) + if (!set.Contains(k)) LastGood.TryRemove(k, out _); + } + + internal static int CountForTests => LastGood.Count; +} diff --git a/src/RynthCore.StatusAgent/StatusReader.cs b/src/RynthCore.StatusAgent/StatusReader.cs index ea1ee34..4ae1efe 100644 --- a/src/RynthCore.StatusAgent/StatusReader.cs +++ b/src/RynthCore.StatusAgent/StatusReader.cs @@ -17,12 +17,12 @@ internal static partial class StatusReader [GeneratedRegex(@"hb #\d+ up=(\d+)s fps=(-?\d+) plug=(-?\d+)/s ws=(\d+)MB login=(\d+)")] private static partial Regex HeartbeatRegex(); - public static List ReadAll(AgentConfig cfg) + public static List ReadAll(AgentConfig cfg, SpellTableService? spells = null) { var clients = new List(); var seenPids = new HashSet(); - ReadStatusFiles(cfg, clients, seenPids); + ReadStatusFiles(cfg, clients, seenPids, spells); if (cfg.UseHeartbeatLogFallback) ReadHeartbeatLogs(cfg, clients, seenPids); @@ -33,27 +33,23 @@ internal static partial class StatusReader // ── Rich source: per-client status JSON files ─────────────────────────── - private static void ReadStatusFiles(AgentConfig cfg, List clients, HashSet seenPids) + private static void ReadStatusFiles(AgentConfig cfg, List clients, HashSet seenPids, SpellTableService? spells) { string dir = cfg.StatusDirectory; if (!Directory.Exists(dir)) return; + var listed = new List(); foreach (string path in SafeEnumerate(dir, "RynthCore.*.status.json")) { int pid = ParsePidFromName(Path.GetFileName(path), ".status.json"); if (pid <= 0) continue; + listed.Add(path); - StatusFileModel? model; - try - { - model = JsonSerializer.Deserialize(File.ReadAllText(path), AgentJsonContext.Default.StatusFileModel); - } - catch (Exception ex) - { - AgentLog.Debug($"status file '{path}' unreadable: {ex.Message}"); - continue; - } + // Shared read, and the last good parse when this one catches the file mid-write: a client is + // never left out of a snapshot just because its file was being replaced (see StatusFileCache). + StatusFileModel? model = StatusFileCache.Read(path, + text => JsonSerializer.Deserialize(text, AgentJsonContext.Default.StatusFileModel), DateTime.UtcNow); if (model == null) continue; double ageSec = AgeSeconds(model.Ts, path); @@ -64,6 +60,7 @@ internal static partial class StatusReader if (!alive && ageSec > cfg.DropDeadAfterSeconds) { try { File.Delete(path); } catch { } + StatusFileCache.Forget(path); continue; } @@ -149,8 +146,22 @@ internal static partial class StatusReader cs.XpSession = model.XpSession; cs.BurdenPct = model.BurdenPct; cs.Area = model.Area; - cs.Landblock = model.Landblock; cs.Indoor = model.Indoor; // [status-export] live map-dot + // [status-export] live map-dot. The landblock goes out in DrakBot's full form ("XXYY0000"), the + // one DrakRemote matches against its floor plans (see RemoteParity.LandblockFull). + cs.Landblock = RemoteParity.LandblockFull(model.Landblock); cs.Indoor = model.Indoor; cs.Wx = model.Wx; cs.Wy = model.Wy; cs.Pz = model.Pz; + // The engine writes wx/wy indoors only; the plugin's "opos" has them outdoors too (world map dot). + if (!model.Indoor && model.Opos is { } pos && (pos.Wx != 0 || pos.Wy != 0)) { cs.Wx = pos.Wx; cs.Wy = pos.Wy; } + cs.Heading = model.Opos?.Heading; + // The player's enchantments, named from portal.dat's spell table (the Buffs tab). + cs.Enchantments = RemoteParity.Enchantments(model.Enchantments, + id => spells != null && spells.TryGet(id, out var info) ? info : null); + // The last phone travel (RynthNav) and how it stands. + cs.Travel = RemoteParity.Travel(model.Travel, cs.RecentChat, cs.Indoor, cs.Wx, cs.Wy); + // Raising from the Skills tab: what the plugin reports; Program clears it without remote control. + cs.RaiseXp = model.RaiseXp && cfg.EnableRemoteControl; + // RynthRemote 0.4+: the movement protocol it speaks (2 = keep-alives + dead-man); 0 when absent. + cs.MoveProto = model.MoveProto; cs.LastIssue = model.LastIssue; cs.LastIssueAgeSec = model.LastIssueAgeSec; // Window state (for the app to show a "minimized — restore on PC" placeholder instead of a @@ -160,6 +171,7 @@ internal static partial class StatusReader clients.Add(cs); seenPids.Add(pid); } + StatusFileCache.ForgetAllBut(listed); } // ── Basic fallback: tail each per-client heartbeat log ────────────────── diff --git a/src/RynthCore.StatusAgent/WorldMapService.cs b/src/RynthCore.StatusAgent/WorldMapService.cs new file mode 100644 index 0000000..b47b699 --- /dev/null +++ b/src/RynthCore.StatusAgent/WorldMapService.cs @@ -0,0 +1,231 @@ +using System.Drawing; +using System.Drawing.Imaging; +using System.Runtime.InteropServices; +using RynthCore2.TerrainData; + +namespace RynthCore.StatusAgent; + +/// +/// A landscape map of Dereth for the phone (GET /worldmap): every outdoor landblock of the client's +/// cell.dat (record 0xXXYYFFFF: 9x9 terrain words + height indices), one pixel per 24-unit terrain cell, +/// coloured by terrain type, roads drawn, hills shaded from the height indices. 255 landblocks x 8 cells +/// = 2040 pixels square, north up. Rendered once in the background on the first request (the world does +/// not change) and cached as a JPEG next to the agent's other files, so later starts serve it at once. +/// +/// Frame (shared with the status "wx"/"wy" and the dungeon floor plans): absolute world units, x west to +/// east, y south to north, 192 units a landblock. Pixel = (wx / 24, 2040 - wy / 24). +/// +internal sealed class WorldMapService +{ + public const int CellsPerLandblock = 8; + public const int Landblocks = 255; + public const int Size = Landblocks * CellsPerLandblock; // 2040 + public const double UnitsPerPixel = 24.0; + private const string CacheName = "worldmap-v1.jpg"; + + private readonly string _cellDatPath; + private readonly string _cacheDir; + private volatile byte[]? _jpeg; + private int _started; + private volatile string _state = "idle"; + + public WorldMapService(string cellDatPath, string cacheDir) + { + _cellDatPath = cellDatPath; + _cacheDir = cacheDir; + } + + /// True when a map can be made here at all (the cell.dat is on this box, or one is cached). + public bool Available => _jpeg != null || File.Exists(_cellDatPath) || File.Exists(CachePath); + + public string State => _state; + + private string CachePath => Path.Combine(_cacheDir, CacheName); + + /// The JPEG, or null while it is being made (the first call starts that). Any thread. + public byte[]? GetJpeg() + { + var j = _jpeg; + if (j != null) return j; + if (Interlocked.Exchange(ref _started, 1) == 0) + { + _state = "being drawn"; + _ = Task.Run(LoadOrRender); + } + return null; + } + + private void LoadOrRender() + { + try + { + if (File.Exists(CachePath)) + { + _jpeg = File.ReadAllBytes(CachePath); + _state = "ready"; + AgentLog.Info($"[worldmap] served from cache {CachePath} ({_jpeg.Length / 1024:N0} KB)."); + return; + } + if (!File.Exists(_cellDatPath)) { _state = "no cell.dat"; AgentLog.Warn($"[worldmap] cell.dat not found at '{_cellDatPath}'."); return; } + + _state = "being drawn"; + var sw = System.Diagnostics.Stopwatch.StartNew(); + byte[] rgb; + int found; + using (var db = new DatDatabase()) + { + if (!db.Open(_cellDatPath)) { _state = "cell.dat unreadable"; AgentLog.Warn($"[worldmap] could not open '{_cellDatPath}'."); return; } + rgb = Render(lb => db.GetFileData(((uint)lb << 16) | 0xFFFF), out found); + } + byte[] jpeg = EncodeJpeg(rgb, Size, Size, 88); + try + { + Directory.CreateDirectory(_cacheDir); + string tmp = CachePath + ".tmp"; + File.WriteAllBytes(tmp, jpeg); + File.Move(tmp, CachePath, overwrite: true); + } + catch (Exception ex) { AgentLog.Warn($"[worldmap] cache write failed: {ex.Message}"); } + _jpeg = jpeg; + _state = "ready"; + AgentLog.Info($"[worldmap] rendered {found:N0} landblocks in {sw.Elapsed.TotalSeconds:0.0}s ({jpeg.Length / 1024:N0} KB)."); + } + catch (Exception ex) + { + _state = "failed"; + AgentLog.Warn($"[worldmap] render failed: {ex.GetType().Name}: {ex.Message}"); + Interlocked.Exchange(ref _started, 0); // let a later request try again + } + } + + /// + /// Paint the whole map into a 24-bit RGB buffer (row 0 = north). + /// returns the raw 0xXXYYFFFF record for a landblock id 0xXXYY, or null where there is none (open sea). + /// Internal for the tests, which hand it made-up landblocks. + /// + internal static byte[] Render(Func readLandblock, out int found) + { + var rgb = new byte[Size * Size * 3]; + Fill(rgb, Sea); + found = 0; + var terrain = new ushort[81]; + var heights = new byte[81]; + for (int lbx = 0; lbx < Landblocks; lbx++) + { + for (int lby = 0; lby < Landblocks; lby++) + { + byte[]? raw = readLandblock((lbx << 8) | lby); + if (!TryParse(raw, terrain, heights)) continue; + found++; + for (int ix = 0; ix < CellsPerLandblock; ix++) + { + for (int iy = 0; iy < CellsPerLandblock; iy++) + { + int v = ix * 9 + iy; + ushort word = terrain[v]; + int type = (word >> 2) & 0x1F; + Rgb c = Palette(type); + bool water = type is >= 16 and <= 20; + if ((word & 0x3) != 0 && !water) c = Road; + if (!water) + { + // Light from the north-west: a cell rising to the east and falling to the north is lit. + int dzx = heights[(ix + 1) * 9 + iy] - heights[v]; + int dzy = heights[ix * 9 + iy + 1] - heights[v]; + double s = Math.Clamp(1.0 + 0.045 * (dzx - dzy), 0.62, 1.35); + c = c.Scale(s); + } + int px = lbx * CellsPerLandblock + ix; + int py = Size - 1 - (lby * CellsPerLandblock + iy); + int o = (py * Size + px) * 3; + rgb[o] = c.R; rgb[o + 1] = c.G; rgb[o + 2] = c.B; + } + } + } + } + return rgb; + } + + /// Record layout: u32 id, u32 hasObjects, u16 terrain[81], u8 height[81] (vertex = ix*9 + iy). + internal static bool TryParse(byte[]? raw, ushort[] terrain, byte[] heights) + { + if (raw == null || raw.Length < 8 + 81 * 2 + 81) return false; + for (int i = 0; i < 81; i++) terrain[i] = BitConverter.ToUInt16(raw, 8 + i * 2); + Buffer.BlockCopy(raw, 8 + 81 * 2, heights, 0, 81); + return true; + } + + /// Where a world position lands on the map, in pixels (may fall outside for bad input). + public static (double X, double Y) ToPixel(double wx, double wy) => (wx / UnitsPerPixel, Size - wy / UnitsPerPixel); + + // ── colours ───────────────────────────────────────────────────────────── + + internal readonly record struct Rgb(byte R, byte G, byte B) + { + public Rgb Scale(double s) => new(Clamp(R * s), Clamp(G * s), Clamp(B * s)); + private static byte Clamp(double v) => (byte)Math.Clamp((int)Math.Round(v), 0, 255); + } + + private static readonly Rgb Sea = new(0x1F, 0x4A, 0x78); + private static readonly Rgb Road = new(0xA8, 0x93, 0x6C); + + /// ACE's LandDefs.TerrainType, 0..20; anything else (the reserved slots) a neutral grey. + internal static Rgb Palette(int type) => type switch + { + 0 => new(0x7A, 0x74, 0x66), // BarrenRock + 1 => new(0x6E, 0x8B, 0x3D), // Grassland + 2 => new(0xD8, 0xE8, 0xF0), // Ice + 3 => new(0x4F, 0x7A, 0x2A), // LushGrass + 4 => new(0x5A, 0x6B, 0x3A), // MarshSparseSwamp + 5 => new(0x6B, 0x52, 0x36), // MudRichDirt + 6 => new(0x2E, 0x2A, 0x30), // ObsidianPlain + 7 => new(0x8C, 0x75, 0x50), // PackedDirt + 8 => new(0x8A, 0x7B, 0x55), // PatchyDirt + 9 => new(0x7F, 0x8F, 0x48), // PatchyGrassland + 10 => new(0xD8, 0xC4, 0x8A), // SandYellow + 11 => new(0xB5, 0xAE, 0x98), // SandGrey + 12 => new(0xB8, 0xA4, 0x7A), // SandRockStrewn + 13 => new(0x9A, 0x84, 0x68), // SedimentaryRock + 14 => new(0x84, 0x7A, 0x63), // SemiBarrenRock + 15 => new(0xF0, 0xF4, 0xF7), // Snow + 16 => new(0x3C, 0x6E, 0x9E), // WaterRunning + 17 => new(0x3F, 0x78, 0xA8), // WaterStandingFresh + 18 => new(0x35, 0x6B, 0x9C), // WaterShallowSea + 19 => new(0x2F, 0x62, 0x93), // WaterShallowStillSea + 20 => new(0x1F, 0x4A, 0x78), // WaterDeepSea + _ => new(0x80, 0x80, 0x80), + }; + + private static void Fill(byte[] rgb, Rgb c) + { + for (int i = 0; i < rgb.Length; i += 3) { rgb[i] = c.R; rgb[i + 1] = c.G; rgb[i + 2] = c.B; } + } + + private static byte[] EncodeJpeg(byte[] rgb, int w, int h, int quality) + { + using var bmp = new Bitmap(w, h, PixelFormat.Format24bppRgb); + var bd = bmp.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.WriteOnly, PixelFormat.Format24bppRgb); + try + { + var row = new byte[w * 3]; + for (int y = 0; y < h; y++) + { + // GDI+ 24bpp is B,G,R in memory. + for (int x = 0; x < w; x++) + { + int s = (y * w + x) * 3; + row[x * 3] = rgb[s + 2]; row[x * 3 + 1] = rgb[s + 1]; row[x * 3 + 2] = rgb[s]; + } + Marshal.Copy(row, 0, bd.Scan0 + y * bd.Stride, row.Length); + } + } + finally { bmp.UnlockBits(bd); } + var enc = Array.Find(ImageCodecInfo.GetImageEncoders(), c => c.FormatID == ImageFormat.Jpeg.Guid) + ?? throw new InvalidOperationException("no jpeg encoder"); + using var ep = new EncoderParameters(1); + ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)Math.Clamp(quality, 1, 100)); + using var ms = new MemoryStream(); + bmp.Save(ms, enc, ep); + return ms.ToArray(); + } +} diff --git a/tools/DatReaderCheck/DatReaderCheck.csproj b/tools/DatReaderCheck/DatReaderCheck.csproj new file mode 100644 index 0000000..6b5bfeb --- /dev/null +++ b/tools/DatReaderCheck/DatReaderCheck.csproj @@ -0,0 +1,39 @@ + + + + + Exe + net10.0-windows + enable + enable + true + true + DatReaderCheck + + + + + + + + diff --git a/tools/DatReaderCheck/Program.cs b/tools/DatReaderCheck/Program.cs new file mode 100644 index 0000000..af61e08 --- /dev/null +++ b/tools/DatReaderCheck/Program.cs @@ -0,0 +1,253 @@ +// DatReaderCheck - proves a change to RynthCore's dat code on the real dat files (read only). +// Written for RynthCore (MIT). The modes are described in DatReaderCheck.csproj. +// +// Only the API of the code under test is used (StatusAgent: DatDatabase, IconDecoder; engine: +// AcDatFile, AcIconDecoder), so the same source builds against the old code and the new, and +// two builds' outputs can be compared line by line. + +using System.Diagnostics; +using System.Security.Cryptography; +using System.Text; +using RynthCore.Engine.UI.ScriptWindows; +using RynthCore.StatusAgent; +using RynthCore2.TerrainData; + +namespace DatReaderCheck; + +internal static class Program +{ + private static int Main(string[] args) + { + if (args.Length >= 3 && args[0] == "manifest") return Manifest(args[1], args[2]); + if (args.Length >= 3 && args[0] == "icons") return Icons(args[1], args[2]); + if (args.Length >= 3 && args[0] == "diff") return Diff(args[1], args[2]); + Console.WriteLine("usage: manifest | icons | diff "); + return 2; + } + + private static StreamWriter Out(string path) => new(path, false, new UTF8Encoding(false)) { NewLine = "\n" }; + + // ------------------------------------------------------------------ manifest + + private static int Manifest(string acDir, string outPath) + { + using var w = Out(outPath); + int rc = DumpDat(w, Path.Combine(acDir, "client_portal.dat")); + rc |= DumpDat(w, Path.Combine(acDir, "client_cell_1.dat")); + var p = Process.GetCurrentProcess(); + p.Refresh(); + w.WriteLine($"#t process peak working set {p.PeakWorkingSet64 / 1048576.0:F1} MB"); + return rc; + } + + private static int DumpDat(StreamWriter w, string path) + { + Console.WriteLine("== " + Path.GetFileName(path)); + w.WriteLine("== " + Path.GetFileName(path)); + var sw = Stopwatch.StartNew(); + using var db = new DatDatabase(); + bool ok = db.Open(path); + w.WriteLine($"open {ok}"); + w.WriteLine($"#t open {sw.Elapsed.TotalMilliseconds:F0} ms"); + if (!ok) { Console.WriteLine("open failed: " + string.Join(" | ", db.DiagLog)); return 1; } + w.WriteLine($"header FileType={db.FileType:X8} BlockSize={db.BlockSize} FileSize={db.FileSize} DataSet={db.DataSet:X8} BTreeRoot={db.BTreeRoot:X8} IsLoaded={db.IsLoaded} records={db.RecordCount}"); + + using var engine = AcDatFile.Open(path, out string why); + w.WriteLine($"engine-open {(engine != null ? "ok" : why)}"); + + var all = db.EntriesInRange(0, uint.MaxValue); + w.WriteLine($"entries-in-range-all {all.Count} {Hashes(all)}"); + var ids = all.Select(e => e.id).OrderBy(i => i).ToList(); + var idSet = new HashSet(ids); + + sw.Restart(); + int nulls = 0, mismatch = 0, engineDiff = 0, engineNull = 0; + long bytes = 0; + foreach (uint id in ids) + { + var f = db.FindFile(id); + if (f == null || f.ObjectId != id) mismatch++; + byte[]? data = db.GetFileData(id); + string digest; + if (data == null) { nulls++; digest = "NULL"; } + else { bytes += data.Length; digest = data.Length + " " + Convert.ToHexString(SHA256.HashData(data)); } + w.WriteLine($"f {id:X8} {f?.BitFlags:X8} {f?.FileOffset:X8} {f?.FileSize} = {digest}"); + + if (engine != null) + { + byte[]? e = engine.Read(id, int.MaxValue); + if (e == null) engineNull++; + else if (data == null || !e.AsSpan().SequenceEqual(data)) engineDiff++; + } + } + w.WriteLine($"files {ids.Count} read-null {nulls} find-mismatch {mismatch} bytes {bytes} engine-null {engineNull} engine-differs {engineDiff}"); + w.WriteLine($"#t all files {sw.Elapsed.TotalMilliseconds:F0} ms"); + Console.WriteLine($" {ids.Count} files, {nulls} null, {mismatch} find mismatches; engine reader: {engineNull} null, {engineDiff} differ"); + + // The engine reader's size cap and a few caps around real sizes. + if (engine != null) + { + int capped = 0; + foreach (var e in all.Take(2000)) if (engine.Read(e.id, (int)e.size - 1) == null) capped++; + int fits = 0; + foreach (var e in all.Take(2000)) if (engine.Read(e.id, (int)e.size) != null) fits++; + w.WriteLine($"engine-cap below-size-null {capped} at-size-ok {fits}"); + } + + sw.Restart(); + int probes = 0, misses = 0, wrong = 0, engineWrong = 0; + void Probe(uint id) + { + probes++; + var f = db.FindFile(id); + bool expect = idSet.Contains(id); + if (f == null) { misses++; if (expect) wrong++; } + else if (!expect || f.ObjectId != id) wrong++; + if (engine != null && probes % 8 == 0 && (engine.Read(id, int.MaxValue) != null) != expect) engineWrong++; + if (db.GetFileData(id) == null == expect) wrong++; + } + foreach (uint id in ids) + { + if (id != uint.MaxValue) Probe(id + 1); + if (id != 0) Probe(id - 1); + } + var rng = new Random(20261005); + for (int i = 0; i < 1_000_000; i++) Probe((uint)rng.NextInt64(0, 1L << 32)); + for (uint t = 0; t <= 0x40; t++) for (uint lo = 0; lo < 0x400; lo++) Probe((t << 24) | lo); + Probe(0); Probe(uint.MaxValue); + w.WriteLine($"probes {probes} misses {misses} wrong {wrong} engine-wrong {engineWrong}"); + w.WriteLine($"#t probes {sw.Elapsed.TotalMilliseconds:F0} ms"); + + for (uint t = 0; t <= 0xFF; t++) + { + var r = db.EntriesInRange(t << 24, (t << 24) | 0xFFFFFF); + if (r.Count > 0) w.WriteLine($"range {t:X2} {r.Count} {Hashes(r)}"); + } + int withCells = 0, cellIds = 0; + for (uint lb = 0; lb <= 0xFFFF; lb++) + { + var c = db.GetLandblockCellIds(lb); + if (c.Count == 0) continue; + withCells++; cellIds += c.Count; + w.WriteLine($"lb {lb:X4} {c.Count} {Hashes(c.Select(i => (i, 0u)).ToList())}"); + } + w.WriteLine($"landblocks with-cells {withCells} cell-ids {cellIds}"); + db.Close(); + w.WriteLine($"closed IsLoaded={db.IsLoaded} find-after-close={(db.FindFile(ids[0]) == null ? "null" : "hit")}"); + return 0; + } + + // Which entries a list holds, whatever their order, then (on a "#o" line, which diff reports + // but doesn't count) the order itself: the old reader returned ties and cell ids in its + // dictionary's order; the new one sorts them (size then id, cell ids ascending). + private static string Hashes(List<(uint id, uint size)> list) => + Hash(list.OrderBy(e => e.id).ThenBy(e => e.size).ToList()) + "\n#o order " + Hash(list); + + private static string Hash(List<(uint id, uint size)> list) + { + var b = new byte[list.Count * 8]; + for (int i = 0; i < list.Count; i++) + { + BitConverter.TryWriteBytes(b.AsSpan(i * 8), list[i].id); + BitConverter.TryWriteBytes(b.AsSpan(i * 8 + 4), list[i].size); + } + return Convert.ToHexString(SHA256.HashData(b), 0, 12); + } + + // ------------------------------------------------------------------ icons + + private static int Icons(string acDir, string outPath) + { + using var w = Out(outPath); + string path = Path.Combine(acDir, "client_portal.dat"); + using var db = new DatDatabase(); + if (!db.Open(path)) { Console.WriteLine("open failed"); return 1; } + using var engine = AcDatFile.Open(path, out string why); + if (engine == null) { Console.WriteLine("engine open failed: " + why); return 1; } + var decoder = new IconDecoder(db); + + var ids = db.EntriesInRange(0x06000000, 0x06FFFFFF).Select(e => e.id).OrderBy(i => i).ToList(); + w.WriteLine($"textures {ids.Count}"); + var byFormat = new SortedDictionary(); // format -> [count, status ok, engine ok, engine-ui ok] + double agentMs = 0, engineMs = 0; + var sw = new Stopwatch(); + var decodable = new List(); + foreach (uint id in ids) + { + byte[]? raw = db.GetFileData(id); + string fmt = "?"; + int fw = 0, fh = 0; + if (raw != null && raw.Length >= 24) + { + fw = BitConverter.ToInt32(raw, 8); fh = BitConverter.ToInt32(raw, 12); + fmt = BitConverter.ToUInt32(raw, 16).ToString("X8"); + } + sw.Restart(); + var a = decoder.Decode(id); + agentMs += sw.Elapsed.TotalMilliseconds; + sw.Restart(); + var e1 = AcIconDecoder.Decode(engine, id); + var e2 = AcIconDecoder.Decode(engine, id, AcIconDecoder.MaxUiSide); + engineMs += sw.Elapsed.TotalMilliseconds; + w.WriteLine($"t {id:X8} {fmt} {fw}x{fh} agent={D(a?.Width, a?.Height, a?.Pixels)} icon={D(e1?.Width, e1?.Height, e1?.Pixels)} ui={D(e2?.Width, e2?.Height, e2?.Pixels)}"); + if (!byFormat.TryGetValue(fmt, out var c)) byFormat[fmt] = c = new int[4]; + c[0]++; + if (a != null) c[1]++; + if (e1 != null) { c[2]++; if (fw == 32 && fh == 32) decodable.Add(id); } + if (e2 != null) c[3]++; + } + foreach (var kv in byFormat) + w.WriteLine($"format {kv.Key}: {kv.Value[0]} textures, agent decodes {kv.Value[1]}, engine icon {kv.Value[2]}, engine ui {kv.Value[3]}"); + w.WriteLine($"#t agent decode {agentMs:F0} ms, engine decode (icon + ui) {engineMs:F0} ms"); + Console.WriteLine($"{ids.Count} textures"); + foreach (var kv in byFormat) Console.WriteLine($" {kv.Key}: {kv.Value[0]} agent {kv.Value[1]} icon {kv.Value[2]} ui {kv.Value[3]}"); + + // Composed item pictures: underlay + icon + overlay (0 = none). + var rng = new Random(424242); + for (int i = 0; i < 3000 && decodable.Count > 0; i++) + { + uint icon = decodable[rng.Next(decodable.Count)]; + uint under = rng.Next(3) == 0 ? 0 : decodable[rng.Next(decodable.Count)]; + uint over = rng.Next(3) == 0 ? 0 : decodable[rng.Next(decodable.Count)]; + var c = AcIconDecoder.Compose(engine, icon, under, over); + w.WriteLine($"c {icon:X8} {under:X8} {over:X8} {D(c?.Width, c?.Height, c?.Pixels)}"); + } + // Ids that aren't textures, or aren't there. + foreach (uint id in new uint[] { 0, 0x05000001, 0x06FFFFFF, 0x07000001, 0x0E00000E }) + w.WriteLine($"x {id:X8} agent={D(decoder.Decode(id)?.Width, 0, decoder.Decode(id)?.Pixels)} icon={D(AcIconDecoder.Decode(engine, id)?.Width, 0, AcIconDecoder.Decode(engine, id)?.Pixels)}"); + return 0; + } + + private static string D(int? w, int? h, byte[]? px) => + px == null ? "null" : $"{w}x{h}:{Convert.ToHexString(SHA256.HashData(px), 0, 12)}"; + + // ------------------------------------------------------------------ diff + + private static int Diff(string a, string b) + { + var oa = File.ReadLines(a).Where(l => l.StartsWith("#o")).ToList(); + var ob = File.ReadLines(b).Where(l => l.StartsWith("#o")).ToList(); + int orderDiffs = oa.Count == ob.Count ? oa.Where((l, i) => l != ob[i]).Count() : -1; + Console.WriteLine($"order lines: {oa.Count} vs {ob.Count}, {(orderDiffs < 0 ? "counts differ" : orderDiffs + " differ")} (reported, not counted)"); + using var la = File.ReadLines(a).Where(l => !l.StartsWith('#')).GetEnumerator(); + using var lb = File.ReadLines(b).Where(l => !l.StartsWith('#')).GetEnumerator(); + long n = 0, diffs = 0; + while (true) + { + bool ha = la.MoveNext(), hb = lb.MoveNext(); + if (!ha && !hb) break; + n++; + string sa = ha ? la.Current : "", sb = hb ? lb.Current : ""; + if (sa == sb) continue; + if (diffs < 40) Console.WriteLine($"line {n}:\n a: {sa}\n b: {sb}"); + diffs++; + } + Console.WriteLine($"{n} lines compared, {diffs} differ"); + foreach (var (name, file) in new[] { ("a", a), ("b", b) }) + { + Console.WriteLine($"timings {name}:"); + foreach (var l in File.ReadLines(file).Where(l => l.StartsWith("#t"))) Console.WriteLine(" " + l); + } + return diffs == 0 ? 0 : 1; + } +} diff --git a/tools/LauncherUpdateTests/LauncherUpdateTests.csproj b/tools/LauncherUpdateTests/LauncherUpdateTests.csproj index 78f3bec..9100fea 100644 --- a/tools/LauncherUpdateTests/LauncherUpdateTests.csproj +++ b/tools/LauncherUpdateTests/LauncherUpdateTests.csproj @@ -3,7 +3,9 @@ + + net10.0-windows + x86 + win-x86 + Library + true + enable + true + Shared + true + Size + RynthCore.Plugin.NetProbe + RynthCore.Plugin.NetProbe + x86 + + + + + + + + + + + + diff --git a/tools/NetMessageTests/NetMessageTests.csproj b/tools/NetMessageTests/NetMessageTests.csproj new file mode 100644 index 0000000..c4fd133 --- /dev/null +++ b/tools/NetMessageTests/NetMessageTests.csproj @@ -0,0 +1,39 @@ + + + + + Exe + net10.0-windows + enable + enable + true + true + NetMessageTests + false + true + + + + + + + + + + + + + + diff --git a/tools/NetMessageTests/Program.cs b/tools/NetMessageTests/Program.cs new file mode 100644 index 0000000..e955f05 --- /dev/null +++ b/tools/NetMessageTests/Program.cs @@ -0,0 +1,969 @@ +using System.Buffers.Binary; +using System.Diagnostics; +using RynthCore.Engine.Net; +using RynthCore.PluginSdk.Net; + +namespace NetMessageTests; + +/// Collects what the reassembler hands over (copied: the pointer is only valid during the call). +internal sealed unsafe class Collect : IServerMessageSink +{ + public readonly List<(uint Seq, byte[] Bytes)> Messages = new(); + public void OnServerMessage(uint fragmentSequence, byte* message, int length) + => Messages.Add((fragmentSequence, new ReadOnlySpan(message, length).ToArray())); +} + +/// Counts only (the perf runs: no copies). +internal sealed unsafe class CountOnly : IServerMessageSink +{ + public long Count, Bytes; + public uint OpcodeXor; + public void OnServerMessage(uint fragmentSequence, byte* message, int length) + { + Count++; + Bytes += length; + OpcodeXor ^= *(uint*)message; + } +} + +internal static unsafe class Program +{ + private static int _checks, _failed; + private static string _case = ""; + private static long _now = 1_000_000; + + private static int Main(string[] args) + { + // Datagram walk + WalkPlain(); + WalkOptionalHeaders(); + WalkBadDatagrams(); + GoldenHexDatagram(); + + // Reassembly + SingleFragment(); + MultiFragmentInOrder(); + MultiFragmentOutOfOrder(); + DuplicateFragmentsAndRetransmits(); + MissingFragmentGoesStale(); + Oversized(); + InconsistentAndBadFragments(); + SlotExhaustion(); + SeveralMessagesPerDatagram(); + SessionReset(); + DoneWindowSlides(); + + // Ring, interest + RingBasics(); + RingWrapAndFull(); + RingCounterWrap(); + RingThreaded(); + Interest(); + + // Parsers + Strings(); + ChatParsers(); + FellowshipParsers(); + FriendsAndAllegiance(); + SystemTextAndConfirmation(); + TruncationNeverThrows(); + EndToEndGameEvents(); + + // Captures given on the command line + foreach (string path in args) + Replay(path); + + Console.WriteLine(); + Console.WriteLine($"{_checks - _failed}/{_checks} checks passed."); + Console.WriteLine(_failed == 0 ? "ALL NET MESSAGE TESTS PASSED." : $"{_failed} FAILED."); + + Performance(); + return _failed == 0 ? 0 : 1; + } + + // ── helpers ───────────────────────────────────────────────────────────── + + private static void Feed(FragmentReassembler r, byte[] datagram, IServerMessageSink sink) + { + fixed (byte* p = datagram) + r.ProcessDatagram(p, datagram.Length, _now, sink); + } + + private static PacketWalk Walk(byte[] d, out int start, out int end) + { + fixed (byte* p = d) + return AcPacketWire.LocateFragments(p, d.Length, out start, out end); + } + + private static byte[] Msg(int length, uint opcode = 0xF745, byte seed = 1) + { + var b = new byte[length]; + if (length >= 4) BinaryPrimitives.WriteUInt32LittleEndian(b, opcode); + for (int i = 4; i < length; i++) b[i] = (byte)(seed + i * 7); + return b; + } + + private static void Case(string name) + { + _case = name; + Console.WriteLine($"- {name}"); + } + + private static void Eq(T actual, T expected, string what) => + Check(EqualityComparer.Default.Equals(actual, expected), $"{what}: expected {expected}, got {actual}"); + + private static void Check(bool ok, string what) + { + _checks++; + if (ok) return; + _failed++; + Console.WriteLine($" FAIL [{_case}] {what}"); + } + + // ── datagram walk ─────────────────────────────────────────────────────── + + private static void WalkPlain() + { + Case("walk: one fragment, no optional headers"); + byte[] d = Datagram.Frags(new Frag(1, 1, 0, Msg(40))); + Eq(Walk(d, out int s, out int e), PacketWalk.Ok, "status"); + Eq(s, 20, "fragments start after the 20-byte header"); + Eq(e, d.Length, "fragments end at the datagram end"); + + Case("walk: no BlobFragments flag (ack only)"); + byte[] ack = Datagram.Build(Datagram.AckSequence); + Eq(Walk(ack, out _, out _), PacketWalk.NoFragments, "status"); + } + + private static void WalkOptionalHeaders() + { + Case("walk: ack + time sync + echo response + flow before the fragments"); + uint flags = Datagram.AckSequence | Datagram.TimeSync | Datagram.EchoResponse | Datagram.Flow; + byte[] d = Datagram.Build(flags, 0, null, new Frag(1, 1, 0, Msg(30))); + Eq(Walk(d, out int s, out _), PacketWalk.Ok, "status"); + Eq(s, 20 + 4 + 8 + 8 + 6, "fragment start skips 26 bytes of optional headers"); + + Case("walk: reject-retransmit list (u32 count + ids)"); + byte[] r = Datagram.Build(Datagram.RejectRetransmit | Datagram.AckSequence, 3, null, new Frag(1, 1, 0, Msg(12))); + Eq(Walk(r, out s, out _), PacketWalk.Ok, "status"); + Eq(s, 20 + 4 + 12 + 4, "start after the list and the ack"); + + Case("walk: a header this reader can't size (referral) is skipped, not guessed"); + byte[] referral = Datagram.Build(Datagram.Referral, 0, null, new Frag(1, 1, 0, Msg(12))); + Eq(Walk(referral, out _, out _), PacketWalk.UnknownOptional, "status"); + } + + private static void WalkBadDatagrams() + { + Case("walk: malformed datagrams are rejected whole"); + Eq(Walk(new byte[10], out _, out _), PacketWalk.Malformed, "shorter than a header"); + byte[] good = Datagram.Frags(new Frag(1, 1, 0, Msg(40))); + Eq(Walk(good[..^1], out _, out _), PacketWalk.Malformed, "header size runs past the bytes received"); + byte[] longer = Datagram.Build(0, 0, 40 + 16 + 4, new Frag(1, 1, 0, Msg(40))); + Eq(Walk(longer, out _, out _), PacketWalk.Malformed, "header size larger than the datagram"); + byte[] fragTooBig = Datagram.Frags(new Frag(1, 1, 0, Msg(40), SizeOverride: 16 + 41)); + Eq(Walk(fragTooBig, out _, out _), PacketWalk.Malformed, "fragment size past the end"); + byte[] fragTooSmall = Datagram.Frags(new Frag(1, 1, 0, Msg(40), SizeOverride: 15)); + Eq(Walk(fragTooSmall, out _, out _), PacketWalk.Malformed, "fragment size under its header"); + byte[] gap = Datagram.Build(0, 0, 40 + 16 + 3, new Frag(1, 1, 0, Msg(40))); + Array.Resize(ref gap, gap.Length + 3); + Eq(Walk(gap, out _, out _), PacketWalk.Malformed, "fragments don't tile the declared size"); + byte[] none = Datagram.Build(Datagram.BlobFragments); + Eq(Walk(none, out _, out _), PacketWalk.Malformed, "fragment flag with no fragment"); + + var r = new FragmentReassembler(); + var c = new Collect(); + Feed(r, good[..^1], c); + Feed(r, longer, c); + Eq(c.Messages.Count, 0, "nothing delivered from malformed datagrams"); + Eq(r.PacketsMalformed, 2L, "malformed counter"); + } + + /// + /// One datagram written out byte by byte: packet seq 5, flags 0x4004 (ack + fragments), + /// size 44, ack 4; fragment seq 0x10, id 0x80000001, count 1, size 40, index 0, queue 10; + /// message HearEmote 0x01E0 from 0x50000002 "Bob": "waves." + /// + private static void GoldenHexDatagram() + { + Case("golden datagram: HearEmote, hand-written bytes"); + byte[] d = Convert.FromHexString( + "05000000" + "04400000" + "00000000" + "0100" + "0000" + "2C00" + "0000" + // header + "04000000" + // ack + "10000000" + "01000080" + "0100" + "2800" + "0000" + "0A00" + // fragment header + "E0010000" + "02000050" + "0300" + "426F62" + "000000" + "0600" + "77617665732E"); // message + Eq(d.Length, 64, "64 bytes"); + var r = new FragmentReassembler(); + var c = new Collect(); + Feed(r, d, c); + Eq(c.Messages.Count, 1, "one message"); + if (c.Messages.Count != 1) return; + Eq(c.Messages[0].Seq, 0x10u, "fragment sequence"); + Check(ServerMessage.TryFromWire(c.Messages[0].Bytes, out ServerMessage m), "wraps"); + Eq(m.Opcode, ServerOpcode.HearEmote, "opcode"); + NetMessageInfo info = NetMessages.Inspect(m); + Check(info.Parsed && info.Leftover == 0, $"parsed with nothing left ({info.Kind} parsed={info.Parsed} leftover={info.Leftover})"); + var e = info.Value as HearEmote; + Eq(e?.SenderId, 0x50000002u, "sender"); + Eq(e?.SenderName, "Bob", "name"); + Eq(e?.Text, "waves.", "text"); + } + + // ── reassembly ────────────────────────────────────────────────────────── + + private static void SingleFragment() + { + Case("one-fragment message is delivered as is"); + var r = new FragmentReassembler(); + var c = new Collect(); + byte[] m = Msg(100, 0xF7B0); + Feed(r, Datagram.Frags(new Frag(5, 1, 0, m)), c); + Eq(c.Messages.Count, 1, "delivered"); + Check(c.Messages.Count == 1 && c.Messages[0].Bytes.AsSpan().SequenceEqual(m), "bytes intact"); + Eq(r.MultiFragmentMessages, 0L, "not counted as multi-fragment"); + } + + private static void MultiFragmentInOrder() + { + Case("multi-fragment message, fragments in order, one per datagram"); + var r = new FragmentReassembler(); + var c = new Collect(); + byte[] m = Msg(448 * 3 + 17, 0xF7B0); + foreach (Frag f in Datagram.Split(9, m)) + { + Eq(c.Messages.Count, 0, $"nothing before the last fragment (index {f.Index})"); + Feed(r, Datagram.Frags(f), c); + } + Eq(c.Messages.Count, 1, "delivered once complete"); + Check(c.Messages.Count == 1 && c.Messages[0].Bytes.AsSpan().SequenceEqual(m), "bytes reassembled exactly"); + Eq(r.PartialCount, 0, "slot freed"); + } + + private static void MultiFragmentOutOfOrder() + { + Case("multi-fragment message, fragments reversed and shuffled"); + var rng = new Random(1234); + for (int trial = 0; trial < 50; trial++) + { + var r = new FragmentReassembler(); + var c = new Collect(); + byte[] m = Msg(rng.Next(449, 448 * 20), 0xF7B0, (byte)trial); + Frag[] frags = Datagram.Split((uint)(100 + trial), m); + if (trial == 0) Array.Reverse(frags); else rng.Shuffle(frags); + foreach (Frag f in frags) Feed(r, Datagram.Frags(f), c); + if (c.Messages.Count != 1 || !c.Messages[0].Bytes.AsSpan().SequenceEqual(m)) + { + Check(false, $"trial {trial}: {frags.Length} fragments not reassembled exactly ({c.Messages.Count} delivered)"); + return; + } + } + Check(true, "50 random orders reassembled exactly"); + + Case("uneven fragment sizes still pack together"); + var r2 = new FragmentReassembler(); + var c2 = new Collect(); + byte[] whole = Msg(300, 0xF7B0); + Feed(r2, Datagram.Frags(new Frag(77, 3, 2, whole[250..])), c2); + Feed(r2, Datagram.Frags(new Frag(77, 3, 0, whole[..100])), c2); + Feed(r2, Datagram.Frags(new Frag(77, 3, 1, whole[100..250])), c2); + Check(c2.Messages.Count == 1 && c2.Messages[0].Bytes.AsSpan().SequenceEqual(whole), "100 + 150 + 50 bytes"); + } + + private static void DuplicateFragmentsAndRetransmits() + { + Case("duplicate fragments and retransmitted datagrams"); + var r = new FragmentReassembler(); + var c = new Collect(); + byte[] m = Msg(1000, 0xF7B0); + Frag[] f = Datagram.Split(20, m); + Feed(r, Datagram.Frags(f[0]), c); + Feed(r, Datagram.Frags(f[0]), c); // duplicate while partial + Feed(r, Datagram.Build(Datagram.Retransmission, 0, null, f[1]), c); + Feed(r, Datagram.Frags(f[2]), c); + Eq(c.Messages.Count, 1, "delivered once"); + Eq(r.DuplicateFragments, 1L, "one duplicate while partial"); + foreach (Frag x in f) Feed(r, Datagram.Build(Datagram.Retransmission, 0, null, x), c); // whole message again + Eq(c.Messages.Count, 1, "a retransmitted complete message isn't delivered twice"); + Feed(r, Datagram.Frags(new Frag(21, 1, 0, Msg(20))), c); + Feed(r, Datagram.Frags(new Frag(21, 1, 0, Msg(20))), c); + Eq(c.Messages.Count, 2, "one-fragment message delivered once"); + Eq(r.DuplicateMessages, 1L, "duplicate one-fragment message counted"); + Check(c.Messages.Count == 2 && c.Messages[0].Bytes.AsSpan().SequenceEqual(m), "bytes intact"); + } + + private static void MissingFragmentGoesStale() + { + Case("a message missing a fragment is dropped after StaleMs, then a late fragment can't revive it"); + var r = new FragmentReassembler(); + var c = new Collect(); + Frag[] f = Datagram.Split(30, Msg(1500, 0xF7B0)); + Feed(r, Datagram.Frags(f[0]), c); + Feed(r, Datagram.Frags(f[1]), c); + Eq(r.PartialCount, 1, "one partial"); + _now += FragmentReassembler.StaleMs + 1; + Feed(r, Datagram.Frags(new Frag(31, 1, 0, Msg(10))), c); // any traffic runs the eviction + Eq(r.PartialCount, 0, "evicted"); + Eq(r.EvictedStale, 1L, "stale counter"); + Feed(r, Datagram.Frags(f[2]), c); + Feed(r, Datagram.Frags(f[3]), c); + Eq(c.Messages.Count(m => m.Seq == 30), 0, "never delivered incomplete"); + Eq(r.PartialCount, 0, "late fragments don't start a new partial"); + Eq(r.DuplicateFragments, 2L, "they count as fragments of a finished sequence"); + } + + private static void Oversized() + { + Case("oversized messages are dropped and remembered"); + var r = new FragmentReassembler(); + var c = new Collect(); + Feed(r, Datagram.Frags(new Frag(40, FragmentReassembler.MaxFragments + 1, 0, Msg(448))), c); + Eq(r.Oversized, 1L, "too many fragments"); + Eq(r.PartialCount, 0, "no slot taken"); + Feed(r, Datagram.Frags(new Frag(40, FragmentReassembler.MaxFragments + 1, 1, Msg(448))), c); + Eq(r.DuplicateFragments, 1L, "its other fragments are ignored as done"); + + byte[] big = Msg(FragmentReassembler.FragmentStride + 1, 0xF7B0); + Feed(r, Datagram.Frags(new Frag(41, 2, 0, Msg(448))), c); + Feed(r, Datagram.Frags(new Frag(41, 2, 1, big)), c); + Eq(r.Oversized, 2L, "fragment body over the stride"); + Eq(r.PartialCount, 0, "its partial dropped"); + Eq(c.Messages.Count, 0, "nothing delivered"); + + Case("largest allowed message still reassembles"); + byte[] max = Msg(448 * FragmentReassembler.MaxFragments, 0xF7B0); + foreach (Frag f in Datagram.Split(42, max)) Feed(r, Datagram.Frags(f), c); + Check(c.Messages.Count == 1 && c.Messages[0].Bytes.AsSpan().SequenceEqual(max), $"{max.Length} bytes in {FragmentReassembler.MaxFragments} fragments"); + } + + private static void InconsistentAndBadFragments() + { + Case("bad fragments: index >= count, count 0, count changes mid-message, body under 4 bytes"); + var r = new FragmentReassembler(); + var c = new Collect(); + Feed(r, Datagram.Frags(new Frag(50, 2, 2, Msg(10))), c); + Feed(r, Datagram.Frags(new Frag(51, 0, 0, Msg(10))), c); + Feed(r, Datagram.Frags(new Frag(52, 3, 0, Msg(448))), c); + Feed(r, Datagram.Frags(new Frag(52, 4, 1, Msg(448))), c); + Feed(r, Datagram.Frags(new Frag(53, 1, 0, new byte[] { 1, 2, 3 })), c); + Eq(r.BadFragments, 4L, "four bad fragments counted"); + Eq(c.Messages.Count, 0, "nothing delivered"); + } + + private static void SlotExhaustion() + { + Case("more partial messages than slots: the least recently touched is dropped"); + var r = new FragmentReassembler(); + var c = new Collect(); + for (uint s = 0; s <= FragmentReassembler.MaxPartials; s++) + { + _now += 1; + Feed(r, Datagram.Frags(new Frag(60 + s, 2, 0, Msg(448, 0xF7B0, (byte)s))), c); + } + Eq(r.PartialCount, FragmentReassembler.MaxPartials, "slots full"); + Eq(r.EvictedFull, 1L, "one evicted"); + Feed(r, Datagram.Frags(new Frag(60, 2, 1, Msg(100))), c); + Eq(c.Messages.Count(m => m.Seq == 60), 0, "the evicted (oldest) message doesn't complete"); + Eq(r.EvictedFull, 1L, "and its straggler evicts nothing else"); + Feed(r, Datagram.Frags(new Frag(61, 2, 1, Msg(100))), c); + Eq(c.Messages.Count(m => m.Seq == 61), 1, "the next one does"); + } + + private static void SeveralMessagesPerDatagram() + { + Case("several fragments of different messages in one datagram, interleaved"); + var r = new FragmentReassembler(); + var c = new Collect(); + byte[] a = Msg(700, 0xF7B0, 3), b = Msg(30, 0x02BB, 4), d = Msg(900, 0xF745, 5); + Frag[] fa = Datagram.Split(70, a, 400), fd = Datagram.Split(72, d, 400); + Feed(r, Datagram.Frags(fa[0], new Frag(71, 1, 0, b), fd[2]), c); + Feed(r, Datagram.Frags(fd[0], fa[1]), c); + Feed(r, Datagram.Frags(fd[1]), c); + Eq(c.Messages.Count, 3, "three messages"); + Eq(string.Join(",", c.Messages.Select(m => m.Seq)), "71,70,72", "completion order"); + Check(c.Messages.Count == 3 && c.Messages[1].Bytes.AsSpan().SequenceEqual(a) && c.Messages[2].Bytes.AsSpan().SequenceEqual(d), "bytes intact"); + } + + private static void SessionReset() + { + Case("a ConnectRequest (new session) restarts the sequence window"); + var r = new FragmentReassembler(); + var c = new Collect(); + for (uint s = 1; s <= 50; s++) Feed(r, Datagram.Frags(new Frag(s, 1, 0, Msg(8))), c); + Feed(r, Datagram.Frags(new Frag(2, 1, 0, Msg(8))), c); + Eq(c.Messages.Count, 50, "an old sequence is a duplicate within a session"); + Feed(r, Datagram.Build(Datagram.ConnectRequest), c); + Eq(r.SessionResets, 1L, "reset seen"); + Feed(r, Datagram.Frags(new Frag(2, 1, 0, Msg(8))), c); + Eq(c.Messages.Count, 51, "the same sequence is new after the reset"); + } + + private static void DoneWindowSlides() + { + Case("the done window slides: a long-finished sequence is still rejected, recent ones tracked by bit"); + var r = new FragmentReassembler(); + var c = new Collect(); + Feed(r, Datagram.Frags(new Frag(10, 1, 0, Msg(8))), c); + Feed(r, Datagram.Frags(new Frag(10 + FragmentReassembler.DoneWindow + 5, 1, 0, Msg(8))), c); + Feed(r, Datagram.Frags(new Frag(10, 1, 0, Msg(8))), c); + Eq(c.Messages.Count, 2, "far-behind sequence rejected"); + Feed(r, Datagram.Frags(new Frag(20 + FragmentReassembler.DoneWindow, 1, 0, Msg(8))), c); + Eq(c.Messages.Count, 3, "a sequence inside the window that never completed is accepted"); + // A partial that started before many later one-fragment messages still completes. + Frag[] f = Datagram.Split(30000, Msg(900, 0xF7B0)); + Feed(r, Datagram.Frags(f[0]), c); + for (uint s = 30001; s < 30001 + 1000; s++) Feed(r, Datagram.Frags(new Frag(s, 1, 0, Msg(8))), c); + Feed(r, Datagram.Frags(f[1]), c); + Feed(r, Datagram.Frags(f[2]), c); + Eq(c.Messages.Count(m => m.Seq == 30000), 1, "slow multi-fragment message completes behind 1000 newer ones"); + } + + // ── ring ──────────────────────────────────────────────────────────────── + + private static bool Read(PacketRing ring, out byte[] data, out uint stamp) + { + data = Array.Empty(); + if (!ring.TryPeek(out byte* p, out int len, out stamp, out int rel)) return false; + data = new ReadOnlySpan(p, len).ToArray(); + ring.Release(rel); + return true; + } + + private static bool Write(PacketRing ring, byte[] d, uint stamp = 0) + { + fixed (byte* p = d) return ring.TryWrite(p, d.Length, stamp); + } + + private static void RingBasics() + { + Case("ring: FIFO, stamps, too-long rejected"); + var ring = new PacketRing(4096); + Check(Write(ring, Msg(100, 1), 11) && Write(ring, Msg(3, 2), 22), "two writes"); + Check(Read(ring, out byte[] a, out uint sa) && a.Length == 100 && sa == 11, "first back"); + Check(Read(ring, out byte[] b, out uint sb) && b.Length == 3 && sb == 22, "second back"); + Check(!Read(ring, out _, out _), "empty"); + Check(!Write(ring, new byte[PacketRing.MaxDatagram + 1]), "too long refused"); + Eq(ring.DroppedTooLong, 1L, "counted"); + } + + private static void RingWrapAndFull() + { + Case("ring: wraps at the end, drops (never waits) when full"); + var ring = new PacketRing(4096); + int wrote = 0, read = 0; + var rng = new Random(7); + var pending = new Queue(); + for (int i = 0; i < 5000; i++) + { + byte[] d = Msg(rng.Next(20, 500), (uint)i, (byte)i); + if (Write(ring, d)) { pending.Enqueue(d); wrote++; } + if (rng.Next(3) == 0) + while (Read(ring, out byte[] got, out _)) + { + read++; + if (!got.AsSpan().SequenceEqual(pending.Dequeue())) { Check(false, $"datagram {read} corrupted across a wrap"); return; } + } + } + while (Read(ring, out byte[] got, out _)) { read++; if (!got.AsSpan().SequenceEqual(pending.Dequeue())) { Check(false, "tail corrupted"); return; } } + Eq(read, wrote, "everything written was read back intact, in order"); + Check(ring.DroppedFull > 0, $"some writes were refused while full ({ring.DroppedFull})"); + Eq(ring.Written, (long)wrote, "written counter"); + } + + private static void RingCounterWrap() + { + Case("ring: the byte counters wrap past int.MaxValue"); + var ring = new PacketRing(4096, int.MaxValue - 3000); + int ok = 0; + for (int i = 0; i < 200; i++) + { + byte[] d = Msg(100 + i, (uint)i, (byte)i); + if (!Write(ring, d) || !Read(ring, out byte[] got, out _) || !got.AsSpan().SequenceEqual(d)) break; + ok++; + } + Eq(ok, 200, "200 round trips across the wrap"); + Eq(ring.Used, 0, "empty after"); + } + + private static void RingThreaded() + { + Case("ring: one producer thread, one consumer thread, 200k datagrams"); + var ring = new PacketRing(64 * 1024); + const int N = 200_000; + int produced = 0; + var t = new Thread(() => + { + byte[] d = new byte[400]; + for (int i = 0; i < N; i++) + { + int len = 20 + (i % 380); + BinaryPrimitives.WriteInt32LittleEndian(d, i); + d[len - 1] = (byte)i; + while (!Write(ring, d[..len], (uint)i)) Thread.SpinWait(20); // the test retries; the hook drops + produced++; + } + }); + t.Start(); + int expect = 0; + bool ok = true; + var sw = Stopwatch.StartNew(); + while (expect < N && sw.Elapsed.TotalSeconds < 30) + { + if (!Read(ring, out byte[] got, out uint stamp)) { Thread.SpinWait(10); continue; } + int len = 20 + (expect % 380); + if (got.Length != len || BinaryPrimitives.ReadInt32LittleEndian(got) != expect || got[len - 1] != (byte)expect || stamp != (uint)expect) + { + ok = false; + break; + } + expect++; + } + t.Join(); + Check(ok && expect == N, $"all {N} datagrams in order and intact (got {expect})"); + } + + private static void Interest() + { + Case("interest sets"); + var s = new ServerMessageInterest(); + Check(s.IsEmpty, "starts empty"); + uint[] ops = { 0x02BB, 0x01E0 }; + uint[] evs = { 0x02BE, 0x0021 }; + fixed (uint* o = ops) fixed (uint* e = evs) Check(s.Set(o, 2, e, 2), "set"); + Check(s.Wants(0x02BB, 0) && s.Wants(0x01E0, 0), "listed opcodes"); + Check(!s.Wants(0xF745, 0), "unlisted opcode"); + Check(s.Wants(0xF7B0, 0x02BE) && s.Wants(0xF7B0, 0x0021), "listed game events"); + Check(!s.Wants(0xF7B0, 0x02C2), "unlisted game event"); + Check(!s.Wants(0x1_0000, 0), "out-of-range opcode never wanted"); + + uint[] allEv = { 0xF7B0 }; + fixed (uint* o = allEv) Check(s.Set(o, 1, null, 0), "0xF7B0 alone"); + Check(s.Wants(0xF7B0, 0x1234) && !s.Wants(0x02BB, 0), "every game event, nothing else"); + + uint[] all = { 0xFFFFFFFF }; + fixed (uint* o = all) Check(s.Set(o, 1, null, 0), "all"); + Check(s.Wants(0xF745, 0) && s.Wants(0xF7B0, 5), "everything"); + + uint[] bad = { 0x02BB, 0x10000 }; + fixed (uint* o = bad) Check(!s.Set(o, 2, null, 0), "an out-of-range opcode refuses the whole set"); + Check(s.IsEmpty, "and leaves it empty"); + Check(!s.Set(null, 3, null, 0), "null with a count refused"); + Check(s.Set(null, 0, null, 0) && s.IsEmpty, "empty set = off"); + } + + // ── parsers ───────────────────────────────────────────────────────────── + + private static void Strings() + { + Case("String16L: lengths 0-6 pad to 4, Latin-1, long form refused"); + for (int len = 0; len <= 6; len++) + { + string text = new string('x', len); + byte[] b = new Body().Str(text).U32(0xDEADBEEF).ToArray(); + Eq(b.Length % 4, 0, $"length {len} padded"); + var r = new NetReader(b); + Check(r.String16L(out string got) && got == text && r.U32(out uint tail) && tail == 0xDEADBEEF, $"length {len} round trip"); + } + var lat = new NetReader(new Body().Str("Café Æthel").ToArray()); + Check(lat.String16L(out string l) && l == "Café Æthel", "Latin-1 characters"); + var lng = new NetReader(new byte[] { 0xFF, 0xFF, 4, 0, 0, 0, 1, 2, 3, 4 }); + Check(!lng.String16L(out _), "0xFFFF long form refused"); + var shortStr = new NetReader(new byte[] { 10, 0, 1, 2 }); + Check(!shortStr.String16L(out _), "length past the end refused"); + } + + private static NetMessageInfo InspectTop(uint opcode, Body body) + { + ServerMessage.TryFromWire(body.Message(opcode), out ServerMessage m); + return NetMessages.Inspect(m); + } + + private static NetMessageInfo InspectEvent(uint type, Body body) + { + ServerMessage.TryFromWire(body.GameEvent(type), out ServerMessage m); + return NetMessages.Inspect(m); + } + + private static void Clean(NetMessageInfo i, string kind) + { + Eq(i.Kind, kind, "kind"); + Check(i.Known && i.Parsed, $"{kind} parsed"); + Eq(i.Leftover, 0, $"{kind} leftover"); + } + + private static void ChatParsers() + { + Case("HearSpeech 0x02BB"); + var i = InspectTop(0x02BB, new Body().Str("Hello there").Str("Aria").U32(0x50000010).U32(2)); + Clean(i, "HearSpeech"); + var s = (HearSpeech)i.Value!; + Check(s.Text == "Hello there" && s.SenderName == "Aria" && s.SenderId == 0x50000010 && s.ChatType == 2, "fields"); + + Case("HearRangedSpeech 0x02BC"); + i = InspectTop(0x02BC, new Body().Str("Help!").Str("Town Crier").U32(0x7A000001).F32(37.5f).U32(12)); + Clean(i, "HearRangedSpeech"); + var rs = (HearRangedSpeech)i.Value!; + Check(rs.Text == "Help!" && rs.SenderName == "Town Crier" && rs.SenderId == 0x7A000001 && rs.Range == 37.5f && rs.ChatType == 12, "fields"); + + Case("HearEmote 0x01E0 / HearSoulEmote 0x01E2"); + i = InspectTop(0x01E0, new Body().U32(0x50000011).Str("Bren").Str("bows deeply.")); + Clean(i, "HearEmote"); + var e = (HearEmote)i.Value!; + Check(e.SenderId == 0x50000011 && e.SenderName == "Bren" && e.Text == "bows deeply." && !e.Soul, "emote fields"); + i = InspectTop(0x01E2, new Body().U32(0x50000012).Str("Cy").Str("*laughs*")); + Clean(i, "HearSoulEmote"); + Check(((HearEmote)i.Value!).Soul, "soul flag"); + + Case("HearDirectSpeech (tell) game event 0x02BD"); + i = InspectEvent(0x02BD, new Body().Str("psst").Str("Dax").U32(0x50000013).U32(0x50000001).U32(3).U32(0)); + Clean(i, "HearDirectSpeech"); + var t = (HearDirectSpeech)i.Value!; + Check(t.Text == "psst" && t.SenderName == "Dax" && t.SenderId == 0x50000013 && t.TargetId == 0x50000001 && t.ChatType == 3 && t.Flags == 0, "fields"); + + Case("ChannelBroadcast game event 0x0147"); + i = InspectEvent(0x0147, new Body().U32(0x800).Str("").Str("pulling now")); + Clean(i, "ChannelBroadcast"); + var cb = (ChannelBroadcast)i.Value!; + Check(cb.Channel == 0x800 && cb.SenderName == "" && cb.Text == "pulling now", "own line: empty sender"); + } + + private static Body FellowBody(Body b, uint id, string name, uint level, bool shareLoot) + => b.U32(id).U32(1000).U32(10).U32(level).U32(300).U32(250).U32(200).U32(280).U32(240).U32(190).Bool(shareLoot).Str(name); + + private static void FellowshipParsers() + { + Case("FellowshipFullUpdate 0x02BE: members, flags, departed, locks"); + var b = new Body().TableHeader(2); + FellowBody(b, 0x50000001, "Leader Lee", 126, true); + FellowBody(b, 0x50000002, "Bo", 80, false); + b.Str("Hunters").U32(0x50000001).Bool(true).Bool(false).Bool(true).Bool(false); + b.TableHeader(1).U32(0x50000003).I32(1234); + b.TableHeader(1).Str("Lugian Citadel").U32(1).U32(2).U32(3).U32(4).U32(5); + var i = InspectEvent(0x02BE, b); + Clean(i, "FellowshipFullUpdate"); + var f = (FellowshipFullUpdate)i.Value!; + Check(f.Name == "Hunters" && f.LeaderId == 0x50000001 && f.ShareXp && !f.EvenXpSplit && f.Open && !f.Locked, "header fields"); + Eq(f.Fellows.Count, 2, "members"); + var lee = f.Fellows[0]; + Check(lee.Id == 0x50000001 && lee.Name == "Leader Lee" && lee.Level == 126 && lee.XpCached == 1000 && lee.LumCached == 10 && + lee.MaxHealth == 300 && lee.MaxStamina == 250 && lee.MaxMana == 200 && lee.Health == 280 && lee.Stamina == 240 && lee.Mana == 190 && lee.ShareLoot, "fellow fields"); + Check(!f.Fellows[1].ShareLoot && f.Fellows[1].Name == "Bo", "second fellow"); + Check(f.TailParsed && f.RecentlyDeparted.TryGetValue(0x50000003, out int when) && when == 1234 && f.LockNames.SequenceEqual(new[] { "Lugian Citadel" }), "tail"); + + Case("FellowshipFullUpdate whose tail doesn't fit: members still returned, leftover reported"); + var b2 = new Body().TableHeader(1); + FellowBody(b2, 0x50000001, "Solo", 50, true); + b2.Str("One").U32(0x50000001).Bool(false).Bool(true).Bool(false).Bool(true); + b2.Bytes(0x01, 0x02); // a tail this layout doesn't know + i = InspectEvent(0x02BE, b2); + Check(i.Parsed && i.Leftover == 2, $"parsed with 2 leftover (parsed={i.Parsed} leftover={i.Leftover})"); + var f2 = (FellowshipFullUpdate)i.Value!; + Check(!f2.TailParsed && f2.Fellows.Count == 1 && f2.Locked, "main fields kept, tail flagged unread"); + + Case("FellowshipUpdateFellow 0x02C0"); + // fellow id, xp, lum, level, max h/s/m, current h/s/m, share loot, name, update type + var u = new Body().U32(0x50000002).U32(1000).U32(10).U32(81).U32(300).U32(250).U32(200).U32(100).U32(50).U32(25).Bool(false).Str("Bo").U32(3); + i = InspectEvent(0x02C0, u); + Clean(i, "FellowshipUpdateFellow"); + var uf = (FellowshipUpdateFellow)i.Value!; + Check(uf.Fellow.Id == 0x50000002 && uf.Fellow.Level == 81 && uf.Fellow.Health == 100 && uf.UpdateType == 3, "fields"); + + Case("FellowshipQuit 0x00A3, FellowshipDismiss 0x00A4, FellowshipDisband 0x02BF"); + i = InspectEvent(0x00A3, new Body().U32(0x50000004)); + Clean(i, "FellowshipQuit"); + Check(((FellowshipMemberLeft)i.Value!).FellowId == 0x50000004 && !((FellowshipMemberLeft)i.Value!).Dismissed, "quit"); + i = InspectEvent(0x00A4, new Body().U32(0x50000005)); + Clean(i, "FellowshipDismiss"); + Check(((FellowshipMemberLeft)i.Value!).Dismissed, "dismiss"); + i = InspectEvent(0x02BF, new Body()); + Clean(i, "FellowshipDisband"); + } + + private static void FriendsAndAllegiance() + { + Case("FriendsUpdate 0x0021: full list"); + var b = new Body().U32(2) + .U32(0x50000020).Bool(true).Bool(false).Str("Ana").U32List(0x50000001).U32List() + .U32(0x50000021).Bool(false).Bool(true).Str("Bertram").U32List().U32List(0x50000001, 0x50000002) + .U32(FriendsUpdate.Full); + var i = InspectEvent(0x0021, b); + Clean(i, "FriendsUpdate"); + var fu = (FriendsUpdate)i.Value!; + Eq(fu.Friends.Count, 2, "two friends"); + Check(fu.Friends[0].Id == 0x50000020 && fu.Friends[0].Online && !fu.Friends[0].AppearOffline && fu.Friends[0].Name == "Ana" && + fu.Friends[0].OutFriends.SequenceEqual(new uint[] { 0x50000001 }) && fu.Friends[0].InFriends.Length == 0, "first"); + Check(!fu.Friends[1].Online && fu.Friends[1].AppearOffline && fu.Friends[1].InFriends.Length == 2, "second"); + Eq(fu.UpdateType, FriendsUpdate.Full, "update type"); + + Case("FriendsUpdate: login change for one friend"); + i = InspectEvent(0x0021, new Body().U32(1).U32(0x50000020).Bool(false).Bool(false).Str("Ana").U32List().U32List().U32(FriendsUpdate.LoginChange)); + Clean(i, "FriendsUpdate"); + Check(((FriendsUpdate)i.Value!).UpdateType == FriendsUpdate.LoginChange, "type 4"); + + Case("FriendsUpdate: absurd count refused without allocating it"); + i = InspectEvent(0x0021, new Body().U32(0x7FFFFFFF).U32(0)); + Check(i.Known && !i.Parsed, "refused"); + + Case("AllegianceLoginNotification 0x027A"); + i = InspectEvent(0x027A, new Body().U32(0x50000030).Bool(true)); + Clean(i, "AllegianceLoginNotification"); + var a = (AllegianceLoginNotification)i.Value!; + Check(a.CharacterId == 0x50000030 && a.LoggedIn, "fields"); + } + + private static void SystemTextAndConfirmation() + { + Case("PopUpString 0x0004, TransientString 0x02EB"); + var i = InspectEvent(0x0004, new Body().Str("You have been booted.")); + Clean(i, "PopUpString"); + Check(((SystemText)i.Value!).Text == "You have been booted." && !((SystemText)i.Value!).Transient, "popup"); + i = InspectEvent(0x02EB, new Body().Str("You're too busy!")); + Clean(i, "TransientString"); + Check(((SystemText)i.Value!).Transient, "transient"); + + Case("ConfirmationRequest 0x0274"); + i = InspectEvent(0x0274, new Body().U32(4).U32(0x1234).Str("Ana has invited you to join a fellowship.")); + Clean(i, "ConfirmationRequest"); + var c = (ConfirmationRequest)i.Value!; + Check(c.ConfirmationType == 4 && c.ContextId == 0x1234 && c.Text.StartsWith("Ana has invited"), "fields"); + + Case("unknown messages are reported as unknown"); + i = InspectTop(0xF745, new Body().U32(1)); + Check(!i.Known, "top-level"); + i = InspectEvent(0x02C2, new Body().U32(1)); + Check(!i.Known, "game event"); + } + + private static void TruncationNeverThrows() + { + Case("every parser, every truncation of its fixture: false, no exception"); + var fixtures = new List<(string, byte[])> + { + ("speech", new Body().Str("Hello there").Str("Aria").U32(1).U32(2).Message(0x02BB)), + ("ranged", new Body().Str("Help!").Str("Crier").U32(1).F32(1).U32(2).Message(0x02BC)), + ("emote", new Body().U32(1).Str("Bren").Str("bows.").Message(0x01E0)), + ("tell", new Body().Str("psst").Str("Dax").U32(1).U32(2).U32(3).U32(0).GameEvent(0x02BD)), + ("channel", new Body().U32(1).Str("A").Str("B").GameEvent(0x0147)), + ("friends", new Body().U32(1).U32(1).Bool(true).Bool(false).Str("Ana").U32List(5).U32List(6).U32(0).GameEvent(0x0021)), + ("allegiance", new Body().U32(1).Bool(true).GameEvent(0x027A)), + ("confirm", new Body().U32(4).U32(5).Str("ok?").GameEvent(0x0274)), + ("popup", new Body().Str("hi").GameEvent(0x0004)), + ("update fellow", new Body().U32(1).U32(1).U32(1).U32(1).U32(1).U32(1).U32(1).U32(1).U32(1).U32(1).Bool(true).Str("Bo").U32(1).GameEvent(0x02C0)), + ("quit", new Body().U32(1).GameEvent(0x00A3)), + }; + var full = new Body().TableHeader(1); + FellowBody(full, 1, "Lee", 5, true); + full.Str("F").U32(1).Bool(true).Bool(true).Bool(true).Bool(true).TableHeader(0).TableHeader(0); + fixtures.Add(("fellowship", full.GameEvent(0x02BE))); + + int cuts = 0; + foreach ((string name, byte[] wire) in fixtures) + { + ServerMessage.TryFromWire(wire, out ServerMessage whole); + NetMessageInfo w = NetMessages.Inspect(whole); + if (!w.Parsed || w.Leftover != 0) { Check(false, $"{name}: full fixture should parse cleanly"); continue; } + int headerLen = whole.IsGameEvent ? 16 : 4; + for (int len = headerLen; len < wire.Length; len++) + { + try + { + ServerMessage.TryFromWire(wire.AsSpan(0, len), out ServerMessage m); + NetMessageInfo i = NetMessages.Inspect(m); + // A cut on a string's padding or the fellowship tail can still parse; it must then report what it used. + if (i.Parsed && name != "fellowship" && i.Leftover != 0) Check(false, $"{name} cut at {len}: parsed but leftover {i.Leftover}"); + cuts++; + } + catch (Exception ex) + { + Check(false, $"{name} cut at {len} threw {ex.GetType().Name}"); + } + } + } + Check(cuts > 300, $"{cuts} truncations tried"); + } + + private static void EndToEndGameEvents() + { + Case("end to end: a 3-datagram fellowship update, out of order, through ring and reassembler to the parser"); + var b = new Body().TableHeader(9); + for (uint n = 0; n < 9; n++) FellowBody(b, 0x50000100 + n, $"Member number {n} with a long name", 100 + n, n % 2 == 0); + b.Str("A fellowship with a long name").U32(0x50000100).Bool(true).Bool(true).Bool(false).Bool(false).TableHeader(0).TableHeader(0); + byte[] wire = b.GameEvent(0x02BE, 0x50000100, 42); + Frag[] frags = Datagram.Split(500, wire); + Check(frags.Length >= 2, $"{wire.Length} bytes needs {frags.Length} fragments"); + var ring = new PacketRing(4096); + var order = frags.Reverse().ToArray(); + foreach (Frag f in order) Write(ring, Datagram.Build(Datagram.AckSequence | Datagram.TimeSync, 0, null, f)); + var r = new FragmentReassembler(); + var c = new Collect(); + while (ring.TryPeek(out byte* p, out int len, out _, out int rel)) + { + r.ProcessDatagram(p, len, _now, c); + ring.Release(rel); + } + Eq(c.Messages.Count, 1, "one message"); + if (c.Messages.Count != 1) return; + ServerMessage.TryFromWire(c.Messages[0].Bytes, out ServerMessage m); + Check(m.IsGameEvent && m.EventObjectId == 0x50000100 && m.EventSequence == 42 && m.EventType == 0x02BE, "game event header"); + Check(FellowshipFullUpdate.TryParse(m.EventBody, out var fs, out int used) && used == m.EventBody.Length, "parsed whole"); + Check(fs != null && fs.Fellows.Count == 9 && fs.Fellows[8].Name == "Member number 8 with a long name" && fs.TailParsed, "all members"); + } + + // ── replay of captures ────────────────────────────────────────────────── + + private static void Replay(string path) + { + Case($"replay {Path.GetFileName(path)}"); + byte[] file; + try { file = File.ReadAllBytes(path); } + catch (Exception ex) { Check(false, $"read failed: {ex.Message}"); return; } + if (file.Length < 4 || file[0] != 'R' || file[1] != 'N' || file[2] != 'C' || file[3] != '1') + { + Check(false, "not an RNC1 capture"); + return; + } + var r = new FragmentReassembler(); + var c = new Collect(); + int pos = 4, datagrams = 0; + while (pos + 6 <= file.Length) + { + uint stamp = BinaryPrimitives.ReadUInt32LittleEndian(file.AsSpan(pos)); + int len = BinaryPrimitives.ReadUInt16LittleEndian(file.AsSpan(pos + 4)); + pos += 6; + if (pos + len > file.Length) { Check(false, $"truncated record at {pos}"); break; } + fixed (byte* p = &file[pos]) + r.ProcessDatagram(p, len, stamp, c); + pos += len; + datagrams++; + } + var byKind = new SortedDictionary(); + var opcodes = new Dictionary(); + foreach (var (_, bytes) in c.Messages) + { + ServerMessage.TryFromWire(bytes, out ServerMessage m); + string key = m.IsGameEvent ? $"F7B0/{m.EventType:X4}" : $"{m.Opcode:X4}"; + opcodes[key] = opcodes.GetValueOrDefault(key) + 1; + NetMessageInfo i = NetMessages.Inspect(m); + if (!i.Known) continue; + var k = byKind.GetValueOrDefault(i.Kind); + byKind[i.Kind] = (k.Ok + (i.Parsed ? 1 : 0), k.Failed + (i.Parsed ? 0 : 1), k.Leftover + (i.Parsed && i.Leftover != 0 ? 1 : 0)); + if (!i.Parsed || i.Leftover != 0) + Console.WriteLine($" {i.Kind} parsed={i.Parsed} leftover={i.Leftover} bytes={Convert.ToHexString(bytes.AsSpan(0, Math.Min(bytes.Length, 64)))}"); + } + Console.WriteLine($" {datagrams} datagrams -> {r.Messages} messages ({r.MultiFragmentMessages} multi-fragment); malformed {r.PacketsMalformed}, " + + $"unknown header {r.PacketsUnknownOptional}, dup {r.DuplicateFragments}, bad {r.BadFragments}, stale {r.EvictedStale}, {r.PartialCount} left partial"); + Console.WriteLine($" top opcodes: {string.Join(" ", opcodes.OrderByDescending(o => o.Value).Take(15).Select(o => $"{o.Key}x{o.Value}"))}"); + foreach (var (kind, v) in byKind) + Console.WriteLine($" {kind}: {v.Ok} ok, {v.Failed} failed, {v.Leftover} with leftover"); + Check(r.PacketsMalformed == 0, "no malformed datagrams in a real capture"); + Check(byKind.Values.All(v => v.Failed == 0), "every known message parsed"); + } + + // ── performance ───────────────────────────────────────────────────────── + + private static void Performance() + { + Console.WriteLine(); + Console.WriteLine("Performance (synthetic server traffic; Release build, this machine):"); + + // A mix shaped like play: mostly one-fragment messages of 20-300 bytes, packed 1-3 per + // datagram, plus a 2-8 fragment message every ~25 datagrams; acks and time sync on many. + var rng = new Random(99); + var datagrams = new List(); + uint seq = 1; + int msgCount = 0; + while (datagrams.Count < 50_000) + { + if (rng.Next(25) == 0) + { + byte[] big = Msg(rng.Next(900, 448 * 8), 0xF7B0, (byte)seq); + foreach (Frag f in Datagram.Split(seq++, big)) datagrams.Add(Datagram.Build(Datagram.AckSequence, 0, null, f)); + msgCount++; + continue; + } + int n = rng.Next(1, 4); + var frags = new Frag[n]; + int room = 448; + for (int k = 0; k < n; k++) + { + int len = Math.Min(rng.Next(20, 300), room - 16 * (n - k)); + if (len < 8) len = 8; + room -= len + 16; + frags[k] = new Frag(seq++, 1, 0, Msg(len, 0xF749, (byte)k)); + msgCount++; + } + uint flags = rng.Next(4) == 0 ? Datagram.AckSequence | Datagram.TimeSync : Datagram.AckSequence; + datagrams.Add(Datagram.Build(flags, 0, null, frags)); + } + long totalBytes = datagrams.Sum(d => (long)d.Length); + var pinned = datagrams.Select(d => GC.AllocateArray(d.Length, pinned: true)).ToArray(); + for (int i = 0; i < pinned.Length; i++) datagrams[i].CopyTo(pinned[i], 0); + + // 1) Receive side: what the detour does while capturing (flags check + ring write), + // timed in batches of 1024 datagrams (the ring is emptied between batches, untimed). + var ring = new PacketRing(512 * 1024); + const int Rounds = 20, Batch = 1024; + long copies = 0, hookTicks = 0; + for (int round = 0; round < Rounds + 2; round++) + { + bool timed = round >= 2; + for (int i0 = 0; i0 < pinned.Length; i0 += Batch) + { + int i1 = Math.Min(pinned.Length, i0 + Batch); + long t0 = Stopwatch.GetTimestamp(); + for (int i = i0; i < i1; i++) + { + byte[] d = pinned[i]; + fixed (byte* p = d) + { + uint flags = AcPacketWire.ReadU32(p + 4); + if ((flags & (PacketFlags.BlobFragments | PacketFlags.ConnectRequest)) != 0) + ring.TryWrite(p, d.Length, 0); + } + } + long t1 = Stopwatch.GetTimestamp(); + if (timed) { hookTicks += t1 - t0; copies += i1 - i0; } + ring.Clear(); + } + } + double tickNs = 1e9 / Stopwatch.Frequency; + double hookNs = hookTicks * tickNs / copies; + Console.WriteLine($" receive hook copy: {hookNs:0} ns per datagram (avg {totalBytes / datagrams.Count} bytes), {copies:N0} datagrams; ring drops {ring.DroppedFull}"); + + // 2) Pump side: ring read + reassembly into a counting sink, timed per drained batch. + var r = new FragmentReassembler(); + var sink = new CountOnly(); + long allocBefore = 0, processed = 0, pumpTicks = 0, msgsTimed = 0, multiTimed = 0; + for (int round = 0; round < Rounds + 2; round++) + { + bool timed = round >= 2; + r.Reset(); + if (round == 2) allocBefore = GC.GetAllocatedBytesForCurrentThread(); + long m0 = r.Messages, mm0 = r.MultiFragmentMessages; + for (int i0 = 0; i0 < pinned.Length; i0 += Batch) + { + int i1 = Math.Min(pinned.Length, i0 + Batch); + for (int i = i0; i < i1; i++) + fixed (byte* p = pinned[i]) + ring.TryWrite(p, pinned[i].Length, 0); + long t0 = Stopwatch.GetTimestamp(); + while (ring.TryPeek(out byte* rp, out int len, out _, out int rel)) + { + r.ProcessDatagram(rp, len, 1000, sink); + ring.Release(rel); + } + long t1 = Stopwatch.GetTimestamp(); + if (timed) { pumpTicks += t1 - t0; processed += i1 - i0; } + } + if (timed) { msgsTimed += r.Messages - m0; multiTimed += r.MultiFragmentMessages - mm0; } + } + long allocAfter = GC.GetAllocatedBytesForCurrentThread(); + double pumpNs = pumpTicks * tickNs / processed; + Console.WriteLine($" pump (ring read + reassembly): {pumpNs:0} ns per datagram, {pumpTicks * tickNs / msgsTimed:0} ns per message; " + + $"{msgsTimed / Rounds:N0} messages per round of {pinned.Length:N0} datagrams ({multiTimed / Rounds:N0} multi-fragment)"); + Console.WriteLine($" steady-state allocation: {(allocAfter - allocBefore) / (double)processed:0.00} bytes per datagram over {processed:N0} datagrams"); + + // 3) What a busy minute costs: ~100 datagrams/s is heavy play, 400/s a portal into a town. + Console.WriteLine($" at 400 datagrams/s: hook {hookNs * 400 / 1000:0.0} us/s on the receive thread, pump {pumpNs * 400 / 1000:0.0} us/s"); + Console.WriteLine(" stream off: the detour adds one volatile bool read (ServerMessageStream.OnDatagram returns at once)."); + } +} diff --git a/tools/NetMessageTests/WireBuilder.cs b/tools/NetMessageTests/WireBuilder.cs new file mode 100644 index 0000000..5a5877c --- /dev/null +++ b/tools/NetMessageTests/WireBuilder.cs @@ -0,0 +1,91 @@ +using System.Buffers.Binary; +using System.Text; + +namespace NetMessageTests; + +/// Little-endian writer for message bodies, in the AC wire types the parsers read. +internal sealed class Body +{ + private readonly List _b = new(); + + public byte[] ToArray() => _b.ToArray(); + public int Length => _b.Count; + + public Body U16(ushort v) { Span t = stackalloc byte[2]; BinaryPrimitives.WriteUInt16LittleEndian(t, v); _b.AddRange(t.ToArray()); return this; } + public Body U32(uint v) { Span t = stackalloc byte[4]; BinaryPrimitives.WriteUInt32LittleEndian(t, v); _b.AddRange(t.ToArray()); return this; } + public Body I32(int v) => U32(unchecked((uint)v)); + public Body F32(float v) => U32(BitConverter.SingleToUInt32Bits(v)); + public Body Bool(bool v) => U32(v ? 1u : 0u); + public Body Bytes(params byte[] v) { _b.AddRange(v); return this; } + + /// u16 length, Latin-1 bytes, zero padding so 2 + length is a multiple of 4. + public Body Str(string s) + { + byte[] raw = Encoding.Latin1.GetBytes(s); + U16((ushort)raw.Length); + _b.AddRange(raw); + for (int pad = (4 - ((2 + raw.Length) & 3)) & 3; pad > 0; pad--) _b.Add(0); + return this; + } + + public Body U32List(params uint[] v) { U32((uint)v.Length); foreach (uint x in v) U32(x); return this; } + public Body TableHeader(int count, int buckets = 32) => U16((ushort)count).U16((ushort)buckets); + + /// A whole top-level message: u32 opcode then this body. + public byte[] Message(uint opcode) => new Body().U32(opcode).Bytes(ToArray()).ToArray(); + + /// A whole game event message: 0xF7B0, object id, sequence, event type, this body. + public byte[] GameEvent(uint eventType, uint objectId = 0x50000001, uint sequence = 7) + => new Body().U32(0xF7B0).U32(objectId).U32(sequence).U32(eventType).Bytes(ToArray()).ToArray(); +} + +/// One fragment for . +internal readonly record struct Frag(uint Sequence, ushort Count, ushort Index, byte[] Data, uint Id = 0x80000001, ushort Queue = 10, int? SizeOverride = null); + +/// Builds server-to-client datagrams: 20-byte header, optional headers, fragments. +internal static class Datagram +{ + public const uint BlobFragments = 0x4, AckSequence = 0x4000, TimeSync = 0x01000000, EchoResponse = 0x04000000, + Flow = 0x08000000, RejectRetransmit = 0x2000, Referral = 0x800, ConnectRequest = 0x40000, Retransmission = 0x1; + + private static uint _packetSeq = 100; + + /// + /// Optional headers are written for the flags given (fixed sizes, zero contents; a reject + /// list gets entries). BlobFragments is added when frags are given. + /// + public static byte[] Build(uint flags, int rejectCount = 0, int? sizeOverride = null, params Frag[] frags) + { + if (frags.Length > 0) flags |= BlobFragments; + var after = new Body(); + if ((flags & RejectRetransmit) != 0) { after.U32((uint)rejectCount); for (int i = 0; i < rejectCount; i++) after.U32((uint)(i + 1)); } + if ((flags & AckSequence) != 0) after.U32(99); + if ((flags & ConnectRequest) != 0) after.Bytes(new byte[32]); + if ((flags & TimeSync) != 0) after.Bytes(new byte[8]); + if ((flags & EchoResponse) != 0) after.Bytes(new byte[8]); + if ((flags & Flow) != 0) after.Bytes(new byte[6]); + foreach (Frag f in frags) + { + after.U32(f.Sequence).U32(f.Id).U16(f.Count).U16((ushort)(f.SizeOverride ?? (16 + f.Data.Length))).U16(f.Index).U16(f.Queue); + after.Bytes(f.Data); + } + byte[] tail = after.ToArray(); + var d = new Body().U32(_packetSeq++).U32(flags).U32(0).U16(1).U16(0).U16((ushort)(sizeOverride ?? tail.Length)).U16(0); + return d.Bytes(tail).ToArray(); + } + + public static byte[] Frags(params Frag[] frags) => Build(0, 0, null, frags); + + /// Splits a message into fragments of at most bytes (448 like the server). + public static Frag[] Split(uint sequence, byte[] message, int chunk = 448) + { + int count = Math.Max(1, (message.Length + chunk - 1) / chunk); + var list = new Frag[count]; + for (int i = 0; i < count; i++) + { + int off = i * chunk; + list[i] = new Frag(sequence, (ushort)count, (ushort)i, message.AsSpan(off, Math.Min(chunk, message.Length - off)).ToArray()); + } + return list; + } +} diff --git a/tools/PlateSizingTests/PlateSizingTests.csproj b/tools/PlateSizingTests/PlateSizingTests.csproj new file mode 100644 index 0000000..19baa44 --- /dev/null +++ b/tools/PlateSizingTests/PlateSizingTests.csproj @@ -0,0 +1,27 @@ + + + + + Exe + net10.0 + enable + enable + true + PlateSizingTests + + + + + + + + diff --git a/tools/PlateSizingTests/Program.cs b/tools/PlateSizingTests/Program.cs new file mode 100644 index 0000000..2960f34 --- /dev/null +++ b/tools/PlateSizingTests/Program.cs @@ -0,0 +1,231 @@ +using System.Globalization; +using RynthCore.Engine.ImGuiBackend.Hud; +using RynthCore.Engine.UI.Data; + +namespace RynthCore.Engine.UI +{ + /// Stub: counts saves, never runs them (no file I/O in the tests). + internal static class UiBackgroundWriter + { + public static int Enqueued; + public static void Enqueue(string label, Action work) => Enqueued++; + } +} + +namespace PlateSizingTests +{ + using S = MonsterHudSettings; + + /// + /// The nameplate sizing settings (per plate type: bar width, bar height, text size) and the + /// ArgbOpacity helper behind the Vision overlay opacity sliders. + /// + internal static class Program + { + private static int _checks, _failed; + private static string _case = ""; + + private static int Main() + { + DefaultsAreTodaysLook(); + RoundTrip(); + OldFileLoads(); + Clamping(); + ResetSizesOnlyTouchesSizes(); + ResetAllResetsSizes(); + RefactorKeepsEveryKey(); + OpacityDefaults(); + OpacityRoundTripsEveryAlpha(); + OpacitySetKeepsRgb(); + + Console.WriteLine(); + Console.WriteLine($"{_checks - _failed}/{_checks} checks passed."); + Console.WriteLine(_failed == 0 ? "ALL PLATE SIZING TESTS PASSED." : $"{_failed} FAILED."); + return _failed == 0 ? 0 : 1; + } + + private static (string Key, Func Get, Action Set, float Min, float Max)[] Sizes => new (string, Func, Action, float, float)[] + { + ("monsterBarWidth", () => S.MonsterBarWidth, v => S.MonsterBarWidth = v, S.MinBarWidth, S.MaxBarWidth), + ("monsterBarHeight", () => S.MonsterBarHeight, v => S.MonsterBarHeight = v, S.MinBarHeight, S.MaxBarHeight), + ("monsterTextSize", () => S.MonsterTextSize, v => S.MonsterTextSize = v, S.MinTextSize, S.MaxTextSize), + ("npcTextSize", () => S.NpcTextSize, v => S.NpcTextSize = v, S.MinTextSize, S.MaxTextSize), + ("playerTextSize", () => S.PlayerTextSize, v => S.PlayerTextSize = v, S.MinTextSize, S.MaxTextSize), + ("selfBarWidth", () => S.SelfBarWidth, v => S.SelfBarWidth = v, S.MinBarWidth, S.MaxBarWidth), + ("selfBarHeight", () => S.SelfBarHeight, v => S.SelfBarHeight = v, S.MinBarHeight, S.MaxBarHeight), + ("selfTextSize", () => S.SelfTextSize, v => S.SelfTextSize = v, S.MinTextSize, S.MaxTextSize), + }; + + private static string[] Written() + { + var sw = new StringWriter(CultureInfo.InvariantCulture); + S.WriteAll(sw); + return sw.ToString().Split('\n', StringSplitOptions.RemoveEmptyEntries).Select(l => l.TrimEnd('\r')).ToArray(); + } + + // ── nameplate sizes ───────────────────────────────────────────────── + + private static void DefaultsAreTodaysLook() + { + Case("defaults: every size multiplier is 1 (today's look), inside its range"); + foreach (var s in Sizes) + { + Check(s.Get() == 1.0f, $"{s.Key} defaults to 1"); + Check(s.Min <= 1.0f && 1.0f <= s.Max, $"{s.Key} range [{s.Min}, {s.Max}] holds 1"); + } + string[] lines = Written(); + foreach (var s in Sizes) + Check(lines.Contains(s.Key + "=1"), $"{s.Key}=1 written"); + } + + private static void RoundTrip() + { + Case("save/load: non-default sizes come back"); + float[] values = { 1.75f, 0.5f, 1.25f, 0.8f, 2f, 2.5f, 3f, 0.65f }; + var sizes = Sizes; + for (int i = 0; i < sizes.Length; i++) sizes[i].Set(values[i]); + S.Scale = 1.3f; S.SelfNumbers = true; + string[] lines = Written(); + + S.ResetToDefaults(); + Check(S.MonsterBarWidth == 1f && S.SelfTextSize == 1f, "reset before reload"); + S.ApplyLines(lines); + for (int i = 0; i < sizes.Length; i++) + Check(MathF.Abs(sizes[i].Get() - values[i]) < 0.001f, $"{sizes[i].Key} = {values[i]} after reload (got {sizes[i].Get()})"); + Check(MathF.Abs(S.Scale - 1.3f) < 0.001f && S.SelfNumbers, "other settings in the same file still load"); + S.ResetToDefaults(); + } + + private static void OldFileLoads() + { + Case("a file from before 2026-10-05 (no size keys) loads with sizes at 1"); + S.MonsterBarWidth = 2f; S.NpcTextSize = 1.5f; + S.ResetToDefaults(); + S.ApplyLines(new[] + { + "# RynthCore monster nameplates - auto-generated, hand-edits OK. /rc plates in game.", + "enabled=1", "scale=1.2", "opacity=0.8", "selfNumbers=1", "npcNames=1", + }); + foreach (var s in Sizes) Check(s.Get() == 1f, $"{s.Key} stays 1"); + Check(MathF.Abs(S.Scale - 1.2f) < 0.001f, "scale from the old file"); + } + + private static void Clamping() + { + Case("load: out-of-range values clamp, junk is ignored"); + S.ResetToDefaults(); + S.ApplyLines(new[] + { + "monsterBarWidth=9", "monsterBarHeight=0.01", "monsterTextSize=-3", + "npcTextSize=abc", "playerTextSize=", "selfBarWidth=0.1", "selfBarHeight=99", "selfTextSize=1e9", + }); + Check(S.MonsterBarWidth == S.MaxBarWidth, "bar width capped"); + Check(S.MonsterBarHeight == S.MinBarHeight, "bar height floored"); + Check(S.MonsterTextSize == S.MinTextSize, "negative text size floored"); + Check(S.NpcTextSize == 1f, "junk ignored (NPC)"); + Check(S.PlayerTextSize == 1f, "empty ignored (player)"); + Check(S.SelfBarWidth == S.MinBarWidth, "self width floored"); + Check(S.SelfBarHeight == S.MaxBarHeight, "self height capped"); + Check(S.SelfTextSize == S.MaxTextSize, "self text capped"); + S.ResetToDefaults(); + } + + private static void ResetSizesOnlyTouchesSizes() + { + Case("Reset bar and text sizes: sizes back to 1, nothing else, saved"); + S.ResetToDefaults(); + foreach (var s in Sizes) s.Set(1.5f); + S.Scale = 1.4f; S.MaxPlates = 7; S.SelfName = true; + int saves = RynthCore.Engine.UI.UiBackgroundWriter.Enqueued; + S.ResetSizes(); + foreach (var s in Sizes) Check(s.Get() == 1f, $"{s.Key} back to 1"); + Check(MathF.Abs(S.Scale - 1.4f) < 0.001f && S.MaxPlates == 7 && S.SelfName, "other settings kept"); + Check(RynthCore.Engine.UI.UiBackgroundWriter.Enqueued == saves + 1, "one save queued"); + S.ResetToDefaults(); + } + + private static void ResetAllResetsSizes() + { + Case("Reset all to defaults also resets the sizes"); + foreach (var s in Sizes) s.Set(0.7f); + S.ResetToDefaults(); + foreach (var s in Sizes) Check(s.Get() == 1f, $"{s.Key} back to 1"); + } + + private static void RefactorKeepsEveryKey() + { + Case("write -> apply -> write is stable (the load/save split kept every key)"); + S.ResetToDefaults(); + S.Enabled = false; S.MaxDistance = 50f; S.Filter = PlateFilter.Engaged; S.SelfPlacement = SelfPlacement.Follow; + S.SelfPosition = SelfPlatePosition.Left; S.GainTime = 2.25f; S.NumSize = 1.5f; S.SelfFixedX = 0.25f; + S.MonsterBarHeight = 2f; S.PlayerTextSize = 0.75f; + string[] first = Written(); + S.ResetToDefaults(); + S.ApplyLines(first); + string[] second = Written(); + Check(first.SequenceEqual(second), "identical text after a reload"); + Check(first.Length == second.Length && first.Length > 50, $"{first.Length} lines written"); + S.ResetToDefaults(); + } + + // ── overlay opacity (colour alpha) ─────────────────────────────────── + + private static readonly (string Name, uint Argb, int Pct)[] TodaysColours = + { + ("slopes (impassable terrain)", 0x60FF2020u, 38), + ("water", 0x600060FFu, 38), + ("radar ring", 0x80FFD000u, 50), + }; + + private static void OpacityDefaults() + { + Case("opacity: today's colours show today's opacity, untouched they never change"); + foreach (var c in TodaysColours) + { + float p = ArgbOpacity.Percent(c.Argb); + Check((int)MathF.Round(p) == c.Pct, $"{c.Name} shows {c.Pct}% (got {p:0.##})"); + Check(ArgbOpacity.WithPercent(c.Argb, p) == c.Argb, $"{c.Name} unchanged when re-applied"); + } + Check(ArgbOpacity.Percent(0x00123456) == 0f && ArgbOpacity.Percent(0xFF123456) == 100f, "0 and 100 at the ends"); + } + + private static void OpacityRoundTripsEveryAlpha() + { + Case("opacity: every alpha byte survives percent and back"); + int bad = 0; + for (uint a = 0; a <= 255; a++) + { + uint c = (a << 24) | 0x00ABCDEF; + if (ArgbOpacity.WithPercent(c, ArgbOpacity.Percent(c)) != c) bad++; + } + Check(bad == 0, $"{bad} of 256 alpha values changed"); + } + + private static void OpacitySetKeepsRgb() + { + Case("opacity: setting it changes only the alpha, clamped to 0..100"); + Check(ArgbOpacity.WithPercent(0x60FF2020, 100f) == 0xFFFF2020, "100% = solid, RGB kept"); + Check(ArgbOpacity.WithPercent(0x60FF2020, 0f) == 0x00FF2020, "0% = invisible, RGB kept"); + Check(ArgbOpacity.WithPercent(0x80FFD000, 25f) == 0x40FFD000, "25% = 0x40"); + Check(ArgbOpacity.WithPercent(0x80FFD000, 150f) == 0xFFFFD000, "above 100 clamps"); + Check(ArgbOpacity.WithPercent(0x80FFD000, -5f) == 0x00FFD000, "below 0 clamps"); + Check(ArgbOpacity.WithPercent(0x80FFD000, float.NaN) == 0x00FFD000, "NaN is 0"); + } + + // ── harness ───────────────────────────────────────────────────────── + + private static void Case(string name) + { + _case = name; + Console.WriteLine("- " + name); + } + + private static void Check(bool ok, string what) + { + _checks++; + if (ok) return; + _failed++; + Console.WriteLine($" FAIL [{_case}] {what}"); + } + } +} diff --git a/tools/PluginManifestTests/PluginManifestTests.csproj b/tools/PluginManifestTests/PluginManifestTests.csproj new file mode 100644 index 0000000..264a67d --- /dev/null +++ b/tools/PluginManifestTests/PluginManifestTests.csproj @@ -0,0 +1,40 @@ + + + + + Exe + net10.0-windows + enable + enable + true + true + PluginManifestTests + $(NoWarn);CS0649;CS0169 + + + + + + + + + + + + + + + diff --git a/tools/PluginManifestTests/Program.cs b/tools/PluginManifestTests/Program.cs new file mode 100644 index 0000000..5e0ea72 --- /dev/null +++ b/tools/PluginManifestTests/Program.cs @@ -0,0 +1,516 @@ +using System.ComponentModel; +using System.Runtime.InteropServices; +using System.Text; +using System.Text.RegularExpressions; +using RynthCore.Engine.Plugins; +using RynthCore.PluginSdk; +using RynthCore.PluginSdk.Manifest; + +// What the SDK targets add to a plugin built with RynthPluginMinEngineApi=71 (see ManifestAttributeDrivesRuntimeMinimum). +[assembly: RynthPluginManifest(71)] + +// Offline tests for plugin manifests: parsing, the engine's gate (API + dependencies + order), +// reading the embedded resource from PE files, and the SDK's API version. See the csproj. +internal static class Program +{ + private static int _fails, _asserts; + private static void Check(bool cond, string msg) + { + _asserts++; + if (!cond) { _fails++; Console.WriteLine($" [FAIL] {msg}"); } + } + private static void Eq(T actual, T expected, string msg) => + Check(EqualityComparer.Default.Equals(actual, expected), $"{msg}: expected '{expected}', got '{actual}'"); + + private static string _root = ""; + private const uint Api = PluginContractVersion.Current; + + private static int Main(string[] args) + { + _root = Path.Combine(Path.GetTempPath(), "rynth-manifest-tests-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(_root); + try + { + Run(nameof(ParsesFullManifest), ParsesFullManifest); + Run(nameof(ParsesShorthandAndIgnoresUnknown), ParsesShorthandAndIgnoresUnknown); + Run(nameof(RejectsBrokenManifests), RejectsBrokenManifests); + Run(nameof(RoundTripsThroughJson), RoundTripsThroughJson); + Run(nameof(EngineApiCheck), EngineApiCheck); + Run(nameof(VersionComparisons), VersionComparisons); + Run(nameof(NoManifestsLoadExactlyAsListed), NoManifestsLoadExactlyAsListed); + Run(nameof(TooNewPluginIsRefusedOthersKeepOrder), TooNewPluginIsRefusedOthersKeepOrder); + Run(nameof(RequiredDependencyMissingRefuses), RequiredDependencyMissingRefuses); + Run(nameof(OptionalDependencyNeverRefusesOrReorders), OptionalDependencyNeverRefusesOrReorders); + Run(nameof(RefusalCascadesDownTheChain), RefusalCascadesDownTheChain); + Run(nameof(RequiredDependenciesStartFirst), RequiredDependenciesStartFirst); + Run(nameof(DependencyVersions), DependencyVersions); + Run(nameof(DependencyOnPluginWithoutManifest), DependencyOnPluginWithoutManifest); + Run(nameof(RequiredCycleRefusesNothing), RequiredCycleRefusesNothing); + Run(nameof(CheckRequiredStartedAtInit), CheckRequiredStartedAtInit); + Run(nameof(ReadsResourceFromPe32AndPe32Plus), ReadsResourceFromPe32AndPe32Plus); + Run(nameof(NoResourceAndNotAPe), NoResourceAndNotAPe); + Run(nameof(GatePlanFromFiles), GatePlanFromFiles); + Run(nameof(SdkApiVersionCannotDrift), SdkApiVersionCannotDrift); + Run(nameof(TrainingStructsMirror), TrainingStructsMirror); + Run(nameof(ManifestAttributeDrivesRuntimeMinimum), ManifestAttributeDrivesRuntimeMinimum); + foreach (string dll in args) + Run("Plugin " + Path.GetFileName(dll), () => CheckBuiltPlugin(dll)); + } + finally + { + try { Directory.Delete(_root, true); } catch { } + } + Console.WriteLine(); + Console.WriteLine(_fails == 0 && _asserts > 0 ? $"PASS ({_asserts} assertions)" : $"FAIL ({_fails} of {_asserts} assertions failed)"); + return _fails == 0 && _asserts > 0 ? 0 : 1; + } + + private static void Run(string name, Action test) + { + int before = _fails; + try { test(); } + catch (Exception ex) { _fails++; _asserts++; Console.WriteLine($" [FAIL] {name} threw {ex.GetType().Name}: {ex.Message}"); } + Console.WriteLine($"{(_fails == before ? "ok " : "FAIL")} {name}"); + } + + // ── Fixtures ───────────────────────────────────────────────────────────── + + private static RynthPluginManifest M(string name, uint min = 66, string version = "2026.10.5.1", uint max = 0, + params (string Name, string Min, bool Optional)[] deps) + { + var m = new RynthPluginManifest { Name = name, Version = version, MinEngineApi = min, MaxEngineApi = max }; + foreach (var d in deps) m.Dependencies.Add(new RynthPluginDependency { Name = d.Name, MinVersion = d.Min, Optional = d.Optional }); + return m; + } + + private static PluginCandidate C(string name, RynthPluginManifest? m = null, string fileVersion = "") => + new($@"C:\Games\RynthSuite\{name}\RynthCore.Plugin.{name}.dll", m, fileVersion); + + private static string Names(IEnumerable list) => string.Join(",", list.Select(c => c.Name)); + + // ── Parsing ────────────────────────────────────────────────────────────── + + private static void ParsesFullManifest() + { + var m = RynthPluginManifest.Parse(""" + { + "schema": 1, + "name": "RynthOracle", + "version": "2026.10.5.1", + "minEngineApi": 71, + "maxEngineApi": 90, + "dependencies": [ + { "name": "RynthAi", "optional": true }, + { "name": "RynthNav", "minVersion": "2026.10.1.1" } + ], + "author": "RynthSuite", + "description": "Quests, character, titles and leaderboards.", + "homepage": "https://aelrynth.com/rynth.html", + "license": "MIT" + } + """); + Eq(m.Name, "RynthOracle", "name"); + Eq(m.Version, "2026.10.5.1", "version"); + Eq(m.MinEngineApi, 71u, "minEngineApi"); + Eq(m.MaxEngineApi, 90u, "maxEngineApi"); + Eq(m.Dependencies.Count, 2, "dependency count"); + Check(m.Dependencies[0].Optional && m.Dependencies[0].Name == "RynthAi", "first dependency optional RynthAi"); + Check(!m.Dependencies[1].Optional && m.Dependencies[1].MinVersion == "2026.10.1.1", "second dependency required with min version"); + Eq(m.Author, "RynthSuite", "author"); + Eq(m.License, "MIT", "license"); + Eq(m.Homepage, "https://aelrynth.com/rynth.html", "homepage"); + } + + private static void ParsesShorthandAndIgnoresUnknown() + { + var m = RynthPluginManifest.Parse("""{ "schema": 2, "name": "X", "minEngineApi": "70", "dependencies": ["RynthNav@2026.10.1.1", "RynthAi"], "futureField": { "a": 1 } }"""); + Eq(m.Schema, 2, "a later schema is read"); + Eq(m.MinEngineApi, 70u, "minEngineApi as a string"); + Eq(m.Dependencies[0].Name, "RynthNav", "shorthand name"); + Eq(m.Dependencies[0].MinVersion, "2026.10.1.1", "shorthand version"); + Check(!m.Dependencies[1].Optional, "shorthand is required"); + var bare = RynthPluginManifest.Parse("""{ "name": "Bare" }"""); + Eq(bare.MinEngineApi, 0u, "no minEngineApi means no limit"); + Eq(bare.Dependencies.Count, 0, "no dependencies"); + } + + private static void RejectsBrokenManifests() + { + string[] bad = + { + "not json", + "[]", + """{ "version": "1.0" }""", + """{ "name": "" }""", + """{ "name": "X", "minEngineApi": 76, "maxEngineApi": 70 }""", + """{ "name": "X", "minEngineApi": -1 }""", + """{ "name": "X", "minEngineApi": "abc" }""", + """{ "name": "X", "dependencies": ["X"] }""", + """{ "name": "X", "dependencies": [{ "name": "Y", "minVersion": "soon" }] }""", + """{ "name": "X", "dependencies": [42] }""", + """{ "name": "X", "dependencies": {} }""", + """{ "name": "X", "schema": 0 }""", + }; + foreach (string json in bad) + { + Check(RynthPluginManifest.TryParse(json, out string err) == null && err.Length > 0, $"refused: {json}"); + } + } + + private static void RoundTripsThroughJson() + { + var m = M("RynthAi", 66, "2026.10.5.1", 0, ("RynthNav", "", true), ("RynthLua", "2026.9.1.1", false)); + m.Description = "The bot: \"combat\", buffs\nand more"; + m.License = "MIT"; + var back = RynthPluginManifest.Parse(m.ToJson()); + Eq(back.Name, m.Name, "name"); + Eq(back.Description, m.Description, "description with quotes and newline"); + Eq(back.Dependencies.Count, 2, "dependencies"); + Check(back.Dependencies[0].Optional && !back.Dependencies[1].Optional, "optional flags"); + Eq(back.Dependencies[1].MinVersion, "2026.9.1.1", "min version"); + Check(!m.ToJson().Contains("maxEngineApi"), "no maxEngineApi written when unset"); + } + + private static void EngineApiCheck() + { + Eq(M("RynthOracle", 77).CheckEngine(76), "RynthOracle needs a newer RynthCore (API 77)", "too new"); + Check(M("RynthOracle", 76).CheckEngine(76) == null, "exact minimum runs"); + Check(M("RynthOracle", 66).CheckEngine(76) == null, "older minimum runs"); + Check(M("Old", 60, max: 70).CheckEngine(76)?.Contains("too old") == true, "past maxEngineApi refused"); + Check(M("Old", 60, max: 76).CheckEngine(76) == null, "at maxEngineApi runs"); + Eq(RynthPluginManifest.NameFromFile(@"C:\x\RynthCore.Plugin.RynthNav.dll"), "RynthNav", "name from file"); + Eq(RynthPluginManifest.NameFromFile(@"C:\x\Other.dll"), "Other", "name from other file"); + } + + private static void VersionComparisons() + { + Check(PluginVersion.Satisfies("2026.10.5.1", "2026.10.1.1"), "newer satisfies"); + Check(PluginVersion.Satisfies("2026.10.1.1", "2026.10.1.1"), "equal satisfies"); + Check(!PluginVersion.Satisfies("2026.9.30.4", "2026.10.1.1"), "older doesn't"); + Check(PluginVersion.Satisfies("2026.10.5.1+8ca322f", "2026.10.5"), "build metadata ignored, 3 vs 4 parts"); + Check(PluginVersion.Satisfies("1.0.0", "2026.10.1.1"), "dev build satisfies anything"); + Check(PluginVersion.Satisfies("1.0.0+abc", "2026.10.1.1"), "dev build with commit satisfies"); + Check(PluginVersion.IsDevBuild("1.0.0.0") && !PluginVersion.IsDevBuild("1.0.1"), "dev build detection"); + Check(!PluginVersion.Satisfies("", "2026.10.1.1"), "no version doesn't satisfy a minimum"); + Check(PluginVersion.Satisfies("", ""), "no minimum, anything goes"); + Check(PluginVersion.TryParse("v2.0.0-beta", out var v) && v.Major == 2, "v prefix and prerelease"); + } + + // ── Resolution (the engine's load plan) ────────────────────────────────── + + private static void NoManifestsLoadExactlyAsListed() + { + var list = new[] { C("RynthChat"), C("RynthAi"), C("RynthNav"), C("Zed") }; + PluginResolution r = PluginManifestResolver.Resolve(list, Api); + Eq(Names(r.Order), "RynthChat,RynthAi,RynthNav,Zed", "order unchanged"); + Eq(r.Refused.Count, 0, "nothing refused"); + Eq(r.Notes.Count, 0, "nothing to say"); + } + + private static void TooNewPluginIsRefusedOthersKeepOrder() + { + var list = new[] { C("RynthChat"), C("RynthOracle", M("RynthOracle", Api + 1)), C("RynthAi", M("RynthAi", 66)) }; + PluginResolution r = PluginManifestResolver.Resolve(list, Api); + Eq(Names(r.Order), "RynthChat,RynthAi", "the rest load in order"); + Eq(r.Refused.Count, 1, "one refused"); + Eq(r.Refused[0].Reason, $"RynthOracle needs a newer RynthCore (API {Api + 1})", "reason fit for chat"); + Check(r.Refused[0].IsEngineMismatch, "engine mismatch flagged"); + } + + private static void RequiredDependencyMissingRefuses() + { + var list = new[] { C("RynthLua", M("RynthLua", 66, deps: ("RynthAi", "", false))), C("RynthChat") }; + PluginResolution r = PluginManifestResolver.Resolve(list, Api); + Eq(Names(r.Order), "RynthChat", "dependent not loaded"); + Eq(r.Refused.Single().Reason, "RynthLua needs the RynthAi plugin, which is not in the plugin list", "reason"); + Check(!r.Refused[0].IsEngineMismatch, "dependency refusal flagged"); + } + + private static void OptionalDependencyNeverRefusesOrReorders() + { + // RynthAi and RynthLua can each use the other: optional both ways is no cycle and no reorder. + var list = new[] + { + C("RynthAi", M("RynthAi", 66, deps: new[] { ("RynthNav", "", true), ("RynthLua", "", true), ("RynthNet", "", true) })), + C("RynthLua", M("RynthLua", 66, deps: ("RynthAi", "", true))), + C("RynthNet", M("RynthNet", 66, deps: ("RynthAi", "", true))), + }; + PluginResolution r = PluginManifestResolver.Resolve(list, Api); + Eq(Names(r.Order), "RynthAi,RynthLua,RynthNet", "order unchanged"); + Eq(r.Refused.Count, 0, "nothing refused"); + Check(r.Notes.Any(n => n.Contains("optional plugin RynthNav is not loaded")), "missing optional noted"); + } + + private static void RefusalCascadesDownTheChain() + { + var list = new[] + { + C("C", M("C", 66, deps: ("B", "", false))), + C("B", M("B", 66, deps: ("A", "", false))), + C("A", M("A", Api + 5)), + C("D"), + }; + PluginResolution r = PluginManifestResolver.Resolve(list, Api); + Eq(Names(r.Order), "D", "only the independent plugin loads"); + Eq(r.Refused.Count, 3, "three refused"); + Check(r.Refused.Any(x => x.Plugin.Name == "B" && x.Reason == "B needs A, which was not loaded"), "B refused for A"); + Check(r.Refused.Any(x => x.Plugin.Name == "C" && x.Reason == "C needs B, which was not loaded"), "C refused for B"); + } + + private static void RequiredDependenciesStartFirst() + { + var list = new[] + { + C("RynthChat"), + C("Addon", M("Addon", 66, deps: ("RynthNav", "", false))), + C("RynthTracker"), + C("RynthNav", M("RynthNav", 66)), + C("RynthVision"), + }; + PluginResolution r = PluginManifestResolver.Resolve(list, Api); + Eq(Names(r.Order), "RynthChat,RynthNav,Addon,RynthTracker,RynthVision", "RynthNav moved before Addon, the rest as listed"); + } + + private static void DependencyVersions() + { + var tooOld = new[] { C("Addon", M("Addon", 66, deps: ("RynthNav", "2026.10.1.1", false))), C("RynthNav", M("RynthNav", 66, "2026.9.30.2")) }; + PluginResolution r = PluginManifestResolver.Resolve(tooOld, Api); + Eq(Names(r.Order), "RynthNav", "too-old dependency refuses the dependent"); + Eq(r.Refused.Single().Reason, "Addon needs RynthNav 2026.10.1.1 or newer (this one is 2026.9.30.2)", "reason"); + + var dev = new[] { C("Addon", M("Addon", 66, deps: ("RynthNav", "2026.10.1.1", false))), C("RynthNav", M("RynthNav", 66, "1.0.0")) }; + r = PluginManifestResolver.Resolve(dev, Api); + Eq(Names(r.Order), "RynthNav,Addon", "a dev build satisfies"); + Check(r.Notes.Any(n => n.Contains("dev build")), "dev build noted"); + + var optOld = new[] { C("Addon", M("Addon", 66, deps: ("RynthNav", "2026.10.1.1", true))), C("RynthNav", M("RynthNav", 66, "2026.9.1.1")) }; + r = PluginManifestResolver.Resolve(optOld, Api); + Eq(r.Refused.Count, 0, "an old optional dependency refuses nothing"); + Check(r.Notes.Any(n => n.Contains("older")), "old optional noted"); + } + + private static void DependencyOnPluginWithoutManifest() + { + // RynthNav from before manifests: found by its file name, versioned by its version resource. + var list = new[] { C("Addon", M("Addon", 66, deps: ("RynthNav", "2026.10.1.1", false))), C("RynthNav", null, "2026.10.4.3+abcdef") }; + PluginResolution r = PluginManifestResolver.Resolve(list, Api); + Eq(Names(r.Order), "RynthNav,Addon", "satisfied by file name and version resource"); + + var noVersion = new[] { C("Addon", M("Addon", 66, deps: ("RynthNav", "2026.10.1.1", false))), C("RynthNav") }; + r = PluginManifestResolver.Resolve(noVersion, Api); + Check(r.Refused.Single().Reason.Contains("has no version"), "an unversioned plugin can't meet a minimum"); + + var anyVersion = new[] { C("Addon", M("Addon", 66, deps: ("RynthNav", "", false))), C("RynthNav") }; + r = PluginManifestResolver.Resolve(anyVersion, Api); + Eq(r.Refused.Count, 0, "no minimum: any copy will do"); + } + + private static void RequiredCycleRefusesNothing() + { + var list = new[] { C("A", M("A", 66, deps: ("B", "", false))), C("B", M("B", 66, deps: ("A", "", false))), C("Z") }; + PluginResolution r = PluginManifestResolver.Resolve(list, Api); + Eq(r.Refused.Count, 0, "a cycle isn't a reason to refuse"); + Eq(r.Order.Count, 3, "all load"); + Check(r.Notes.Any(n => n.Contains("cycle")), "cycle noted"); + } + + private static void CheckRequiredStartedAtInit() + { + var m = M("Addon", 66, deps: new[] { ("RynthNav", "", false), ("RynthAi", "", true) }); + Check(PluginManifestGate.CheckRequiredStarted(null, _ => null) == null, "no manifest, no check"); + Check(PluginManifestGate.CheckRequiredStarted(m, n => n == "RynthNav" ? true : null) == null, "required started, optional absent: fine"); + Eq(PluginManifestGate.CheckRequiredStarted(m, n => n == "RynthNav" ? false : true), "Addon needs RynthNav, which failed to start", "required failed"); + Eq(PluginManifestGate.CheckRequiredStarted(m, _ => null), "Addon needs RynthNav, which is not loaded", "required missing"); + } + + // ── PE files ───────────────────────────────────────────────────────────── + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern IntPtr BeginUpdateResourceW(string file, bool deleteExisting); + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern bool UpdateResourceW(IntPtr h, IntPtr type, string name, ushort lang, byte[] data, uint cb); + [DllImport("kernel32.dll", SetLastError = true)] + private static extern bool EndUpdateResourceW(IntPtr h, bool discard); + + /// What the build's RynthEmbedPluginManifest task does. + private static void Embed(string path, string json, string name = RynthPluginManifest.ResourceName) + { + IntPtr h = BeginUpdateResourceW(path, false); + if (h == IntPtr.Zero) throw new Win32Exception(Marshal.GetLastWin32Error()); + byte[] data = Encoding.UTF8.GetBytes(json); + if (!UpdateResourceW(h, (IntPtr)RynthPluginManifest.ResourceType, name, 0, data, (uint)data.Length)) + { + int err = Marshal.GetLastWin32Error(); + EndUpdateResourceW(h, true); + throw new Win32Exception(err); + } + if (!EndUpdateResourceW(h, false)) throw new Win32Exception(Marshal.GetLastWin32Error()); + } + + private static string CopyOf(string source, string name) + { + string dest = Path.Combine(_root, Guid.NewGuid().ToString("N")[..8], name); + Directory.CreateDirectory(Path.GetDirectoryName(dest)!); + File.Copy(source, dest); + return dest; + } + + private static string ThisDll => typeof(Program).Assembly.Location; + private static string ThisExe => Path.ChangeExtension(ThisDll, ".exe"); + + private static void ReadsResourceFromPe32AndPe32Plus() + { + // The test's own IL DLL is PE32 (AnyCPU); its apphost .exe is a native PE32+ image. + foreach (string source in new[] { ThisDll, ThisExe }) + { + string copy = CopyOf(source, "RynthCore.Plugin.Probe" + Path.GetExtension(source)); + Check(PluginManifestReader.Read(copy) == null, $"{Path.GetFileName(source)}: no manifest before embedding"); + string json = M("Probe", 71, deps: ("RynthAi", "", true)).ToJson(); + Embed(copy, json); + RynthPluginManifest? m = PluginManifestReader.Read(copy); + Check(m != null, $"{Path.GetFileName(source)}: manifest read back"); + Eq(m?.MinEngineApi ?? 0, 71u, $"{Path.GetFileName(source)}: minEngineApi"); + Eq(PluginManifestReader.ReadJson(copy), json, $"{Path.GetFileName(source)}: exact JSON"); + Check(!string.IsNullOrEmpty(System.Diagnostics.FileVersionInfo.GetVersionInfo(copy).ProductVersion), + $"{Path.GetFileName(source)}: version resource survives"); + // Replace in place (a rebuild): the new one wins. + Embed(copy, M("Probe", 72).ToJson()); + Eq(PluginManifestReader.Read(copy)?.MinEngineApi ?? 0, 72u, $"{Path.GetFileName(source)}: re-embedded"); + // Readable while another process has it open for execution-style sharing (the engine's shadow copy case). + using (new FileStream(copy, FileMode.Open, FileAccess.Read, FileShare.Read)) + Check(PluginManifestReader.Read(copy) != null, $"{Path.GetFileName(source)}: readable while open"); + } + // Lower-case name in the file still matches (resource names are case-insensitive). + string lower = CopyOf(ThisDll, "lower.dll"); + Embed(lower, M("Lower", 66).ToJson(), "rynth_plugin_manifest"); + Eq(PluginManifestReader.Read(lower)?.Name, "Lower", "case-insensitive resource name"); + } + + private static void NoResourceAndNotAPe() + { + string text = Path.Combine(_root, "notes.dll"); + File.WriteAllText(text, "this is not a DLL, just text long enough to have a header-sized body ................................."); + try { PluginManifestReader.Read(text); Check(false, "a text file should throw"); } + catch (InvalidDataException) { Check(true, "text file refused as not a PE"); } + + string tiny = Path.Combine(_root, "tiny.dll"); + File.WriteAllBytes(tiny, new byte[] { 0x4D, 0x5A }); + try { PluginManifestReader.Read(tiny); Check(false, "a 2-byte file should throw"); } + catch (InvalidDataException) { Check(true, "truncated file refused"); } + + // Another RCDATA resource, not ours: still "no manifest". + string other = CopyOf(ThisDll, "other.dll"); + Embed(other, "{}", "SOMETHING_ELSE"); + Check(PluginManifestReader.Read(other) == null, "other resources are not a manifest"); + } + + private static void GatePlanFromFiles() + { + string dir = Path.Combine(_root, "suite"); + Directory.CreateDirectory(dir); + string P(string name) => Path.Combine(dir, $"RynthCore.Plugin.{name}.dll"); + File.Copy(ThisDll, P("RynthChat")); // no manifest: loads as before + File.Copy(ThisDll, P("RynthOracle")); + Embed(P("RynthOracle"), M("RynthOracle", Api + 1).ToJson()); + File.Copy(ThisDll, P("RynthAi")); + Embed(P("RynthAi"), M("RynthAi", 66, deps: ("RynthLua", "", true)).ToJson()); + File.Copy(ThisDll, P("Broken")); + Embed(P("Broken"), "{ \"name\": "); // broken JSON: loads as without one + File.Copy(ThisDll, P("Needy")); + Embed(P("Needy"), M("Needy", 66, deps: ("RynthNav", "", false)).ToJson()); + + var paths = new[] { P("RynthChat"), P("RynthOracle"), P("RynthAi"), P("Broken"), P("Needy") }; + PluginManifestGate.LoadPlan plan = PluginManifestGate.Plan(paths, Api, _ => "2026.10.4.3"); + Eq(string.Join(",", plan.Load.Select(l => RynthPluginManifest.NameFromFile(l.Path))), "RynthChat,RynthAi,Broken", "load list"); + Check(plan.Load.Single(l => l.Path == P("RynthChat")).Manifest == null, "RynthChat has no manifest"); + Check(plan.Load.Single(l => l.Path == P("RynthAi")).Manifest?.Name == "RynthAi", "RynthAi carries its manifest"); + Eq(plan.Refused.Count, 2, "two refused"); + Check(plan.Refused.Any(r => r.Reason == $"RynthOracle needs a newer RynthCore (API {Api + 1})"), "Oracle refused for API"); + Check(plan.Refused.Any(r => r.Reason.StartsWith("Needy needs the RynthNav plugin")), "Needy refused for RynthNav"); + Check(plan.Log.Any(l => l.Contains("Broken") && l.Contains("manifest unreadable")), "broken manifest logged"); + Check(plan.Log.Any(l => l.Contains("optional plugin RynthLua")), "optional note logged"); + + PluginManifestGate.LoadPlan none = PluginManifestGate.Plan(new[] { P("RynthChat"), P("Broken") }, Api); + Eq(none.Load.Count, 2, "no manifests: everything loads"); + Check(none.Log.Any(l => l.Contains("no plugin has a manifest")), "said once"); + } + + // ── The SDK's version ──────────────────────────────────────────────────── + + private static void SdkApiVersionCannotDrift() + { + Eq(RynthCoreHost.CurrentApiVersion, PluginContractVersion.Current, "RynthCoreHost.CurrentApiVersion"); + Check(RynthCoreHost.BaselineApiVersion <= RynthCoreHost.CurrentApiVersion, "baseline at or below current"); + + // The SDK's copy of the table must reach as far as the engine's (same field count, same size). + int sdkFields = typeof(RynthCoreApiNative).GetFields().Length; + int engineFields = typeof(RynthCoreAPI).GetFields().Length; + Eq(sdkFields, engineFields, "RynthCoreApiNative fields vs the engine's RynthCoreAPI (add the new fields to the SDK)"); + Eq(Marshal.SizeOf(), Marshal.SizeOf(), "table size"); + + // The build targets' copy, used to refuse a RynthPluginMinEngineApi the SDK doesn't know. + string targets = FindUp(Path.Combine("src", "RynthCore.PluginSdk", "build", "RynthCore.PluginSdk.targets")); + Match match = Regex.Match(File.ReadAllText(targets), @"(\d+)"); + Check(match.Success, "targets declare RynthCoreSdkApiVersion"); + Eq(match.Success ? uint.Parse(match.Groups[1].Value) : 0u, PluginContractVersion.Current, "RynthCoreSdkApiVersion in RynthCore.PluginSdk.targets"); + } + + // v79: the SDK's copies of the training structs must be the engine's, byte for byte. + private static void TrainingStructsMirror() + { + Eq(Marshal.SizeOf(), 64, "SDK TrainingInfoNative size"); + Eq(Marshal.SizeOf(), 64, "engine TrainingInfoNative size"); + Eq(Marshal.SizeOf(), 64, "SDK TrainingEntryNative size"); + Eq(Marshal.SizeOf(), 64, "engine TrainingEntryNative size"); + foreach (var f in typeof(RynthCore.Engine.Plugins.TrainingInfoNative).GetFields()) + Eq((int)Marshal.OffsetOf(f.Name), (int)Marshal.OffsetOf(f.Name), "TrainingInfoNative." + f.Name + " offset"); + foreach (var f in typeof(RynthCore.Engine.Plugins.TrainingEntryNative).GetFields()) + Eq((int)Marshal.OffsetOf(f.Name), (int)Marshal.OffsetOf(f.Name), "TrainingEntryNative." + f.Name + " offset"); + Eq(RynthCore.PluginSdk.TrainingInfoFlags.Busy, RynthCore.Engine.Plugins.TrainingInfoFlags.Busy, "info flag bits"); + Eq(RynthCore.PluginSdk.TrainingEntryFlags.Trainable, RynthCore.Engine.Plugins.TrainingEntryFlags.Trainable, "entry flag bits"); + // The three v79 slots, then v80's GetMergeStackResultFn, end the table in this order. + var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).TakeLast(4).ToArray(); + Check(names.SequenceEqual(new[] { "GetTrainingInfoFn", "RaiseFn", "TrainSkillFn", "GetMergeStackResultFn" }), "v79 then v80 slots last: " + string.Join(",", names)); + var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).TakeLast(4).ToArray(); + Check(sdkNames.SequenceEqual(names), "SDK v79 and v80 slots in the same order"); + } + + private sealed class ProbePlugin : RynthCore.PluginCore.RynthPluginBase { } + private sealed class OverridingPlugin : RynthCore.PluginCore.RynthPluginBase { public override uint MinimumApiVersion => 70; } + + private static void ManifestAttributeDrivesRuntimeMinimum() + { + // RynthPluginBase.MinimumApiVersion defaults to the assembly's [RynthPluginManifest(min)] ... + Eq(new ProbePlugin().MinimumApiVersion, 71u, "default follows the manifest attribute"); + // ... an explicit override still wins ... + Eq(new OverridingPlugin().MinimumApiVersion, 70u, "an override wins"); + // ... and an assembly without one (RynthCore.PluginSdk itself has none) gets the baseline. + Check(typeof(RynthCoreHost).Assembly.GetCustomAttributes(typeof(RynthPluginManifestAttribute), false).Length == 0, + "the SDK assembly carries no manifest attribute"); + } + + private static string FindUp(string relative) + { + for (DirectoryInfo? d = new(AppContext.BaseDirectory); d != null; d = d.Parent) + { + string p = Path.Combine(d.FullName, relative); + if (File.Exists(p)) return p; + } + throw new FileNotFoundException(relative); + } + + // ── Real plugin DLLs (arguments) ───────────────────────────────────────── + + private static void CheckBuiltPlugin(string dll) + { + RynthPluginManifest? m = PluginManifestReader.Read(dll); + Check(m != null, $"{dll}: has a manifest"); + if (m == null) return; + Console.WriteLine($" {PluginManifestGate.Describe(m)}"); + Eq(m.Name, RynthPluginManifest.NameFromFile(dll), $"{Path.GetFileName(dll)}: manifest name matches the file"); + Check(m.MinEngineApi >= RynthCoreHost.BaselineApiVersion, $"{m.Name}: minEngineApi {m.MinEngineApi} at or above the SDK baseline"); + Check(m.CheckEngine(PluginContractVersion.Current) == null, $"{m.Name}: runs on this engine (API {PluginContractVersion.Current})"); + Check(m.Description.Length > 0, $"{m.Name}: has a description"); + Check(!string.IsNullOrEmpty(System.Diagnostics.FileVersionInfo.GetVersionInfo(dll).ProductVersion), $"{m.Name}: version resource intact"); + } +} diff --git a/tools/PluginManifestTests/Test-PluginManifestPs.ps1 b/tools/PluginManifestTests/Test-PluginManifestPs.ps1 new file mode 100644 index 0000000..e4997cb --- /dev/null +++ b/tools/PluginManifestTests/Test-PluginManifestPs.ps1 @@ -0,0 +1,37 @@ +#Requires -Version 7 +<# +.SYNOPSIS + Checks installer\PluginManifest.ps1 (what Publish-Update.ps1 uses to put minEngineApi in the feed) + against plugin DLLs: it must read the same manifest the engine and launcher read. + +.EXAMPLE + .\Test-PluginManifestPs.ps1 -Dll C:\Projects\manifest\_pub\RynthChat\RynthCore.Plugin.RynthChat.dll + Exit 0 = pass. Read-only: maps the DLLs as data files, runs nothing from them. +#> +param([string[]]$Dll = @(), [string[]]$NoManifestDll = @()) + +$ErrorActionPreference = "Stop" +$repo = (Resolve-Path (Join-Path $PSScriptRoot "..\..")).Path +. (Join-Path $repo "installer\PluginManifest.ps1") +$fails = 0 +function Check($cond, $msg) { if ($cond) { Write-Host "ok $msg" } else { Write-Host "FAIL $msg"; $script:fails++ } } + +$api = Get-RynthEngineApi $repo +$src = Get-Content (Join-Path $repo "src\RynthCore.Engine\Plugins\PluginContractVersion.cs") -Raw +Check ($api -gt 0 -and $src -match "Current = $api;") "Get-RynthEngineApi reads PluginContractVersion.Current ($api)" + +foreach ($d in $Dll) { + $m = Get-RynthPluginManifest $d + Check ($null -ne $m) "$(Split-Path $d -Leaf): manifest found" + if (-not $m) { continue } + $expected = [IO.Path]::GetFileNameWithoutExtension($d) -replace '^RynthCore\.Plugin\.', '' + Check ($m.name -eq $expected) "$(Split-Path $d -Leaf): name '$($m.name)'" + Check ([int]$m.minEngineApi -ge 66 -and [int]$m.minEngineApi -le $api) "$(Split-Path $d -Leaf): minEngineApi $($m.minEngineApi) within 66..$api" +} +foreach ($d in $NoManifestDll) { + Check ($null -eq (Get-RynthPluginManifest $d)) "$(Split-Path $d -Leaf): no manifest -> `$null" +} + +if ($fails -gt 0) { Write-Host "FAIL ($fails)"; exit 1 } +Write-Host "PASS" +exit 0 diff --git a/tools/ReloadDeferralTests/Program.cs b/tools/ReloadDeferralTests/Program.cs new file mode 100644 index 0000000..4211b15 --- /dev/null +++ b/tools/ReloadDeferralTests/Program.cs @@ -0,0 +1,119 @@ +using RynthCore.Engine; + +namespace ReloadDeferralTests; + +/// +/// The engine's hot-reload deferral (ReloadDeferral.cs). Drakkon died on 2026-10-05 after an +/// engine reload took every plugin down for 8 s mid-fight; the engine now waits while a plugin +/// (RynthAi) says a reload would hurt, up to 2 minutes. +/// +internal static class Program +{ + private static int _checks, _failed; + private static string _case = ""; + + private static int Main() + { + NoBlockerReloadsAtOnce(); + WaitsWhileInCombatThenReloads(); + CapReloadsAnyway(); + ThrowingQueryNeverHolds(); + SeveralPluginsDescribed(); + + Console.WriteLine($"{_checks} check(s), {_failed} failed."); + return _failed == 0 ? 0 : 1; + } + + private static void Check(bool ok, string what) + { + _checks++; + if (ok) return; + _failed++; + Console.WriteLine($"[FAIL] {_case}: {what}"); + } + + /// A fake clock that only moves when the deferral sleeps. + private sealed class Rig + { + public DateTime Now = new(2026, 10, 5, 13, 42, 54, DateTimeKind.Utc); + public readonly List Logs = new(); + public readonly List Notes = new(); + public int Queries; + public Func> Answer = _ => Array.Empty<(string, string)>(); + + public ReloadDeferral Make() => new() + { + Query = () => Answer(++Queries), + Log = Logs.Add, + Notify = Notes.Add, + Clock = () => Now, + Sleep = t => Now += t, + }; + } + + private static readonly (string, string)[] InCombat = { ("RynthAi", "in combat (a monster engaged, health 12% under Emergency Heal At 30%)") }; + + private static void NoBlockerReloadsAtOnce() + { + _case = "no blocker"; + var r = new Rig(); + var outcome = r.Make().Run(out TimeSpan waited); + Check(outcome == ReloadDeferral.Outcome.Clear, "nothing objects: Clear"); + Check(waited == TimeSpan.Zero, "no wait"); + Check(r.Queries == 1, "asked once"); + Check(r.Logs.Count == 0 && r.Notes.Count == 0, "nothing logged or said"); + } + + private static void WaitsWhileInCombatThenReloads() + { + _case = "in combat"; + var r = new Rig(); + // In combat for the first 80 answers (40 s at 0.5 s), then clear. + r.Answer = n => n <= 80 ? InCombat : Array.Empty<(string, string)>(); + var outcome = r.Make().Run(out TimeSpan waited); + Check(outcome == ReloadDeferral.Outcome.ClearedAfterWait, $"cleared after a wait (got {outcome})"); + Check(Math.Abs(waited.TotalSeconds - 40) < 0.01, $"waited 40 s (got {waited.TotalSeconds})"); + Check(r.Logs.Count > 0 && r.Logs[0].StartsWith("engine reload waiting: RynthAi in combat (a monster engaged", StringComparison.Ordinal), + $"the first line names the plugin and why: {r.Logs.FirstOrDefault()}"); + int repeats = r.Logs.Count(l => l.StartsWith("engine reload waiting:", StringComparison.Ordinal)); + Check(repeats == 3, $"the waiting line at once, then every 15 s (0, 15, 30 s: 3 lines, got {repeats})"); + Check(r.Logs[^1].StartsWith("engine reload: the plugins are clear after 40.0 s", StringComparison.Ordinal), $"the last line says it goes now: {r.Logs[^1]}"); + Check(r.Notes.Count == 1 && r.Notes[0].Contains("RynthAi in combat"), "the player is told once"); + } + + private static void CapReloadsAnyway() + { + _case = "cap"; + var r = new Rig(); + r.Answer = _ => InCombat; // never clears + var outcome = r.Make().Run(out TimeSpan waited); + Check(outcome == ReloadDeferral.Outcome.TimedOut, $"timed out (got {outcome})"); + Check(waited >= ReloadDeferral.DefaultCap && waited < ReloadDeferral.DefaultCap + TimeSpan.FromSeconds(1), + $"at the 2-minute cap (got {waited.TotalSeconds} s)"); + Check(r.Logs[^1].Contains("reloading anyway") && r.Logs[^1].Contains("RynthAi in combat"), $"and says so: {r.Logs[^1]}"); + Check(r.Queries <= 242, $"asked about every 0.5 s, no busier (got {r.Queries})"); + } + + private static void ThrowingQueryNeverHolds() + { + _case = "query throws"; + var r = new Rig(); + r.Answer = _ => throw new InvalidOperationException("plugin list changed"); + var outcome = r.Make().Run(out TimeSpan waited); + Check(outcome == ReloadDeferral.Outcome.Clear, "a failed query doesn't hold the reload"); + Check(waited == TimeSpan.Zero, "no wait"); + Check(r.Logs.Count == 1 && r.Logs[0].Contains("asking the plugins failed"), "and it is logged"); + + // Throws while waiting: counts as clear too. + var w = new Rig(); + w.Answer = n => n == 1 ? InCombat : throw new InvalidOperationException("boom"); + Check(w.Make().Run(out _) == ReloadDeferral.Outcome.ClearedAfterWait, "a query that fails mid-wait ends the wait"); + } + + private static void SeveralPluginsDescribed() + { + _case = "describe"; + string d = ReloadDeferral.Describe(new[] { ("RynthAi", "in combat (a monster engaged)"), ("RynthLua", "busy (a script step)") }); + Check(d == "RynthAi in combat (a monster engaged); RynthLua busy (a script step)", $"joined: {d}"); + } +} diff --git a/tools/ReloadDeferralTests/ReloadDeferralTests.csproj b/tools/ReloadDeferralTests/ReloadDeferralTests.csproj new file mode 100644 index 0000000..ac22a40 --- /dev/null +++ b/tools/ReloadDeferralTests/ReloadDeferralTests.csproj @@ -0,0 +1,25 @@ + + + + + Exe + net10.0 + enable + enable + true + ReloadDeferralTests + + + + + + + diff --git a/tools/StatusAgentTests/Program.cs b/tools/StatusAgentTests/Program.cs new file mode 100644 index 0000000..20d2246 --- /dev/null +++ b/tools/StatusAgentTests/Program.cs @@ -0,0 +1,558 @@ +using System.Text; +using System.Text.Json; +using RynthCore.StatusAgent; + +namespace StatusAgentTests; + +/// +/// The StatusAgent's DrakRemote parity pieces, offline. Args (optional, read-only): +/// --portal PATH also read the real spell table from this portal.dat +/// --cell PATH also render the real world map from this cell.dat (prints size and timing) +/// --out FILE with --cell: write the rendered JPEG there to look at +/// +internal static class Program +{ + private static int _checks, _failed; + + private static int Main(string[] args) + { + string? portal = Arg(args, "--portal"), cell = Arg(args, "--cell"), outFile = Arg(args, "--out"); + + Landblocks(); + AppMatchesWithTheInstalledPhone(); + ClickMapping(); + Capabilities(); + SpellTable(); + Enchantments(); + PluginStatusAdditions(); + PayloadJsonNames(); + WorldMap(); + NavSearch(); + TravelStatus(); + RaiseCommand(); + StatusFileReads(); + MoveProtocol(); + if (Arg(args, "--atlas") is { } atlas) RealAtlas(atlas); + if (portal != null) RealSpellTable(portal); + if (cell != null) RealWorldMap(cell, outFile); + + Console.WriteLine(); + Console.WriteLine(_failed == 0 ? $"PASS ({_checks} checks)" : $"FAIL ({_failed} of {_checks} checks failed)"); + return _failed == 0 ? 0 : 1; + } + + // ── landblocks ────────────────────────────────────────────────────────── + + private static void Landblocks() + { + Section("landblock ids"); + Check(RemoteParity.LandblockFull("00005A48") == "5A480000", "engine short form \"00005A48\" -> \"5A480000\""); + Check(RemoteParity.LandblockFull("5A48") == "5A480000", "four digits -> full"); + Check(RemoteParity.LandblockFull("5A480000") == "5A480000", "full stays full"); + Check(RemoteParity.LandblockFull("5A48013F") == "5A480000", "a cell id drops its cell part"); + Check(RemoteParity.LandblockFull("") == "", "empty stays empty (outdoors at login)"); + Check(RemoteParity.LandblockFull("00000000") == "", "zero is no landblock"); + Check(RemoteParity.LandblockFull("zz") == "zz", "unparseable passes through"); + Check(RemoteParity.TryLandblockShort("5A480000", out uint a) && a == 0x5A48, "/map?lb=5A480000 -> 0x5A48"); + Check(RemoteParity.TryLandblockShort("00005A48", out uint b) && b == 0x5A48, "/map?lb=00005A48 -> 0x5A48"); + Check(RemoteParity.TryLandblockShort("5A48", out uint c) && c == 0x5A48, "/map?lb=5A48 -> 0x5A48"); + Check(!RemoteParity.TryLandblockShort("", out _) && !RemoteParity.TryLandblockShort("0", out _), "empty / zero refused"); + } + + /// DrakRemote v1.0.13 (cf0e206, on the phone now): AcMapEntry.LandblockId shifts a short id up, + /// AcClientStatus.LandblockId takes the id as written. The agent's output must match under those rules. + private static void AppMatchesWithTheInstalledPhone() + { + Section("matching under the installed app's rules"); + static uint MapRule(string s) => uint.TryParse(s, System.Globalization.NumberStyles.HexNumber, null, out var v) ? (v > 0xFFFF ? v : v << 16) : 0; + static uint ClientRule(string s) => uint.TryParse(s, System.Globalization.NumberStyles.HexNumber, null, out var v) ? v : 0; + + // Before: what the agent wrote (engine form for both) never matched. + Check(MapRule("00005A48") != ClientRule("00005A48"), "negative control: the old output does not match (the bug)"); + string map = RemoteParity.LandblockFull("00005A48"), client = RemoteParity.LandblockFull("00005A48"); + Check(MapRule(map) == ClientRule(client) && ClientRule(client) == 0x5A480000, "new output: map and client both 0x5A480000"); + // The image URL the app builds from the matched map: lb.ToString("X") of the parsed id. + string urlLb = MapRule(map).ToString("X"); + Check(RemoteParity.TryLandblockShort(urlLb, out uint file) && $"{file:X8}_1.bin" == "00005A48_1.bin", "the /map request finds the baked file 00005A48_1.bin"); + } + + // ── click mapping ─────────────────────────────────────────────────────── + + private static void ClickMapping() + { + Section("tap-to-click mapping"); + Check(RemoteParity.ClickPoint(0, 0, 1280, 720) == (0, 0), "top-left -> 0,0"); + Check(RemoteParity.ClickPoint(1, 1, 1280, 720) == (1279, 719), "bottom-right -> last pixel"); + Check(RemoteParity.ClickPoint(0.5, 0.5, 1280, 720) == (640, 360), "centre (rounded half away)"); + Check(RemoteParity.ClickPoint(0.25, 0.75, 1920, 1080) == (480, 809), "a quarter across, three quarters down"); + Check(RemoteParity.ClickPoint(-0.2, 1.4, 800, 600) == (0, 599), "out of range clamps to the edge"); + Check(RemoteParity.ClickPoint(double.NaN, double.PositiveInfinity, 800, 600) == (0, 0), "NaN / infinity -> origin, never an exception"); + // The same tap on a stream scaled down to 720 wide lands on the same game pixel (same aspect). + var native = RemoteParity.ClickPoint(812.0 / 1919, 300.0 / 1079, 1920, 1080); + Check(native == (812, 300), "a pixel picked on the native frame maps back to itself"); + long lp = (long)RemoteParity.MouseLParam(640, 360); + Check((lp & 0xFFFF) == 640 && ((lp >> 16) & 0xFFFF) == 360, "lParam: x low word, y high word"); + long big = (long)RemoteParity.MouseLParam(3839, 2159); + Check((big & 0xFFFF) == 3839 && ((big >> 16) & 0xFFFF) == 2159, "lParam holds a 4K client area"); + } + + // ── capabilities ──────────────────────────────────────────────────────── + + private static void Capabilities() + { + Section("capabilities"); + var all = new AgentConfig { EnableRemoteControl = true, EnableScreenStream = true, EnableVideoStream = true }; + var c = RemoteParity.Capabilities(all, iconDat: true, dungeonMaps: true, worldMap: true, characterSheets: true); + Check(c.Movement && c.CloseClient && c.Click && c.Video && c.VideoHd && c.Icons && c.Maps && c.WorldMap && c.Character, + "everything on when configured and present"); + Check(!c.Act && !c.Nearby && !c.Pick && !c.Dungeon && !c.VideoMinimized, "DrakBot-only routes stay off on RynthCore"); + + var readOnly = new AgentConfig(); + var r = RemoteParity.Capabilities(readOnly, iconDat: false, dungeonMaps: false, worldMap: false, characterSheets: false); + Check(!r.Movement && !r.CloseClient && !r.Click && !r.Video && !r.VideoHd, "a read-only agent offers no control or video"); + Check(!r.Icons && !r.Maps && !r.WorldMap && !r.Character, "nothing on disk -> no icons, maps or Skills tab"); + Check(r.Inventory && r.Settings && r.Runs, "the file-backed routes are always there"); + + var streamOnly = new AgentConfig { EnableScreenStream = true }; + Check(!RemoteParity.Capabilities(streamOnly, false, false, false, false).Click, "click needs remote control as well as the stream"); + Check(RemoteParity.Capabilities(readOnly, false, false, worldMap: true, false).Maps, "a world map alone lights the Map tab"); + } + + // ── spell table ───────────────────────────────────────────────────────── + + private static byte[] SpellTableFile(params (uint Id, string Name, uint School, uint Icon, uint Category, uint Flags, uint Meta)[] spells) + { + var w = new Writer(); + w.U32(0x0E00000E); + w.U16((ushort)spells.Length); + w.U16(64); + foreach (var s in spells) + { + w.U32(s.Id); + w.Obfuscated(s.Name); + w.Obfuscated("A description that is not read."); + w.U32(s.School); w.U32(s.Icon); w.U32(s.Category); w.U32(s.Flags); + w.U32(10); // base mana + w.Zero(8); // range constant, range mod + w.U32(150); // power + w.Zero(12); // economy mod, formula version, component loss + w.U32(s.Meta); w.U32(s.Id); + if (s.Meta is 1 or 12) w.Zero(16); + else if (s.Meta == 7) w.Zero(8); + w.Zero(8 * 4 + 12 + 8 + 4 + 12); + } + return w.ToArray(); + } + + private static void SpellTable() + { + Section("spell table parse"); + byte[] raw = SpellTableFile( + (2, "Strength Self I", 4, 0x06001234, 1, 0x4 | 0x8, 1), // creature, beneficial, enchantment + (1237, "Drain Health Other I", 2, 0x06002222, 83, 0x0, 1), // life, harmful + (157, "Summon Primary Portal I", 3, 0x06003333, 200, 0x4, 7), // a portal summon (different tail) + (4305, "Incantation of Strength Self", 4, 0x06004444, 1, 0x4 | 0x8, 1)); + var t = SpellTableService.Parse(raw, out int total); + Check(total == 4 && t.Count == 4, "all four spells read, including after a portal summon's shorter tail"); + Check(t.TryGetValue(2, out var s) && s.Name == "Strength Self I" && s.Icon == 0x06001234 && s.Category == 1 && s.Beneficial, "name, icon, family, beneficial"); + Check(t.TryGetValue(1237, out var d) && !d.Beneficial && d.School == 2, "a harmful spell is not beneficial"); + Check(t.TryGetValue(4305, out var inc) && inc.Name == "Incantation of Strength Self", "the spell after the portal summon is still aligned"); + Check(SpellTableService.TierFromName("Strength Self VII") == 7 && SpellTableService.TierFromName("Incantation of Strength Self") == 8 + && SpellTableService.TierFromName("Strength Self VIII") == 8 && SpellTableService.TierFromName("Aura of Defender") == 0, "tier from the name"); + var cut = SpellTableService.Parse(raw[..(raw.Length - 40)], out _); + Check(cut.Count == 3, "a truncated file keeps the spells before the cut and never throws"); + } + + private static void Enchantments() + { + Section("enchantments for the Buffs tab"); + var table = SpellTableService.Parse(SpellTableFile( + (2, "Strength Self I", 4, 0x06001234, 1, 0x4, 1), + (1237, "Drain Health Other I", 2, 0x06002222, 83, 0x0, 1)), out _); + SpellTableService.SpellInfo? Lookup(uint id) => table.TryGetValue(id, out var i) ? i : null; + + var input = new List + { + new() { SpellId = 2, SecondsRemaining = 1800 }, + new() { SpellId = 1237, SecondsRemaining = 42 }, + new() { SpellId = 99999, SecondsRemaining = -1 }, // permanent, unknown to the table + new() { SpellId = 0, SecondsRemaining = 10 }, // junk + }; + var outList = RemoteParity.Enchantments(input, Lookup)!; + Check(outList.Count == 3, "id 0 dropped"); + Check(outList[0].SpellId == 1237 && outList[1].SpellId == 2 && outList[2].SpellId == 99999, "soonest first, permanent last"); + Check(outList[1].Name == "Strength Self I" && outList[1].Family == 1 && outList[1].Tier == 1 && outList[1].IconId == 0x06001234 && outList[1].Beneficial, "named, family, tier, icon"); + Check(!outList[0].Beneficial, "a debuff reads as not beneficial (the app lists it under debuffs)"); + Check(outList[2].Name == "Spell 99999" && outList[2].IconId == 0 && outList[2].Beneficial && outList[2].SecondsRemaining == -1, "unknown spell: id as name, no icon, kept as a buff"); + Check(RemoteParity.Enchantments(null, Lookup) == null, "no enchantments from an older plugin -> null (the app shows nothing in force)"); + var before = RemoteParity.Enchantments(new() { new() { SpellId = 2, SecondsRemaining = 5 } }, _ => null)!; + Check(before[0].Name == "Spell 2", "before the table loads the countdown still works"); + } + + // ── what the plugin writes, read back by the agent ────────────────────── + + private static void PluginStatusAdditions() + { + Section("plugin status additions read by the agent"); + // A status file as the RynthRemote plugin 0.3 writes it: the engine object + bot + the two additions. + const string file = """ + {"schema":"rynthcore.client-status/1","pid":8808,"character":"Drakkon","inWorld":true, + "landblock":"0000A9B4","indoor":false,"area":"A9B4","bot":null, + "enchantments":[{"spellId":1237,"secondsRemaining":42},{"spellId":2,"secondsRemaining":1800},{"spellId":4305,"secondsRemaining":-1}], + "opos":{"cell":"A9B40031","indoor":false,"wx":32549.12,"wy":34620.5,"z":42.03,"heading":271.5}} + """; + var m = JsonSerializer.Deserialize(file, AgentJsonContext.Default.StatusFileModel)!; + Check(m.Enchantments is { Count: 3 } && m.Enchantments[0].SpellId == 1237 && m.Enchantments[2].SecondsRemaining == -1, "enchantments parsed"); + Check(m.Opos is { Wx: 32549.12, Wy: 34620.5, Heading: 271.5 } && m.Opos.Cell == "A9B40031", "outdoor position parsed"); + var old = JsonSerializer.Deserialize("""{"schema":"rynthcore.client-status/1","pid":1,"landblock":"","indoor":false}""", AgentJsonContext.Default.StatusFileModel)!; + Check(old.Enchantments == null && old.Opos == null, "an older plugin's file still reads (fields absent)"); + // The world map pixel for that position: 32549.12/24 = 1356.2, 2040 - 34620.5/24 = 597.5. + var (px, py) = WorldMapService.ToPixel(m.Opos!.Wx, m.Opos.Wy); + Check(Math.Abs(px - 1356.21) < 0.01 && Math.Abs(py - 597.48) < 0.01, "world map pixel for the outdoor position"); + } + + private static void PayloadJsonNames() + { + Section("JSON names the phone reads"); + var payload = new AggregatePayload + { + Host = "PC", ClientCount = 1, + Capabilities = RemoteParity.Capabilities(new AgentConfig { EnableRemoteControl = true, EnableScreenStream = true }, true, true, true, true), + Clients = + { + new ClientStatus + { + Pid = 8808, Landblock = RemoteParity.LandblockFull("00005A48"), Indoor = true, Heading = 90, + Enchantments = new() { new EnchantmentOut { SpellId = 2, Name = "Strength Self I", SecondsRemaining = 1800, IconId = 0x06001234 } }, + }, + }, + }; + string json = Encoding.UTF8.GetString(JsonSerializer.SerializeToUtf8Bytes(payload, AgentJsonContext.Default.AggregatePayload)); + using var doc = JsonDocument.Parse(json); + var root = doc.RootElement; + Check(root.TryGetProperty("capabilities", out var caps) && caps.GetProperty("click").GetBoolean() && caps.GetProperty("worldMap").GetBoolean() + && caps.GetProperty("character").GetBoolean() && !caps.GetProperty("act").GetBoolean(), "capabilities: click, worldMap, character, act"); + var c = root.GetProperty("clients")[0]; + Check(c.GetProperty("landblock").GetString() == "5A480000", "client landblock in full form"); + var e = c.GetProperty("enchantments")[0]; + Check(e.GetProperty("spellId").GetUInt32() == 2 && e.GetProperty("name").GetString() == "Strength Self I" + && e.GetProperty("secondsRemaining").GetDouble() == 1800 && e.GetProperty("iconId").GetUInt32() == 0x06001234 + && e.TryGetProperty("family", out _) && e.TryGetProperty("tier", out _) && e.TryGetProperty("beneficial", out _) && e.TryGetProperty("school", out _), + "enchantment entry has DrakBot's field names"); + Check(c.GetProperty("heading").GetDouble() == 90, "heading"); + } + + // ── world map ─────────────────────────────────────────────────────────── + + private static byte[] Landblock(ushort terrainWord, byte height, Func? heightAt = null) + { + var b = new byte[8 + 81 * 2 + 81]; + for (int i = 0; i < 81; i++) + { + BitConverter.GetBytes(terrainWord).CopyTo(b, 8 + i * 2); + b[8 + 162 + i] = heightAt?.Invoke(i) ?? height; + } + return b; + } + + private static void WorldMap() + { + Section("world map render"); + // Landblock 0x0000 (south-west corner) is snow; 0xFE00 (south-east) grassland with a road word; + // 0x00FE (north-west) is sand; everything else open sea. + ushort snow = 15 << 2, grass = 1 << 2, road = (1 << 2) | 1, sand = 10 << 2; + var blocks = new Dictionary + { + [0x0000] = Landblock(snow, 10), + [0xFE00] = Landblock(road, 10), + [0x00FE] = Landblock(sand, 10), + [0x8080] = Landblock(grass, 0, i => (byte)(i / 9 * 4)), // rising to the east: lit from the north-west + }; + byte[] rgb = WorldMapService.Render(lb => blocks.TryGetValue(lb, out var r) ? r : null, out int found); + int size = WorldMapService.Size; + Check(size == 2040 && rgb.Length == size * size * 3, "2040 x 2040 RGB"); + Check(found == 4, "four landblocks drawn"); + (byte R, byte G, byte B) Px(int x, int y) { int o = (y * size + x) * 3; return (rgb[o], rgb[o + 1], rgb[o + 2]); } + Check(Px(0, size - 1) == (0xF0, 0xF4, 0xF7), "south-west corner is snow, at the bottom-left (north up)"); + Check(Px(0, 0) == (0xD8, 0xC4, 0x8A), "landblock 0x00FE (north) is at the top: sand"); + Check(Px(0xFE * 8, size - 1) == (0xA8, 0x93, 0x6C), "a road word draws as road"); + Check(Px(1000, 1000) == (0x1F, 0x4A, 0x78), "no landblock -> sea"); + var g = Px(0x80 * 8 + 3, size - 1 - (0x80 * 8 + 3)); + Check(g.G > 0x8B, "a slope rising east is lit brighter than flat grass"); + var (wx, wy) = (0x80 * 192.0 + 72, 0x80 * 192.0 + 72); // that cell's corner, in world units + var (mx, my) = WorldMapService.ToPixel(wx, wy); + Check((int)mx == 0x80 * 8 + 3 && (int)Math.Ceiling(my) - 1 == size - 1 - (0x80 * 8 + 3), "ToPixel lands on the cell that was painted"); + } + + // ── travel ────────────────────────────────────────────────────────────── + + private const string AtlasJson = """ + {"version":1,"generated":"2026-10-01T09:59:37Z","locations":[ + {"name":"Holtburg","type":"Town","cell":"A9B40001","place":"outdoor","ns":42.10,"ew":33.60,"id":1}, + {"name":"Holtburg Dungeon","type":"Dungeon","cell":"A9B20001","place":"outdoor","ns":43.57,"ew":32.98,"id":2}, + {"name":"Holtburg Portal Shrine","type":"Portal","cell":"A9B40010","place":"outdoor","ns":42.20,"ew":33.50,"id":3,"dest":{"name":"Town Network"}}, + {"name":"Barkeeper Holtburg","type":"NPC","cell":"A9B4011A","place":"outdoor","ns":42.15,"ew":33.62,"id":4}, + {"name":"Secret Room of Holtburg","type":"Landmark","cell":"01E901AD","place":"dungeon","id":5}, + {"name":"Shoushi","type":"Town","cell":"DE510001","place":"outdoor","ns":-33.50,"ew":72.80,"id":6}, + {"name":"Lifestone","type":"Lifestone","cell":"A9B40020","place":"outdoor","ns":42.05,"ew":33.55,"id":7}, + {"name":"Closed Mine","type":"Dungeon","place":"outdoor","ns":40.0,"ew":30.0,"id":8,"closed":true} + ]} + """; + + private static void NavSearch() + { + Section("travel search (RynthNav's Atlas ranking)"); + var (places, generated) = NavAtlasService.Parse(AtlasJson); + Check(places.Count == 8 && generated == "2026-10-01T09:59:37Z", "Atlas read"); + var hits = NavAtlasService.Search(places, "holtburg", null, null, null, 40); + Check(hits.Select(h => h.Place.Name).SequenceEqual(new[] { "Holtburg", "Holtburg Dungeon", "Holtburg Portal Shrine", "Secret Room of Holtburg", "Barkeeper Holtburg" }), + "exact name, then starts-with by type (town, dungeon, portal), then whole-word, then inside a name - as in game"); + Check(NavAtlasService.Search(places, "holtburg", "Dungeon", null, null, 40).Single().Place.Name == "Holtburg Dungeon", "type filter"); + Check(NavAtlasService.Search(places, "h", null, null, null, 40).Count == 0, "one letter is too little to search"); + Check(NavAtlasService.Search(places, "holt dung", null, null, null, 40).Single().Place.Name == "Holtburg Dungeon", "every word somewhere in the name"); + var near = NavAtlasService.Search(places, "holtburg", null, 42.10, 33.60, 40); + Check(near[0].Distance == 0 && near[1].Distance is > 300 and < 400, "distance from the character, in RynthNav's units (240 a degree)"); + Check(near.Single(h => h.Place.Name == "Secret Room of Holtburg").Distance == null, "a place inside a dungeon has no distance"); + Check(NavAtlasService.Search(places, "holtburg", null, null, null, 2).Count == 2, "max"); + + Check(places.Single(p => p.Name == "Lifestone").Area == "near Holtburg" && places.Single(p => p.Name == "Holtburg").Area == "", "area = nearest town (a town is its own)"); + using var doc = JsonDocument.Parse(NavAtlasService.SearchJson(NavAtlasService.Search(places, "holtburg", null, 42.10, 33.60, 40), "holtburg", places.Count, generated)); + var root = doc.RootElement; + Check(root.GetProperty("schema").GetString() == "rynthcore.nav-search/1" && root.GetProperty("count").GetInt32() == 5, "search JSON"); + var r0 = root.GetProperty("results")[0]; + Check(r0.GetProperty("name").GetString() == "Holtburg" && r0.GetProperty("type").GetString() == "Town" && r0.GetProperty("coords").GetString() == "42.1N, 33.6E" + && r0.GetProperty("ns").GetDouble() == 42.1 && r0.GetProperty("canTravel").GetBoolean() && r0.GetProperty("distance").GetDouble() == 0, "a result: name, type, coords, distance, can travel"); + var secret = root.GetProperty("results").EnumerateArray().Single(e => e.GetProperty("name").GetString() == "Secret Room of Holtburg"); + Check(!secret.GetProperty("canTravel").GetBoolean() && !secret.TryGetProperty("ns", out _) && secret.GetProperty("where").GetString() == "dungeon", "inside a dungeon: listed, can't travel (RynthNav won't guess)"); + var closed = NavAtlasService.SearchJson(NavAtlasService.Search(places, "closed", null, null, null, 5), "closed", 8, ""); + Check(closed.Contains("\"closed\":true") && closed.Contains("\"canTravel\":false"), "a closed place can't be travelled to"); + Check(NavAtlasService.Fmt(-33.5, 72.8) == "33.5S, 72.8E", "coordinates like RynthNav's"); + var (wns, wew) = NavAtlasService.FromWorld((33.6 * 10 + 1019.5) * 24, (42.1 * 10 + 1019.5) * 24); + Check(Math.Abs(wns - 42.1) < 1e-9 && Math.Abs(wew - 33.6) < 1e-9, "world units -> coordinates"); + + var cfg = new AgentConfig { EnableRemoteControl = true }; + Check(RemoteParity.Capabilities(cfg, false, false, false, false, navAtlas: true).Travel, "travel on with the Atlas and remote control"); + Check(!RemoteParity.Capabilities(new AgentConfig(), false, false, false, false, navAtlas: true).Travel, "no remote control -> no travel (the Go would be refused)"); + Check(!RemoteParity.Capabilities(cfg, false, false, false, false, navAtlas: false).Travel, "no Atlas -> no travel"); + } + + private static void TravelStatus() + { + Section("travel status"); + var sent = new TravelIn { Dest = "Holtburg", Ns = 42.1, Ew = 33.6, State = "sent", SentAt = DateTimeOffset.UtcNow }; + var chat = new List + { + new() { Text = "[RynthNav] walking to Holtburg (2.1k yd) — /rnav stop to cancel" }, + new() { Text = "Drakkon says, \"hi\"" }, + }; + // Standing 1 degree south of Holtburg: 240 units left. + var t = RemoteParity.Travel(sent, chat, indoor: false, wx: (33.6 * 10 + 1019.5) * 24, wy: (41.1 * 10 + 1019.5) * 24)!; + Check(t.State == "sent" && t.Note == "walking to Holtburg (2.1k yd) — /rnav stop to cancel", "RynthNav's latest note, tag removed"); + Check(t.Distance == 240, "distance left from the character's position"); + chat.Add(new ChatLine { Text = "[RynthNav] Arrived at Holtburg." }); + Check(RemoteParity.Travel(sent, chat, false, 1, 1)!.State == "arrived", "RynthNav's arrival note -> arrived"); + chat.Add(new ChatLine { Text = "[RynthNav] Arrived at Shoushi." }); + Check(RemoteParity.Travel(sent, chat, false, 1, 1)!.State == "sent", "arriving somewhere else doesn't count"); + Check(RemoteParity.Travel(sent, chat, indoor: true, 1, 1)!.Distance == null, "no distance indoors"); + Check(RemoteParity.Travel(null, chat, false, 1, 1) == null && RemoteParity.Travel(new TravelIn(), chat, false, 1, 1) == null, "no travel yet -> null"); + var stopped = RemoteParity.Travel(new TravelIn { Dest = "Holtburg", State = "stopped" }, null, false, 0, 0)!; + Check(stopped.State == "stopped" && stopped.Note == "" && stopped.Distance == null, "stopped, no chat, no position"); + // The plugin's status.json entry, read back. + var m = JsonSerializer.Deserialize("""{"schema":"rynthcore.client-status/1","pid":1,"travel":{"dest":"Holtburg","ns":42.1,"ew":33.6,"state":"sent","detail":"","sentAt":"2026-10-05T09:00:00Z"}}""", + AgentJsonContext.Default.StatusFileModel)!; + Check(m.Travel is { Dest: "Holtburg", State: "sent", Ns: 42.1 } && m.Travel.SentAt == new DateTimeOffset(2026, 10, 5, 9, 0, 0, TimeSpan.Zero), "plugin travel entry parsed"); + } + + private static void RealAtlas(string path) + { + Section("real Atlas (read-only) " + path); + var (places, generated) = NavAtlasService.Parse(File.ReadAllText(path)); + Console.WriteLine($" {places.Count:N0} places, generated {generated}"); + Check(places.Count > 5000, "the Atlas has thousands of places"); + var hits = NavAtlasService.Search(places, "holtburg", null, 42.1, 33.6, 10); + Console.WriteLine(" " + string.Join(" | ", hits.Select(h => $"{h.Place.Name} ({h.Place.Type}{(h.Place.Area.Length > 0 ? ", " + h.Place.Area : "")}{(h.Distance is double d ? $", {d:0} yd" : "")})"))); + Check(hits.Count > 0 && hits[0].Place.Name == "Holtburg" && hits[0].Place.Type == "Town", "\"holtburg\" finds the town first"); + } + + private static void RealSpellTable(string portal) + { + Section("real spell table (read-only) " + portal); + using var db = new RynthCore2.TerrainData.DatDatabase(); + Check(db.Open(portal), "portal.dat opens"); + byte[]? raw = db.GetFileData(0x0E00000E); + Check(raw != null, "spell table present"); + if (raw == null) return; + var t = SpellTableService.Parse(raw, out int total); + Console.WriteLine($" {t.Count:N0} of {total:N0} spells"); + Check(t.Count == total && total > 5000, "every spell parsed"); + Check(t.TryGetValue(2, out var s) && s.Name == "Strength Self I" && s.Beneficial && s.Icon != 0, "spell 2 is Strength Self I, beneficial, with an icon"); + } + + private static void RealWorldMap(string cell, string? outFile) + { + Section("real world map (read-only) " + cell); + var sw = System.Diagnostics.Stopwatch.StartNew(); + using var db = new RynthCore2.TerrainData.DatDatabase(); + Check(db.Open(cell), "cell.dat opens"); + Console.WriteLine($" indexed in {sw.Elapsed.TotalSeconds:0.0}s"); + byte[] rgb = WorldMapService.Render(lb => db.GetFileData(((uint)lb << 16) | 0xFFFF), out int found); + Console.WriteLine($" {found:N0} landblocks in {sw.Elapsed.TotalSeconds:0.0}s"); + Check(found > 20000, "most of Dereth's landblocks found"); + if (outFile != null) + { + string dir = Path.Combine(Path.GetTempPath(), "rc-worldmap-test-" + Guid.NewGuid().ToString("N")); + var svc = new WorldMapService(cell, dir); + byte[]? jpg = null; + for (int i = 0; i < 600 && (jpg = svc.GetJpeg()) == null; i++) Thread.Sleep(200); + Check(jpg != null, "the service renders and caches a JPEG"); + if (jpg != null) { File.WriteAllBytes(outFile, jpg); Console.WriteLine($" {jpg.Length / 1024:N0} KB -> {outFile}"); } + try { Directory.Delete(dir, true); } catch { } + } + } + + // ── helpers ───────────────────────────────────────────────────────────── + + private sealed class Writer + { + private readonly MemoryStream _ms = new(); + public void U32(uint v) => _ms.Write(BitConverter.GetBytes(v)); + public void U16(ushort v) => _ms.Write(BitConverter.GetBytes(v)); + public void Zero(int n) => _ms.Write(new byte[n]); + public void Obfuscated(string s) + { + byte[] b = Encoding.Latin1.GetBytes(s); + U16((ushort)b.Length); + foreach (byte x in b) _ms.WriteByte((byte)((x >> 4) | (x << 4))); + while (_ms.Length % 4 != 0) _ms.WriteByte(0); + } + public byte[] ToArray() => _ms.ToArray(); + } + + private static string? Arg(string[] args, string name) + { + int i = Array.IndexOf(args, name); + return i >= 0 && i + 1 < args.Length ? args[i + 1] : null; + } + + // ── raise (Skills tab "+") ────────────────────────────────────────────── + + private static void RaiseCommand() + { + Section("raise command (POST /command action raise)"); + var control = new AgentConfig { EnableRemoteControl = true }; + Check(RemoteParity.Capabilities(control, false, false, false, characterSheets: true, raiseXp: true).RaiseXp, "raiseXp on: control + a sheet + a client that can"); + Check(!RemoteParity.Capabilities(new AgentConfig(), false, false, false, true, raiseXp: true).RaiseXp, "off without remote control"); + Check(!RemoteParity.Capabilities(control, false, false, false, true, raiseXp: false).RaiseXp, "off when no client can (old engine or plugin)"); + Check(!RemoteParity.Capabilities(control, false, false, false, characterSheets: false, raiseXp: true).RaiseXp, "off without character sheets (nothing to show costs from)"); + + var clients = new Dictionary { [8808] = true, [9100] = false }; + int code = RemoteParity.CheckRaise(8808, """{"kind":"attribute","id":5,"count":1,"cost":1234567,"nonce":"k3f9","extra":"dropped"}""", clients, out string norm, out string err); + Check(code == 202 && norm == """{"kind":"attribute","id":5,"count":1,"cost":1234567,"nonce":"k3f9"}""", "accepted and rewritten in the fixed shape (extra members dropped)"); + code = RemoteParity.CheckRaise(8808, """{"kind":"Vital","id":"Stamina","count":10,"cost":42}""", clients, out norm, out _); + Check(code == 202 && norm == """{"kind":"vital","id":"stamina","count":10,"cost":42,"nonce":""}""", "vital by name, lower-cased"); + code = RemoteParity.CheckRaise(8808, """{"kind":"train","id":22,"cost":6,"count":77}""", clients, out norm, out _); + Check(code == 202 && norm.Contains("\"count\":1"), "train: count forced to 1"); + Check(RemoteParity.CheckRaise(1234, """{"kind":"attribute","id":5,"cost":1}""", clients, out _, out err) == 404 && err == "unknown client", "a pid the agent doesn't read -> 404"); + Check(RemoteParity.CheckRaise(9100, """{"kind":"attribute","id":5,"cost":1}""", clients, out _, out err) == 409 && err.Contains("plugin API 79"), "a client without raising -> 409 with why"); + Check(RemoteParity.CheckRaise(8808, """{"kind":"attribute","id":5,"count":1}""", clients, out _, out err) == 400 && err.Contains("confirmed cost"), "no confirmed cost -> 400"); + Check(RemoteParity.CheckRaise(8808, """{"kind":"attribute","id":5,"cost":0}""", clients, out _, out _) == 400, "cost 0 -> 400"); + Check(RemoteParity.CheckRaise(8808, """{"kind":"attribute","id":5,"cost":4294967296}""", clients, out _, out _) == 400, "cost over 32 bits -> 400"); + Check(RemoteParity.CheckRaise(8808, """{"kind":"attribute","id":9,"cost":1}""", clients, out _, out _) == 400 + && RemoteParity.CheckRaise(8808, """{"kind":"vital","id":2,"cost":1}""", clients, out _, out _) == 400 + && RemoteParity.CheckRaise(8808, """{"kind":"skill","id":"34","cost":1}""", clients, out _, out _) == 400, "bad ids -> 400"); + Check(RemoteParity.CheckRaise(8808, """{"kind":"skill","id":34,"count":101,"cost":1}""", clients, out _, out _) == 400 + && RemoteParity.CheckRaise(8808, """{"kind":"skill","id":34,"count":0,"cost":1}""", clients, out _, out _) == 400, "count out of 1..100 -> 400"); + Check(RemoteParity.CheckRaise(8808, """{"kind":"luminance","id":1,"cost":1}""", clients, out _, out _) == 400 + && RemoteParity.CheckRaise(8808, "not json", clients, out _, out _) == 400 + && RemoteParity.CheckRaise(8808, "", clients, out _, out _) == 400, "unknown kind / junk / empty -> 400"); + code = RemoteParity.CheckRaise(8808, "{\"kind\":\"skill\",\"id\":34,\"cost\":5,\"nonce\":\"a\\\"},{\\\"x\"}", clients, out norm, out _); + Check(code == 202 && norm.EndsWith("\"nonce\":\"ax\"}") && JsonDocument.Parse(norm).RootElement.GetProperty("nonce").GetString() == "ax", "a nonce can't break out of its string"); + + // The plugin's flag reaches the client and the phone's JSON. + var m = JsonSerializer.Deserialize("""{"schema":"rynthcore.client-status/1","pid":1,"raiseXp":true}""", AgentJsonContext.Default.StatusFileModel)!; + Check(m.RaiseXp, "status.json raiseXp read"); + var old = JsonSerializer.Deserialize("""{"schema":"rynthcore.client-status/1","pid":1}""", AgentJsonContext.Default.StatusFileModel)!; + Check(!old.RaiseXp, "an older plugin: no raiseXp -> false"); + string json = JsonSerializer.Serialize(new AggregatePayload + { + Capabilities = RemoteParity.Capabilities(control, false, false, false, true, raiseXp: true), + Clients = { new ClientStatus { Pid = 1, RaiseXp = true } }, + }, AgentJsonContext.Default.AggregatePayload); + using var doc = JsonDocument.Parse(json); + Check(doc.RootElement.GetProperty("capabilities").GetProperty("raiseXp").GetBoolean() + && doc.RootElement.GetProperty("clients")[0].GetProperty("raiseXp").GetBoolean(), "capabilities.raiseXp and clients[].raiseXp in the payload"); + } + + // The flicker's back-end half: a status file caught mid-write must not drop its client from a snapshot, + // and a read must not stop the plugin's atomic replace. + private static void StatusFileReads() + { + Section("status files: shared reads and the last good parse"); + string dir = Path.Combine(Path.GetTempPath(), "statusagent-tests-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(dir); + try + { + string path = Path.Combine(dir, "RynthCore.25580.status.json"); + File.WriteAllText(path, """{"schema":"rynthcore.client-status/1","pid":25580,"character":"Lucy McJuicy","moveProto":2}"""); + static StatusFileModel? Parse(string t) => JsonSerializer.Deserialize(t, AgentJsonContext.Default.StatusFileModel); + var t0 = new DateTime(2026, 10, 5, 11, 21, 21, DateTimeKind.Utc); + var m = StatusFileCache.Read(path, Parse, t0); + Check(m?.Character == "Lucy McJuicy" && m.MoveProto == 2, "a good file reads (and carries moveProto)"); + + // What the agent used to see: the plugin's in-place fallback caught half-written. + File.WriteAllText(path, """{"schema":"rynthcore.client-status/1","pid":25580,"charac"""); + var torn = StatusFileCache.Read(path, Parse, t0.AddMilliseconds(60)); + Check(torn != null && ReferenceEquals(torn, m), "a torn file answers the last good parse - the client stays in the snapshot"); + File.WriteAllText(path, ""); + Check(StatusFileCache.Read(path, Parse, t0.AddMilliseconds(120)) is { Character: "Lucy McJuicy" }, "an empty file too"); + Check(StatusFileCache.Read(path, Parse, t0.AddSeconds(3.5)) == null, "but not for longer than 3 s (a file that stays broken is a real problem)"); + Check(StatusFileCache.Read(Path.Combine(dir, "missing.json"), Parse, t0) == null, "a missing file with no history is just missing"); + + // While the agent has the file open, the plugin's replace (File.Move over it) fails on Windows + // whatever the read's sharing (MoveFileEx won't replace an open file). RynthRemote 0.3 then + // overwrote the file in place, which is what tore it; 0.4 skips that one write instead. The two + // halves the agent relies on: the replace really fails mid-read (so skipping is needed), and the + // shared read doesn't block an old plugin's in-place rewrite (its torn result is covered above). + File.WriteAllText(path, """{"pid":1,"character":"old"}"""); + using (var reader = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete)) + { + string tmp = path + ".tmp"; + File.WriteAllText(tmp, """{"pid":1,"character":"new"}"""); + bool moved; + try { File.Move(tmp, path, overwrite: true); moved = true; } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { moved = false; } + Check(!moved, "a replace fails while the agent reads - why RynthRemote 0.4 skips that write instead of overwriting in place"); + try { File.Delete(tmp); } catch { } + bool rewrote; + try { File.WriteAllText(path, """{"pid":1,"character":"inplace"}"""); rewrote = true; } catch (IOException) { rewrote = false; } + Check(rewrote, "an old plugin's in-place rewrite isn't blocked by the agent's read (no more 'status write failed')"); + } + Check(StatusFileCache.ReadAllTextShared(path).Contains("inplace"), "and the next read sees it"); + + StatusFileCache.Read(path, Parse, t0); + StatusFileCache.ForgetAllBut(Array.Empty()); + Check(StatusFileCache.CountForTests == 0, "files that are gone are forgotten"); + } + finally { try { Directory.Delete(dir, true); } catch { } } + } + + private static void MoveProtocol() + { + Section("hold-to-move protocol passes through"); + var payload = new AggregatePayload { Host = "PC", ClientCount = 2, Clients = { new ClientStatus { Pid = 1, MoveProto = 2 }, new ClientStatus { Pid = 2 } } }; + using var doc = JsonDocument.Parse(JsonSerializer.SerializeToUtf8Bytes(payload, AgentJsonContext.Default.AggregatePayload)); + var cs = doc.RootElement.GetProperty("clients"); + Check(cs[0].GetProperty("moveProto").GetInt32() == 2, "a RynthRemote 0.4 client says moveProto 2"); + Check(!cs[1].TryGetProperty("moveProto", out var mp) || mp.GetInt32() == 0, "an older plugin's client: 0 or absent, the phone uses the old protocol"); + var old = JsonSerializer.Deserialize("""{"pid":1}""", AgentJsonContext.Default.StatusFileModel)!; + Check(old.MoveProto == 0, "a status file without the field reads as 0"); + } + + private static void Section(string title) => Console.WriteLine("\n== " + title); + + private static void Check(bool ok, string what) + { + _checks++; + if (!ok) _failed++; + Console.WriteLine((ok ? " ok " : " FAIL ") + what); + } +} diff --git a/tools/StatusAgentTests/StatusAgentTests.csproj b/tools/StatusAgentTests/StatusAgentTests.csproj new file mode 100644 index 0000000..d47a65e --- /dev/null +++ b/tools/StatusAgentTests/StatusAgentTests.csproj @@ -0,0 +1,37 @@ + + + + + Exe + net10.0-windows + enable + enable + true + StatusAgentTests + + + + + + + + + + + + + + + + + + + diff --git a/tools/TrainingCostTests/Program.cs b/tools/TrainingCostTests/Program.cs new file mode 100644 index 0000000..9ce20f3 --- /dev/null +++ b/tools/TrainingCostTests/Program.cs @@ -0,0 +1,214 @@ +using RynthCore.Engine.Compatibility; +using RynthCore.Engine.UI.ScriptWindows; +using RynthCore.PluginSdk; + +namespace TrainingCostTests; + +/// +/// Spending experience, offline: the portal XpTable as the engine reads it, the XP a raise of +/// n ranks costs (what the engine sends and the phone shows), and the checks a raise from the +/// plugin API must pass before anything is sent. +/// +internal static class Program +{ + private static int _checks, _failed; + + private static int Main(string[] args) + { + string dat = FindDat(args.Length > 0 ? args[0] : @"C:\Turbine\Asheron's Call"); + XpTableData? t = RealTable(dat); + if (t != null) + { + TableShape(t); + CostsOnTheRealTable(t); + AffordableMatchesALinearScan(t); + RaiseChecks(t); + } + TrainChecks(); + ParserRefusesJunk(); + SdkNumbersMatch(); + Console.WriteLine(); + Console.WriteLine(_failed == 0 && _checks > 0 ? $"PASS ({_checks} checks)" : $"FAIL ({_failed} of {_checks} checks failed)"); + return _failed == 0 && _checks > 0 ? 0 : 1; + } + + private static string FindDat(string arg) + { + if (File.Exists(arg)) return arg; + foreach (string name in new[] { "client_portal.dat", "portal.dat" }) + { + string p = Path.Combine(arg, name); + if (File.Exists(p)) return p; + } + return Path.Combine(arg, "client_portal.dat"); + } + + private static XpTableData? RealTable(string path) + { + Section("the XpTable (0x0E000018) from " + path); + using AcDatFile? dat = AcDatFile.Open(path, out string why); + Check(dat != null, "portal dat opens read-only" + (dat == null ? ": " + why : "")); + if (dat == null) return null; + byte[]? raw = dat.Read(0x0E000018, 1024 * 1024); + Check(raw != null && raw.Length > 100, "XpTable present"); + if (raw == null) return null; + bool ok = TrainingCosts.TryParseXpTable(raw, out XpTableData t); + Check(ok, "XpTable parses"); + Console.WriteLine($" ranks: attributes {t.AttributeXp.Length - 1}, vitals {t.VitalXp.Length - 1}, trained {t.TrainedXp.Length - 1}, specialized {t.SpecializedXp.Length - 1}, levels {t.LevelXp.Length - 1}"); + return ok ? t : null; + } + + private static void TableShape(XpTableData t) + { + Section("table shape (retail: 190 attribute, 196 vital, 208 trained, 226 specialized ranks, 275 levels)"); + Check(t.AttributeXp.Length == 191 && t.VitalXp.Length == 197 && t.TrainedXp.Length == 209 && t.SpecializedXp.Length == 227, + "rank counts"); + Check(t.LevelXp.Length == 276, "level count"); + foreach (var (name, a) in Tables(t)) + { + Check(a[0] == 0, name + ": rank 0 costs nothing"); + bool rising = true; + for (int i = 1; i < a.Length; i++) if (a[i] <= a[i - 1]) rising = false; + Check(rising, name + ": strictly rising (every rank costs something)"); + } + Check(t.AttributeXp[^1] == 4_019_438_644u, $"attribute top = 4,019,438,644 XP (retail max attribute XP) - got {t.AttributeXp[^1]:N0}"); + Check(t.SpecializedXp[^1] == 4_100_490_438u, $"specialized top = 4,100,490,438 XP - got {t.SpecializedXp[^1]:N0}"); + } + + private static void CostsOnTheRealTable(XpTableData t) + { + Section("costs: table[ranks + n] - spent"); + uint[] a = t.AttributeXp; + Check(TrainingCosts.CostOf(a, 0, 0, 1) == a[1], "+1 from rank 0 = table[1]"); + Check(TrainingCosts.CostOf(a, 50, a[50], 1) == a[51] - a[50], "+1 from rank 50, nothing extra spent"); + Check(TrainingCosts.CostOf(a, 50, a[50] + 1000, 1) == a[51] - a[50] - 1000, "XP already put toward the next rank comes off"); + Check(TrainingCosts.CostOf(a, 50, a[50], 10) == a[60] - a[50], "+10 = table[ranks + 10] - spent"); + // +10 equals ten +1s in a row (the server raises as far as the XP covers). + foreach (var (name, tab) in Tables(t)) + { + bool same = true; + for (uint r = 0; r + 10 < tab.Length; r += 7) + { + uint spent = tab[r] + (r % 3 == 0 ? 0u : Math.Min(5u, tab[r + 1] - tab[r] - 1)); + long ten = TrainingCosts.CostOf(tab, r, spent, 10); + long chained = 0; uint rr = r, sp = spent; + for (int k = 0; k < 10; k++) { long c = TrainingCosts.CostOf(tab, rr, sp, 1); chained += c; sp = (uint)(sp + c); rr++; } + if (ten != chained) same = false; + } + Check(same, name + ": +10 = ten +1s"); + } + int top = a.Length - 1; + Check(TrainingCosts.CostOf(a, (uint)top, a[top], 1) == -1 && TrainingCosts.IsMax(a, (uint)top), "at the top: -1, IsMax"); + Check(TrainingCosts.CostOf(a, (uint)top - 5, a[top - 5], 10) == -1 && TrainingCosts.CostOf(a, (uint)top - 5, a[top - 5], 5) > 0, + "+10 with five ranks left: -1 (+5 still prices)"); + Check(TrainingCosts.RanksLeft(a, (uint)top - 5) == 5 && TrainingCosts.RanksLeft(a, (uint)top) == 0, "ranks left"); + Check(TrainingCosts.CostOf(a, 0, 0, 0) == 0, "+0 costs 0"); + // A few numbers for the report / the phone's first test. + Console.WriteLine($" attribute rank 10 -> 11: {TrainingCosts.CostOf(a, 10, a[10], 1):N0} XP; +10: {TrainingCosts.CostOf(a, 10, a[10], 10):N0} XP"); + Console.WriteLine($" vital rank 10 -> 11: {TrainingCosts.CostOf(t.VitalXp, 10, t.VitalXp[10], 1):N0} XP"); + Console.WriteLine($" trained rank 10 -> 11: {TrainingCosts.CostOf(t.TrainedXp, 10, t.TrainedXp[10], 1):N0}; specialized: {TrainingCosts.CostOf(t.SpecializedXp, 10, t.SpecializedXp[10], 1):N0}"); + Console.WriteLine($" attribute rank 180 -> 181: {TrainingCosts.CostOf(a, 180, a[180], 1):N0} XP"); + } + + private static void AffordableMatchesALinearScan(XpTableData t) + { + Section("affordable ranks (binary search) = a linear scan"); + var rnd = new Random(79); + bool all = true; + foreach (var (_, tab) in Tables(t)) + for (int i = 0; i < 400; i++) + { + uint r = (uint)rnd.Next(0, tab.Length); + uint spent = tab[r] + (r + 1 < tab.Length ? (uint)rnd.Next(0, (int)Math.Min(int.MaxValue, tab[r + 1] - tab[r])) : 0u); + long have = rnd.Next(4) switch { 0 => 0, 1 => rnd.Next(), 2 => (long)rnd.Next() * 50, _ => long.MaxValue / 4 }; + int lin = 0; + for (int n = 1; ; n++) + { + long c = TrainingCosts.CostOf(tab, r, spent, n); + if (c < 0 || c > have) break; + lin = n; + } + if (TrainingCosts.Affordable(tab, r, spent, have) != lin) all = false; + } + Check(all, "1,600 random ranks / XP amounts on the four tables"); + Check(TrainingCosts.Affordable(t.AttributeXp, 0, 0, long.MaxValue) == t.AttributeXp.Length - 1, "unlimited XP buys every rank"); + } + + private static void RaiseChecks(XpTableData t) + { + Section("the checks before a raise is sent (CheckRaise)"); + uint[] a = t.AttributeXp; + long c1 = TrainingCosts.CostOf(a, 100, a[100], 1); + Check(TrainingCosts.CheckRaise(a, 100, a[100], c1, 1, c1, out long sent) == RaiseStatus.Sent && sent == c1, "exactly enough XP, confirmed cost -> Sent with that XP"); + Check(TrainingCosts.CheckRaise(a, 100, a[100], c1 - 1, 1, c1, out _) == RaiseStatus.NotEnough, "one XP short -> NotEnough"); + Check(TrainingCosts.CheckRaise(a, 100, a[100], long.MaxValue, 1, c1 + 1, out _) == RaiseStatus.CostChanged, "a different confirmed cost -> CostChanged (nothing sent)"); + Check(TrainingCosts.CheckRaise(a, 101, a[101], long.MaxValue, 1, c1, out _) == RaiseStatus.CostChanged, "the stat moved on since the user looked -> CostChanged"); + Check(TrainingCosts.CheckRaise(a, 100, a[100], long.MaxValue, 1, 0, out sent) == RaiseStatus.Sent && sent == c1, "0 = don't compare"); + long c10 = TrainingCosts.CostOf(a, 100, a[100], 10); + Check(TrainingCosts.CheckRaise(a, 100, a[100], long.MaxValue, 10, c10, out sent) == RaiseStatus.Sent && sent == c10, "+10"); + int top = a.Length - 1; + Check(TrainingCosts.CheckRaise(a, (uint)top, a[top], long.MaxValue, 1, 0, out _) == RaiseStatus.NotRaisable, "top rank -> NotRaisable"); + Check(TrainingCosts.CheckRaise(a, (uint)top - 3, a[top - 3], long.MaxValue, 10, 0, out _) == RaiseStatus.NotRaisable, "+10 past the top -> NotRaisable"); + Check(TrainingCosts.CheckRaise(null, 0, 0, long.MaxValue, 1, 0, out _) == RaiseStatus.NotRaisable, "untrained skill (no table) -> NotRaisable"); + Check(TrainingCosts.TableFor(t, 3, 1) == null && TrainingCosts.TableFor(t, 3, 0) == null, "untrained / unknown skill: no table"); + Check(TrainingCosts.TableFor(t, 3, 2) == t.TrainedXp && TrainingCosts.TableFor(t, 3, 3) == t.SpecializedXp, "trained / specialized tables"); + Check(TrainingCosts.TableFor(t, 1, 0) == t.AttributeXp && TrainingCosts.TableFor(t, 2, 0) == t.VitalXp && TrainingCosts.TableFor(t, 9, 0) == null, "attribute / vital / unknown kind"); + Check(TrainingCosts.CheckRaise(a, 100, a[100], long.MaxValue, 0, 0, out _) == RaiseStatus.BadArguments + && TrainingCosts.CheckRaise(a, 100, a[100], long.MaxValue, 101, 0, out _) == RaiseStatus.BadArguments + && TrainingCosts.CheckRaise(a, 100, a[100], long.MaxValue, 1, -5, out _) == RaiseStatus.BadArguments, "0 ranks, over 100 ranks, a negative cost -> BadArguments"); + Check(TrainingCosts.CheckRaise(a, 0, 0, long.MaxValue, 100, 0, out long hundred) == RaiseStatus.Sent && hundred == a[100], "+100 from rank 0 = table[100], within one 32-bit game action"); + // A fake table whose step exceeds 32 bits can't be sent in one game action. + uint[] huge = { 0, uint.MaxValue }; + Check(TrainingCosts.CheckRaise(huge, 0, 0, long.MaxValue, 1, 0, out long hc) == RaiseStatus.Sent && hc == uint.MaxValue, "uint.MaxValue XP fits"); + Check(TrainingCosts.CheckRaise(a, 50, a[51], long.MaxValue, 1, 0, out _) == RaiseStatus.NotRaisable, "spent already covers the next rank (cost 0) -> NotRaisable, nothing sent"); + } + + private static void TrainChecks() + { + Section("the checks before a train is sent (CheckTrain)"); + Check(TrainingCosts.CheckTrain(1, 6, 6, 6) == RaiseStatus.Sent, "untrained, priced 6, 6 credits, confirmed 6 -> Sent"); + Check(TrainingCosts.CheckTrain(0, 6, 10, 0) == RaiseStatus.Sent, "not in the skill table yet (class 0) counts as untrained"); + Check(TrainingCosts.CheckTrain(1, 6, 5, 6) == RaiseStatus.NotEnough, "5 credits -> NotEnough"); + Check(TrainingCosts.CheckTrain(1, 6, 10, 4) == RaiseStatus.CostChanged, "confirmed a different price -> CostChanged"); + Check(TrainingCosts.CheckTrain(2, 6, 10, 6) == RaiseStatus.NotRaisable && TrainingCosts.CheckTrain(3, 6, 10, 6) == RaiseStatus.NotRaisable, "already trained / specialized -> NotRaisable"); + Check(TrainingCosts.CheckTrain(1, 0, 10, 0) == RaiseStatus.NotRaisable, "no price in the dat -> NotRaisable"); + Check(TrainingCosts.CheckTrain(1, 6, 10, -1) == RaiseStatus.BadArguments, "negative confirm -> BadArguments"); + } + + private static void ParserRefusesJunk() + { + Section("the XpTable parser refuses junk"); + Check(!TrainingCosts.TryParseXpTable(Array.Empty(), out _), "empty"); + Check(!TrainingCosts.TryParseXpTable(new byte[23], out _), "short header"); + var b = new byte[24]; + BitConverter.GetBytes(0x0E000018u).CopyTo(b, 0); + BitConverter.GetBytes(50000u).CopyTo(b, 4); + Check(!TrainingCosts.TryParseXpTable(b, out _), "absurd counts"); + var c = new byte[24 + 4 * 2 * 4 + 8 * 2 + 3]; // counts of 1: two of each u32 table, two u64 levels; then cut short + BitConverter.GetBytes(1u).CopyTo(c, 4); BitConverter.GetBytes(1u).CopyTo(c, 8); BitConverter.GetBytes(1u).CopyTo(c, 12); + BitConverter.GetBytes(1u).CopyTo(c, 16); BitConverter.GetBytes(1u).CopyTo(c, 20); + Check(TrainingCosts.TryParseXpTable(c, out XpTableData small) && small.AttributeXp.Length == 2 && small.LevelXp.Length == 2, "the smallest well-formed table"); + Check(!TrainingCosts.TryParseXpTable(c.AsSpan(0, c.Length - 4), out _), "the same, a few bytes short"); + } + + private static void SdkNumbersMatch() + { + Section("the SDK's RaiseResult = the engine's RaiseStatus"); + foreach (RaiseStatus s in Enum.GetValues()) + Check(Enum.TryParse(s.ToString(), out RaiseResult r) && (int)r == (int)s, $"{s} = {(int)s}"); + Check((int)RaiseResult.EngineTooOld == -100 && !Enum.IsDefined(typeof(RaiseStatus), -100), "EngineTooOld is the SDK's own"); + Check((uint)TrainingKind.Attribute == 1 && (uint)TrainingKind.Vital == 2 && (uint)TrainingKind.Skill == 3, "kinds 1 / 2 / 3"); + } + + private static IEnumerable<(string, uint[])> Tables(XpTableData t) => + new[] { ("attribute", t.AttributeXp), ("vital", t.VitalXp), ("trained", t.TrainedXp), ("specialized", t.SpecializedXp) }; + + private static void Section(string title) => Console.WriteLine("\n== " + title); + + private static void Check(bool ok, string what) + { + _checks++; + if (!ok) _failed++; + Console.WriteLine((ok ? " ok " : " FAIL ") + what); + } +} diff --git a/tools/TrainingCostTests/TrainingCostTests.csproj b/tools/TrainingCostTests/TrainingCostTests.csproj new file mode 100644 index 0000000..73002c0 --- /dev/null +++ b/tools/TrainingCostTests/TrainingCostTests.csproj @@ -0,0 +1,29 @@ + + + + + Exe + net10.0-windows + enable + enable + true + true + TrainingCostTests + + + + + + + + + + diff --git a/tools/pe_pattern.py b/tools/pe_pattern.py index 75583cb..f350366 100644 --- a/tools/pe_pattern.py +++ b/tools/pe_pattern.py @@ -165,6 +165,14 @@ GROUPS = { "TimeSyncHooks": [ ("ClientNet_HandleTimeSynch", 0x005448F0), ], + "UiFlowHooks": [ + ("UIFlow_UseNewMode", 0x00479AA0), ("Client_Cleanup", 0x004118D0), + ], + "UiElementHooks": [ + ("UIElementManager_StartTooltip", 0x0045DF70), ("UIElementManager_ResetTooltip", 0x0045C440), + ("UIElementManager_CheckTooltip", 0x0045B7C0), ("UIElementManager_StartDragandDrop", 0x0045E120), + ("UIElement_CatchDroppedItem", 0x00461860), ("UIElement_ItemList_InqDropIconInfo", 0x004E3380), + ], "PlayerTrade": [ ("Event_OpenTradeNegotiations", 0x006AE260), ("Event_AddToTrade", 0x006AE030), ("Event_ResetTrade", 0x006AE330), ("Event_CloseTradeNegotiations", 0x006AE140), diff --git a/tools/train_senders_check.py b/tools/train_senders_check.py new file mode 100644 index 0000000..49d455c --- /dev/null +++ b/tools/train_senders_check.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python3 +""" +Offline check of the raise / train senders (Compatibility/PlayerTraining.cs, plugin API v79 +Raise / TrainSkill) against an acclient.exe. Read-only: maps the file, runs nothing. + +The engine binds the client's own CM_Train game-action senders, the functions the retail +character window calls for "+" (gmAttributeUI / gmSkillUI RaiseSelection and +Raise10Selection) and for the train dialog (gmSkillUI::TrainSkillDialogCallback). This +proves, on the given client build, that: + + * each embedded pattern is unique and lands on its VA (as pe_pattern.py CHECK does); + * each target starts a function and is the generated two-argument sender: it reads its + first argument at [esp+1Ch] and its second at [esp+20h] (after sub esp,0Ch and three + pushes), writes the expected game-action opcode (0x45 RaiseAttribute, 0x44 RaiseVital, + 0x46 RaiseSkill, 0x47 TrainSkill) and returns with a plain ret (cdecl: the caller pops); + * the retail character window's own raise/train handlers call exactly these functions + (direct E8 calls at the Chorizite-map call sites) with two pushed arguments and pop + 8 bytes after: the engine calls them the same way (bool __cdecl (uint, uint)). + +Usage: python tools/train_senders_check.py ["" ...] +Default: both client copies (C:\\Turbine\\Asheron's Call and C:\\Games\\RynthCore\\AcClient). +Exit 0 = every check passed on every client given. +""" +import os +import struct +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from pe_pattern import read_window, matches, parse_engine_patterns # noqa: E402 + +DEFAULT_CLIENTS = [r"C:\Turbine\Asheron's Call\acclient.exe", r"C:\Games\RynthCore\AcClient\acclient.exe"] + +# name in PlayerTraining.cs -> (opcode, the character window's call sites from the Chorizite +# acclient map: (call address, the function it sits in)) +SENDERS = { + "PlayerTraining.Event_TrainAttribute": (0x45, [ + (0x0049D361, "gmAttributeUI::RaiseSelection"), (0x0049D491, "gmAttributeUI::Raise10Selection")]), + "PlayerTraining.Event_TrainAttribute2nd": (0x44, [ + (0x0049D38A, "gmAttributeUI::RaiseSelection"), (0x0049D4BA, "gmAttributeUI::Raise10Selection")]), + "PlayerTraining.Event_TrainSkill": (0x46, [ + (0x0049CBF7, "gmSkillUI::RaiseSelection"), (0x0049BA97, "gmSkillUI::Raise10Selection")]), + "PlayerTraining.Event_TrainSkillAdvancementClass": (0x47, [ + (0x0049C5B1, "gmSkillUI::TrainSkillDialogCallback")]), +} + +fails = 0 + + +def check(ok, msg): + global fails + print(("ok " if ok else "FAIL ") + msg) + if not ok: + fails += 1 + + +def run(path): + print(f"\n=== {path}") + if not os.path.exists(path): + check(False, "acclient.exe not found") + return + W, BASE = read_window(path) + + def at(va, n): + o = va - BASE + return W[o:o + n] + + def rel_callers(target): + out, i = [], 0 + while True: + i = W.find(b"\xE8", i) + if i < 0 or i + 5 > len(W): + break + if BASE + i + 5 + struct.unpack_from("= 0: + return True + if after[0] == 0xEB: # jmp short to a join that pops + dest = call_va + 5 + 2 + struct.unpack_from("= 0 + return False + + items = {it["name"]: it for it in parse_engine_patterns() if it["file"] == "PlayerTraining.cs" and it["kind"] == "fn"} + for name, (opcode, sites) in SENDERS.items(): + it = items.get(name) + check(it is not None, f"{name}: pattern present in PlayerTraining.cs") + if it is None: + continue + ms = matches(W, it["pattern"], limit=4) + va = BASE + ms[0] if len(ms) == 1 else None + check(va is not None, f"{name}: pattern unique ({len(ms)} match{'es' if len(ms) != 1 else ''}) at 0x{(va or 0):08X}" + + (" = the map's VA" if va == it["va"] else f" (map VA 0x{it['va']:08X})")) + if va is None: + continue + check(it["pattern"][-1] == opcode and at(va + 90, 7) == bytes([0xC7, 0x02, opcode, 0, 0, 0, 0x8B]), + f"{name}: writes game action 0x{opcode:04X}") + prev = at(va - 4, 4) + check(prev[-1] in (0x90, 0xCC, 0xC3) or (prev[-3] == 0xC2 and prev[-1] == 0x00), f"{name}: starts a function (before: {prev.hex(' ')})") + check(at(va, 6) == bytes([0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57]), f"{name}: sub esp,0Ch / push ebx,esi,edi") + body = at(va, 0x180) + check(body.find(bytes([0x8B, 0x4C, 0x24, 0x1C])) >= 0 and body.find(bytes([0x8B, 0x54, 0x24, 0x20])) >= 0, + f"{name}: reads two stack arguments ([esp+1Ch], [esp+20h])") + end = body.find(bytes([0x83, 0xC4, 0x0C, 0xC3])) + check(end > 0 and body[:end].find(bytes([0xC2, 0x08, 0x00])) < 0 and body[:end].find(bytes([0xC2, 0x04, 0x00])) < 0, + f"{name}: add esp,0Ch / ret at +0x{end:X} (cdecl, no ret N)") + check(body[:end].find(bytes([0x8A, 0xD8])) >= 0, f"{name}: returns the send's bool in al (mov bl,al ... )") + callers = rel_callers(va) + for call, owner in sites: + check(call in callers, f"{name}: called by the character window ({owner}, call at 0x{call:08X})") + if call in callers: + check(pops_8_after(call), f"{name}: {owner} pops 8 bytes after the call (two cdecl arguments)") + print(f" {len(callers)} direct call site(s): " + ", ".join(f"0x{c:08X}" for c in callers)) + + +def main(): + paths = sys.argv[1:] or DEFAULT_CLIENTS + for p in paths: + run(p) + print() + print("PASS" if fails == 0 else f"FAIL ({fails})") + return 0 if fails == 0 else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/ui_hooks_check.py b/tools/ui_hooks_check.py new file mode 100644 index 0000000..72bb0bb --- /dev/null +++ b/tools/ui_hooks_check.py @@ -0,0 +1,175 @@ +#!/usr/bin/env python3 +""" +Offline check of the UI hooks (Compatibility/UiFlowHooks.cs, Compatibility/UiElementHooks.cs) +against an acclient.exe. Read-only: maps the file, runs nothing. + +pe_pattern.py CHECK already proves every embedded pattern is unique and lands on its VA. +This goes further and checks the facts the detours rely on, so a different client build +fails here instead of in game: + + * each target starts a function (padding or a ret right before it) and returns the way + its detour's signature says (ret / ret 4 / ret 0Ch / ret 14h, or a tail jump); + * UseNewMode copies UIFlow+0x90 into +0x8C (the offsets the detour reads); + * StartTooltip / ResetTooltip use UIElementManager +0x2F4 / +0x2F8, ResetTooltip + tail-jumps into CheckTooltip; + * StartDragandDrop stores the drag icon at +0x31C and its owner at +0x320; + * StopDragandDrop calls the catcher's vtable +0xD8, and every UIElement vtable in the + client has CatchDroppedItem there (directly, or UIElement_Field's, which calls it); + * every UIElement vtable has GetUIElementType at +0x98 (mov eax,imm32 / ret, or xor/ret), + UIElement_ItemList's returns 0x10000031, GetParent is the vtable +0xA0 call that + GetAncestorByID walks, and the element id is at +0x2E4. + +Usage: python tools/ui_hooks_check.py [""] +Exit 0 = every check passed. +""" +import os +import struct +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from pe_pattern import read_window, matches, parse_engine_patterns # noqa: E402 + +DEFAULT_CLIENT = r"C:\Turbine\Asheron's Call\acclient.exe" +N = None + +fails = 0 + + +def check(ok, msg): + global fails + print(("ok " if ok else "FAIL ") + msg) + if not ok: + fails += 1 + + +def main(): + path = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_CLIENT + if not os.path.exists(path): + print(f"acclient.exe not found: {path}") + return 2 + W, BASE = read_window(path) + + def at(va, n): + o = va - BASE + return W[o:o + n] + + def u32(va): + return struct.unpack_from("= 0 + + def rel_callers(target, op=0xE8): + out, i = [], 0 + while True: + i = W.find(bytes([op]), i) + if i < 0 or i + 5 > len(W): + break + if BASE + i + 5 + struct.unpack_from("= 10, f"InqDropIconInfo: {len(callers)} callers in the client (AC uses it itself)") + popping = [c for c in callers if body_has(c + 5, [0x83, 0xC4, 0x10], 0x0C)] + check(len(popping) >= len(callers) - 1, + f"InqDropIconInfo: cdecl with 4 args - {len(popping)}/{len(callers)} callers pop 16 bytes right after (one batches it later)") + check(at(va["UiElement.InqDropIconInfo"], 4) == bytes([0x8B, 0x44, 0x24, 0x10]) and body_has(va["UiElement.InqDropIconInfo"], [0x3B, 0xF3], 0x20), + "InqDropIconInfo: reads its 4th arg first and null-checks the element") + + # 3. UseNewMode: +0x90 -> +0x8C + check(body_has(va["UiFlow.UseNewMode"], [0x8B, 0x8E, 0x90, 0x00, 0x00, 0x00, 0x57, 0x89, 0x8E, 0x8C, 0x00, 0x00, 0x00]), + "UseNewMode: mov ecx,[esi+90h] / mov [esi+8Ch],ecx (pending -> current mode)") + check(len(rel_callers(va["UiFlow.UseNewMode"])) == 1, "UseNewMode: one call site") + check(len(rel_callers(va["UiFlow.ClientCleanup"])) == 1 and len(abs_refs(va["UiFlow.ClientCleanup"])) >= 1, + "Client::Cleanup: one direct call (gmClient::Cleanup) and a vtable entry") + + # 4. tooltip offsets + check(body_has(va["UiElement.StartTooltip"], [0x89, 0xBE, 0xF4, 0x02, 0x00, 0x00], 0x60), "StartTooltip: owner stored at +0x2F4") + check(body_has(va["UiElement.ResetTooltip"], [0xC7, 0x86, 0xF8, 0x02, 0x00, 0x00, 0, 0, 0, 0], 0x20), "ResetTooltip: clears the tooltip element at +0x2F8") + jmp = W.find(bytes([0x8B, 0xCE, 0x5E, 0xE9]), va["UiElement.ResetTooltip"] - BASE, va["UiElement.ResetTooltip"] - BASE + 0x80) + tail = BASE + jmp + 3 + 5 + struct.unpack_from("= 0 else 0 + check(tail == va["UiElement.CheckTooltip"], f"ResetTooltip: tail-jumps into CheckTooltip (0x{tail:08X})") + inner = W.find(bytes([0x89, 0xB3, 0xF8, 0x02, 0x00, 0x00]), va["UiElement.StartTooltip"] - BASE - 0x6000, va["UiElement.StartTooltip"] - BASE) + check(inner >= 0, "the inner StartTooltip stores the new tooltip element at +0x2F8") + + # 5. drag: icon +0x31C, owner +0x320 + check(body_has(va["UiElement.StartDragandDrop"], [0x89, 0x9E, 0x1C, 0x03, 0x00, 0x00], 0x260), "StartDragandDrop: drag icon stored at +0x31C") + check(body_has(va["UiElement.StartDragandDrop"], [0x89, 0x8E, 0x20, 0x03, 0x00, 0x00], 0x260), "StartDragandDrop: drag owner stored at +0x320") + check(len(rel_callers(va["UiElement.StartDragandDrop"])) == 5, "StartDragandDrop: 5 call sites (one is itself: the drag proxy)") + + # 6. StopDragandDrop builds DragDropInfo and calls the catcher's +0xD8 + stop = find([0x53, 0x57, 0x8B, 0xF9, 0x8B, 0x87, 0x1C, 0x03, 0x00, 0x00, 0x33, 0xDB, 0x3B, 0xC3, 0x0F, 0x84]) + check(stop is not None, f"StopDragandDrop found (0x{(stop or 0):08X})") + if stop: + check(body_has(stop, [0x89, 0x46, 0x08], 0x50) and body_has(stop, [0x89, 0x56, 0x0C], 0x60) and body_has(stop, [0x89, 0x4E, 0x10], 0x60), + "StopDragandDrop: DragDropInfo +0x08 icon, +0x0C owner, +0x10 catcher") + check(body_has(stop, [0xFF, 0x90, 0xD8, 0x00, 0x00, 0x00], 0x80), "StopDragandDrop: calls catcher->vtable[+0xD8] (CatchDroppedItem)") + + # 7. every UIElement vtable: +0xD8, +0x98, +0xA0 + ancestor = find([0x8B, 0x01, 0xFF, 0x90, 0xA0, 0x00, 0x00, 0x00, 0x85, 0xC0, 0x74, 0x1C, 0x56, 0x8B, 0x74, 0x24, 0x08, + 0x39, 0xB0, 0xE4, 0x02, 0x00, 0x00]) + check(ancestor is not None, f"UIElement::GetAncestorByID found (walks vtable +0xA0, compares +0x2E4) at 0x{(ancestor or 0):08X}") + field = find([0x56, 0x8B, 0xF1, 0x8A, 0x86, 0xF0, 0x05, 0x00, 0x00, 0x84, 0xC0, 0x74, 0x18]) + if field: + call = W.find(bytes([0xE8]), field - BASE + 0x2C, field - BASE + 0x2D) + target = BASE + call + 5 + struct.unpack_from("= 0 else 0 + check(target == va["UiElement.CatchDroppedItem"], "UIElement_Field::CatchDroppedItem calls UIElement::CatchDroppedItem") + if ancestor: + tables = [r - 0xA4 for r in abs_refs(ancestor)] + check(len(tables) >= 100, f"{len(tables)} UIElement vtables (GetAncestorByID at +0xA4)") + bad_drop = [t for t in tables if u32(t + 0xD8) not in (va["UiElement.CatchDroppedItem"], field)] + check(not bad_drop, f"every UIElement vtable's +0xD8 reaches CatchDroppedItem ({len(tables) - len(bad_drop)}/{len(tables)})") + bad_type = [t for t in tables if not (at(u32(t + 0x98), 1) == b"\xB8" and at(u32(t + 0x98) + 5, 1) == b"\xC3" or at(u32(t + 0x98), 3) == b"\x33\xC0\xC3")] + check(not bad_type, f"every UIElement vtable's +0x98 is GetUIElementType ({len(tables) - len(bad_type)}/{len(tables)})") + itemlist = [t for t in tables if at(u32(t + 0x98), 6) == bytes([0xB8, 0x31, 0x00, 0x00, 0x10, 0xC3])] + check(len(itemlist) >= 1, f"UIElement_ItemList's GetUIElementType returns 0x10000031 ({len(itemlist)} vtable(s))") + + print("=" * 60) + print("PASS - the UI hooks' facts hold on this client." if fails == 0 else f"FAIL - {fails} check(s) failed.") + return 1 if fails else 0 + + +if __name__ == "__main__": + sys.exit(main())