merge: bring main (engine 2026.10.5.16) into QOL-items for PR #10
Resolves the 15 conflicting files between QOL-items and main's upstream snapshot line. Plugin API is now 80: main's v77-v79 numbering stays and GetMergeStackResultFn (v77 on QOL-items) moves to the end of the table as v80 in the engine and the SDK. Details in Changelog/2026-10-07-merge-main-into-QOL-items.md. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
commit
50056c1d6f
123 changed files with 13415 additions and 1182 deletions
|
|
@ -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.<pid>.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.
|
||||
117
Changelog/2026-10-06-upstream-snapshot-comparison.md
Normal file
117
Changelog/2026-10-06-upstream-snapshot-comparison.md
Normal file
|
|
@ -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.
|
||||
66
Changelog/2026-10-07-merge-main-into-QOL-items.md
Normal file
66
Changelog/2026-10-07-merge-main-into-QOL-items.md
Normal file
|
|
@ -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.
|
||||
|
|
@ -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`
|
||||
|
|
@ -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`.
|
||||
|
|
@ -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.
|
||||
```
|
||||
|
|
|
|||
|
|
@ -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]"
|
||||
|
|
|
|||
86
installer/PluginManifest.ps1
Normal file
86
installer/PluginManifest.ps1
Normal file
|
|
@ -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 <dll> 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 <repoRoot> 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;
|
||||
|
||||
/// <summary>RCDATA resource <paramref name="name"/> of a PE file, or null if it has none.</summary>
|
||||
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
|
||||
}
|
||||
|
|
@ -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 <version>" 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)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
|
|
@ -61,6 +61,8 @@
|
|||
<Compile Include="..\RynthCore.App\AppSettingsStore.cs" Link="Shared\AppSettingsStore.cs" />
|
||||
<Compile Include="..\RynthCore.App\DecalAccountModes.cs" Link="Shared\DecalAccountModes.cs" />
|
||||
<Compile Include="..\RynthCore.App\PluginDefinition.cs" Link="Shared\PluginDefinition.cs" />
|
||||
<!-- The plugin API of the engine installed with this launcher (RynthUpdater.InstalledEngineApi). -->
|
||||
<Compile Include="..\RynthCore.Engine\Plugins\PluginContractVersion.cs" Link="Shared\PluginContractVersion.cs" />
|
||||
<Compile Include="..\RynthCore.Injector\EngineInjectionService.cs" Link="Shared\EngineInjectionService.cs" />
|
||||
<Compile Include="..\RynthCore.Injector\InjectionResult.cs" Link="Shared\InjectionResult.cs" />
|
||||
</ItemGroup>
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
||||
/// <summary>A feed plugin the player can install: where it would go, what it is, and whether it's new.</summary>
|
||||
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)
|
||||
{
|
||||
/// <summary>
|
||||
/// 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").
|
||||
/// </summary>
|
||||
public string Blocker { get; init; } = "";
|
||||
public bool CanInstall => Blocker.Length == 0;
|
||||
}
|
||||
|
||||
/// <summary>What <see cref="InstallPluginAsync"/> did: Downloaded is false when a good copy was already there.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The manifest's optional "changes": up to 20 lines.</summary>
|
||||
private static IReadOnlyList<string> ReadChanges(JsonElement r)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -42,9 +42,14 @@ internal sealed partial class RynthUpdater
|
|||
/// One plugin in the feed. <paramref name="Description"/> is the optional one-line "description"
|
||||
/// (written since 2026.10.5); older feeds have none and the launcher's own table fills in
|
||||
/// (<see cref="DescribePlugin"/>). Launchers before it ignore the field.
|
||||
/// <paramref name="MinEngineApi"/> 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 <see cref="EngineBlocker"/>.
|
||||
/// </summary>
|
||||
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);
|
||||
/// <summary>The core release. <paramref name="EngineApi"/>: the optional "engineApi", its engine's plugin API (0 = not said).</summary>
|
||||
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<PluginEntry> Plugins, NavDataEntry? NavData = null)
|
||||
{
|
||||
|
|
@ -56,8 +61,17 @@ internal sealed partial class RynthUpdater
|
|||
}
|
||||
|
||||
/// <summary>One installed copy of a plugin the feed knows.</summary>
|
||||
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)
|
||||
{
|
||||
/// <summary>For <see cref="PluginState.NeedsNewerEngine"/>: "needs RynthCore 2026.10.6.1".</summary>
|
||||
public string Blocker { get; init; } = "";
|
||||
}
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
public enum PluginState { UpToDate, NeedsUpdate, LocalBuild, NeedsNewerEngine }
|
||||
|
||||
/// <summary>A plugin split out of one the player has, to be installed beside it (see <see cref="Companions"/>).</summary>
|
||||
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<PluginStatus> PluginsToUpdate => Plugins.Where(p => p.State == PluginState.NeedsUpdate);
|
||||
/// <summary>Plugin updates held back until RynthCore is updated (<see cref="PluginState.NeedsNewerEngine"/>).</summary>
|
||||
public IEnumerable<PluginStatus> PluginsWaitingForCore => Plugins.Where(p => p.State == PluginState.NeedsNewerEngine);
|
||||
/// <summary>New plugins that came out of an installed one; installed with the plugin updates.</summary>
|
||||
public IReadOnlyList<CompanionInstall> Companions { get; init; } = Array.Empty<CompanionInstall>();
|
||||
/// <summary>Feed plugins not in the plugin list, for the player to install or not (see <see cref="GetAvailable"/>).</summary>
|
||||
|
|
@ -113,6 +129,26 @@ internal sealed partial class RynthUpdater
|
|||
_appDir = appDir ?? AppContext.BaseDirectory;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal uint InstalledEngineApi { get; set; } = RynthCore.Engine.Plugins.PluginContractVersion.Current;
|
||||
|
||||
/// <summary>
|
||||
/// Empty when the installed engine runs <paramref name="e"/>; 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)".
|
||||
/// </summary>
|
||||
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})";
|
||||
}
|
||||
|
||||
/// <summary>False until the signing keys exist: with no trusted key nothing can verify.</summary>
|
||||
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<CompanionInstall> 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<PluginEntry>();
|
||||
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() ?? "",
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
{
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
||||
/// <summary>AC's main thread only (AcMainThreadQueue.Drain).</summary>
|
||||
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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static void WantSlow() =>
|
||||
Volatile.Write(ref _slowWantedUntilMs, Environment.TickCount64 + SlowWantWindowMs);
|
||||
|
||||
/// <summary>Read again at the next main-thread tick (after a raise). Any thread.</summary>
|
||||
public static void RefreshSoon() => Volatile.Write(ref _nextReadMs, 0);
|
||||
|
||||
/// <summary>
|
||||
/// Environment.TickCount64 of the last successful read, changed or not (0 = never), so a
|
||||
/// reader can tell how old <see cref="Current"/>'s numbers are. Any thread.
|
||||
/// </summary>
|
||||
public static long LastReadMs => Volatile.Read(ref _lastReadMs);
|
||||
|
||||
/// <summary>The last published read, or null. Never written again once published. Any thread.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>The player's enchantments that change a skill, attribute or vital (not vitae).</summary>
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
/// </summary>
|
||||
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
|
||||
|
|
|
|||
|
|
@ -43,12 +43,20 @@ namespace RynthCore.Engine.Compatibility;
|
|||
/// never sees it; every other "/rv" line still goes to the plugin.</item>
|
||||
/// <item><c>/rc server [auto|aelrynth|other]</c> — which server the engine detects
|
||||
/// (<see cref="ServerInfo"/>) and why; aelrynth/other force it for this session.</item>
|
||||
/// <item><c>/rc hooks [on|off <name>]</c> (alias <c>/rc uihooks</c>) — the UI hooks
|
||||
/// (screen mode, client cleanup, tooltip, drag/drop; <see cref="UiHookRegistry"/>):
|
||||
/// status, or switch one off/on (now and in engine.json).</item>
|
||||
/// <item><c>/rc mastery</c> — the Aelrynth mastery feed's state (<see cref="MasteryFeed"/>),
|
||||
/// and ask the server for /mastery-data again.</item>
|
||||
/// <item><c>/rc worldlayer [auto|uipass|transition|endscene]</c> — where the world overlays
|
||||
/// (nameplates, combat text, Nav3D markers) draw in AC's frame
|
||||
/// (<see cref="D3D9.Nav3DRenderInjector"/>): alone it reports the path and counters;
|
||||
/// a mode forces it for this session (A/B checks). Auto at every start; not saved.</item>
|
||||
/// <item><c>/rc netmsg [status|on|off|log on|off|capture on|off]</c> - the reassembled
|
||||
/// server-message stream for plugins (<see cref="Net.ServerMessageStream"/>, 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.</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
internal static class RynthCoreChatCommands
|
||||
|
|
@ -153,6 +161,26 @@ internal static class RynthCoreChatCommands
|
|||
return true;
|
||||
}
|
||||
|
||||
// /rc hooks [on|off <name>] : 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// /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.
|
||||
/// </summary>
|
||||
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 <name>");
|
||||
return;
|
||||
}
|
||||
foreach (string line in UiHookRegistry.DescribeLines())
|
||||
Reply(line);
|
||||
}
|
||||
|
||||
/// <summary>"on"/"off" sets; anything else (or nothing) toggles.</summary>
|
||||
private static bool Flag(string? value, bool current) =>
|
||||
value?.ToLowerInvariant() switch { "on" or "1" or "true" => true, "off" or "0" or "false" => false, _ => !current };
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
|
|
|||
278
src/RynthCore.Engine/Compatibility/TrainingApi.cs
Normal file
278
src/RynthCore.Engine/Compatibility/TrainingApi.cs
Normal file
|
|
@ -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
|
||||
{
|
||||
/// <summary>Numbers older than this are not raised against.</summary>
|
||||
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;
|
||||
|
||||
/// <summary>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.</summary>
|
||||
public static bool InWorld =>
|
||||
LoginLifecycleHooks.HasObservedLoginComplete
|
||||
&& UiFlowHooks.InWorldOrUnknown
|
||||
&& !UiFlowHooks.ClientCleanupStarted
|
||||
&& !LogoutLifecycleHooks.HasObservedLogout
|
||||
&& !DbCacheTeardownHooks.TeardownActive
|
||||
&& ClientHelperHooks.GetPlayerId() != 0;
|
||||
|
||||
/// <summary>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.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The snapshot to act on, or why not.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>v79 Raise: <paramref name="ranks"/> ranks of one attribute (1..6), vital (1 health,
|
||||
/// 3 stamina, 5 mana) or trained/specialized skill. <paramref name="xpSent"/> = the XP sent.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>v79 TrainSkill: untrained -> trained for exactly the SkillTable's credit price.</summary>
|
||||
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();
|
||||
}
|
||||
}
|
||||
191
src/RynthCore.Engine/Compatibility/TrainingCosts.cs
Normal file
191
src/RynthCore.Engine/Compatibility/TrainingCosts.cs
Normal file
|
|
@ -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;
|
||||
|
||||
/// <summary>The four raise tables of the portal XpTable (index = rank, value = total XP at that rank).</summary>
|
||||
internal sealed class XpTableData
|
||||
{
|
||||
public uint[] AttributeXp = Array.Empty<uint>();
|
||||
public uint[] VitalXp = Array.Empty<uint>();
|
||||
public uint[] TrainedXp = Array.Empty<uint>();
|
||||
public uint[] SpecializedXp = Array.Empty<uint>();
|
||||
public ulong[] LevelXp = Array.Empty<ulong>();
|
||||
}
|
||||
|
||||
/// <summary>The plugin API's raise and train results (RynthCoreAPI.RaiseFn / TrainSkillFn, v79).</summary>
|
||||
internal enum RaiseStatus
|
||||
{
|
||||
Sent = 1,
|
||||
/// <summary>The client's raise senders aren't bound on this build.</summary>
|
||||
Unavailable = 0,
|
||||
NotInWorld = -1,
|
||||
BadArguments = -2,
|
||||
/// <summary>No player snapshot or no XP table yet (both are being fetched; try again in a second).</summary>
|
||||
NotReady = -3,
|
||||
/// <summary>The numbers are older than the freshness limit; a new read was asked for. Try again in a second.</summary>
|
||||
Stale = -4,
|
||||
/// <summary>The cost the caller expected isn't the cost now (something changed: refresh and ask again).</summary>
|
||||
CostChanged = -5,
|
||||
/// <summary>Not enough unassigned XP (or skill credits for a train).</summary>
|
||||
NotEnough = -6,
|
||||
/// <summary>Can't be raised: at or past the top rank, an untrained skill, or a skill that can't be trained.</summary>
|
||||
NotRaisable = -7,
|
||||
/// <summary>An earlier raise or train hasn't shown up in the numbers yet (5 s at most).</summary>
|
||||
Busy = -8,
|
||||
/// <summary>The send failed or the action queue was full.</summary>
|
||||
SendFailed = -9,
|
||||
}
|
||||
|
||||
internal static class TrainingCosts
|
||||
{
|
||||
/// <summary>Most ranks one API raise may buy (the retail window offers 1 and 10).</summary>
|
||||
public const int MaxRanksPerRaise = 100;
|
||||
|
||||
// ── the XpTable ──────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Reads the portal XpTable file (0x0E000018). False when it is short or the counts are absurd.</summary>
|
||||
public static bool TryParseXpTable(ReadOnlySpan<byte> 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<byte> 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<byte> b, ref int p, int n, out uint[] a)
|
||||
{
|
||||
a = Array.Empty<uint>();
|
||||
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) ──
|
||||
|
||||
/// <summary>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).</summary>
|
||||
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,
|
||||
};
|
||||
|
||||
/// <summary>True when <paramref name="ranks"/> is the table's top rank (nothing left to buy).</summary>
|
||||
public static bool IsMax(uint[] table, uint ranks) => table.Length == 0 || ranks + 1L >= table.Length;
|
||||
|
||||
/// <summary>Ranks left to the top of the table.</summary>
|
||||
public static int RanksLeft(uint[] table, uint ranks) => (int)Math.Max(0L, table.Length - 1L - ranks);
|
||||
|
||||
/// <summary>XP to buy <paramref name="n"/> more ranks from <paramref name="ranks"/> with
|
||||
/// <paramref name="spent"/> already spent; -1 past the top; 0 for n < 1.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>How many ranks in a row <paramref name="available"/> XP buys (0 when not even one), up to the top.</summary>
|
||||
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 ──────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Everything a raise of <paramref name="count"/> 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 (<paramref name="expectedXp"/> > 0; 0 = don't compare), enough
|
||||
/// unassigned XP, and an amount the 32-bit game action can carry.
|
||||
/// <paramref name="cost"/> is the XP to send when the result is <see cref="RaiseStatus.Sent"/>.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 (<paramref name="expectedCredits"/> > 0; 0 = don't compare) and
|
||||
/// the player must have the credits.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
480
src/RynthCore.Engine/Compatibility/UiElementHooks.cs
Normal file
480
src/RynthCore.Engine/Compatibility/UiElementHooks.cs
Normal file
|
|
@ -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]<IntPtr, IntPtr, IntPtr, uint, uint, uint, void> 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]<IntPtr, void> 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]<IntPtr, void> 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]<IntPtr, IntPtr, int, int, byte> 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]<IntPtr, IntPtr, byte> 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 ─────────────────────────────────────
|
||||
|
||||
/// <summary>Tooltip/drag/drop hooks a plugin can rely on (GetUiHookFlags bits 3-6).</summary>
|
||||
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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The object whose tooltip AC shows, or 0 (any thread; a plain field).</summary>
|
||||
public static uint CurrentTooltipObject => _tooltipShown ? _tooltipObject : 0;
|
||||
|
||||
/// <summary>UiFlowHooks, leaving the world (main thread): forget tooltip/drag state; no events.</summary>
|
||||
public static void OnScreenLeaving()
|
||||
{
|
||||
_tooltipShown = false;
|
||||
_tooltipOwner = IntPtr.Zero;
|
||||
_tooltipObject = _tooltipSpell = 0;
|
||||
_dragObject = _dragSpell = 0;
|
||||
}
|
||||
|
||||
/// <summary>UiFlowHooks, Client::Cleanup (main thread): AC's UI is about to go; never touch it again.</summary>
|
||||
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]<IntPtr, IntPtr, IntPtr, uint, uint, uint, void>)_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]<IntPtr, void>)_origResetTooltip)(mgr);
|
||||
if (ResetTooltipSlot.Enabled)
|
||||
AfterTooltipCheck(mgr, ResetTooltipSlot);
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvThiscall)])]
|
||||
private static void CheckTooltipDetour(IntPtr mgr)
|
||||
{
|
||||
((delegate* unmanaged[Thiscall]<IntPtr, void>)_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]<IntPtr, IntPtr, int, int, byte>)_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]<IntPtr, IntPtr, byte>)_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) ──────────────────────────────────────
|
||||
|
||||
/// <summary>AC's InqDropIconInfo on <paramref name="element"/>, then up to <paramref name="parents"/> parents.</summary>
|
||||
private static void Identify(IntPtr element, int parents, out uint objectId, out uint spellId)
|
||||
{
|
||||
objectId = spellId = 0;
|
||||
var inq = (delegate* unmanaged[Cdecl]<IntPtr, uint*, uint*, uint*, void>)_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, IntPtr>)(*(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, int>)(*(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();
|
||||
}
|
||||
334
src/RynthCore.Engine/Compatibility/UiFlowHooks.cs
Normal file
334
src/RynthCore.Engine/Compatibility/UiFlowHooks.cs
Normal file
|
|
@ -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;
|
||||
|
||||
/// <summary>AC's main thread, inside UseNewMode before the old screen's UI is destroyed (hook only).</summary>
|
||||
public static event Action<int, int>? ScreenLeaving;
|
||||
/// <summary>AC's main thread, after the new screen was built (hook) or on the next tick (poll fallback).</summary>
|
||||
public static event Action<int, int>? ScreenChanged;
|
||||
/// <summary>AC's main thread, before Client::Cleanup runs. Once.</summary>
|
||||
public static event Action? ClientCleanup;
|
||||
|
||||
/// <summary>The UIFlow mode as last observed; 0 until the first observation.</summary>
|
||||
public static int CurrentMode => Volatile.Read(ref _mode);
|
||||
public static int PreviousMode => Volatile.Read(ref _previousMode);
|
||||
|
||||
/// <summary>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.</summary>
|
||||
public static bool InWorldOrUnknown
|
||||
{
|
||||
get
|
||||
{
|
||||
int m = Volatile.Read(ref _mode);
|
||||
return m == ModeNone || m == ModeGamePlay;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Client::Cleanup has started: AC is tearing its UI down. Never cleared.</summary>
|
||||
public static bool ClientCleanupStarted => Volatile.Read(ref _cleanupStarted) != 0;
|
||||
|
||||
/// <summary>The UseNewMode detour is installed and switched on (else the poll drives the events).</summary>
|
||||
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]<IntPtr, void> 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]<IntPtr, void> 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]<IntPtr, void>)_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]<IntPtr, void>)_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 ────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
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}"); }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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")}.";
|
||||
}
|
||||
215
src/RynthCore.Engine/Compatibility/UiHookRegistry.cs
Normal file
215
src/RynthCore.Engine/Compatibility/UiHookRegistry.cs
Normal file
|
|
@ -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 <name> - 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 <name> 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;
|
||||
}
|
||||
|
||||
/// <summary>The switch name (engine.json DisabledUiHooks, /rc hooks on|off).</summary>
|
||||
public string Name { get; }
|
||||
/// <summary>The AC function, for people.</summary>
|
||||
public string What { get; }
|
||||
public int FallbackVa { get; }
|
||||
|
||||
public IntPtr Address;
|
||||
/// <summary>"pattern", "fallback", or empty when not installed.</summary>
|
||||
public string Source = string.Empty;
|
||||
public bool Installed;
|
||||
/// <summary>Why it isn't installed ("off in engine.json", "pattern and fallback both failed", ...).</summary>
|
||||
public string Reason = "not probed yet";
|
||||
public int Fired;
|
||||
public string LastNote = string.Empty;
|
||||
|
||||
private int _enabled = 1;
|
||||
/// <summary>Runtime switch: false = the detour only calls AC's original.</summary>
|
||||
public bool Enabled
|
||||
{
|
||||
get => Volatile.Read(ref _enabled) != 0;
|
||||
set => Volatile.Write(ref _enabled, value ? 1 : 0);
|
||||
}
|
||||
|
||||
/// <summary>Installed and switched on: the detour does its work.</summary>
|
||||
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<UiHookSlot> 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<UiHookSlot> All()
|
||||
{
|
||||
lock (Sync) return new List<UiHookSlot>(Slots);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// <paramref name="trampoline"/> is AC's original.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Enables a hook TryInstall created (after the caller stored the trampoline).</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>/rc hooks on|off <name>: runtime pass-through plus engine.json for the next start.</summary>
|
||||
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<string> DescribeLines()
|
||||
{
|
||||
var lines = new List<string>();
|
||||
foreach (UiHookSlot s in All())
|
||||
lines.Add(s.Describe());
|
||||
lines.Add(UiFlowHooks.DescribeState());
|
||||
lines.Add(UiElementHooks.DescribeState());
|
||||
return lines;
|
||||
}
|
||||
}
|
||||
|
|
@ -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)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -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());
|
||||
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
|
||||
/// <summary>
|
||||
/// 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".
|
||||
/// </summary>
|
||||
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))
|
||||
|
|
|
|||
|
|
@ -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
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs <paramref name="action"/> 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>True when anything ImGui should be drawn this frame.</summary>
|
||||
private static bool HasImGuiContent()
|
||||
{
|
||||
|
|
@ -556,9 +575,13 @@ internal static class EngineFrameController
|
|||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
private static bool PanelsLive => Compatibility.LoginLifecycleHooks.HasObservedLoginComplete;
|
||||
private static bool PanelsLive => Compatibility.LoginLifecycleHooks.HasObservedLoginComplete
|
||||
&& Compatibility.UiFlowHooks.InWorldOrUnknown
|
||||
&& !Compatibility.UiFlowHooks.ClientCleanupStarted;
|
||||
|
||||
/// <summary>DPI scale the fonts and style were built for (see Init).</summary>
|
||||
private static float _uiScale = 1f;
|
||||
|
|
|
|||
|
|
@ -123,6 +123,17 @@ internal static unsafe class ImGuiPopOuts
|
|||
/// <summary>The pop-out typing into a text box, or null (for the input log). AC thread.</summary>
|
||||
public static string? TextFocusTitle => _keyboard is { WantTextInput: true } k ? k.Title : null;
|
||||
|
||||
/// <summary>
|
||||
/// True when the cursor is over <paramref name="title"/>'s pop-out window right now
|
||||
/// (UiDropTargets: an AC item released over a popped-out panel). AC thread.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The screen position of the game window's client origin (to place a pop-out where the docked panel was).</summary>
|
||||
public static Vector2 ClientOriginOnScreen()
|
||||
{
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
||||
/// <summary>A name label's text size: players' or NPCs' (vendors count as NPCs).</summary>
|
||||
private static float LabelTextSize(byte kind) =>
|
||||
kind == RadarKind.Player ? MonsterHudSettings.PlayerTextSize : MonsterHudSettings.NpcTextSize;
|
||||
|
||||
/// <summary>Screen rect of a plate at a given upward nudge: (x0, y0, x1, y1).</summary>
|
||||
private static Vector4 RectAt(Plate p, float nudge, float uiScale)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
/// <summary>Monster plates: the health bar's width and height, and their text (name, level, HP, weak-to, distance).</summary>
|
||||
public static float MonsterBarWidth = 1.0f, MonsterBarHeight = 1.0f, MonsterTextSize = 1.0f;
|
||||
/// <summary>Name labels over NPCs and vendors.</summary>
|
||||
public static float NpcTextSize = 1.0f;
|
||||
/// <summary>Name labels over other players.</summary>
|
||||
public static float PlayerTextSize = 1.0f;
|
||||
/// <summary>Your own plate: the three bars' width and height, and their text (cur / max numbers, your name).</summary>
|
||||
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; }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Applies the file's key=value lines (unknown keys and bad values are skipped). Also the tests' entry.</summary>
|
||||
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);
|
||||
|
||||
/// <summary>Writes the settings in the background. Any thread.</summary>
|
||||
|
|
@ -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 */ }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Every setting as the file's key=value lines. Also the tests' entry.</summary>
|
||||
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";
|
||||
|
||||
/// <summary>Back to the defaults (and saved). Render / chat thread.</summary>
|
||||
|
|
@ -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();
|
||||
}
|
||||
|
||||
/// <summary>Every plate type's bar and text size back to 1 (and saved). Render / chat thread.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The fixed plate back to its default spot (and saved). Render / chat thread.</summary>
|
||||
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";
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
|
||||
/// <summary>A size multiplier slider ("1.00x" = the default look) with a tooltip. Labels are the ids: keep them unique.</summary>
|
||||
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);
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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++)
|
||||
|
|
|
|||
|
|
@ -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))
|
||||
|
|
|
|||
|
|
@ -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<string> _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<int> _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<int> { i });
|
||||
ImGuiNET.ImGui.PopID();
|
||||
return;
|
||||
}
|
||||
|
|
@ -362,6 +396,216 @@ internal sealed class NavFace : IImGuiPanel
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Plain click selects one row, Ctrl toggles a row, Shift selects from the anchor.</summary>
|
||||
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<int> SelectedIndices()
|
||||
{
|
||||
var list = new List<int>(_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;
|
||||
}
|
||||
|
||||
/// <summary>Moves the selected rows one slot, the way the plugin does (NavRouteEditing.Move).</summary>
|
||||
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<NavPoint>();
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>Each selected row gets a copy right after it (as the plugin does); the copies end up selected.</summary>
|
||||
private void DuplicateSelected()
|
||||
{
|
||||
if (_multi.Count == 0) return;
|
||||
NavCommands.Send(new NavCmd { Cmd = "duplicatePoints", Indices = SelectedIndices() });
|
||||
var result = new List<NavPoint>(_data.Points.Count + _multi.Count);
|
||||
var copies = new HashSet<int>();
|
||||
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<int>(_multi));
|
||||
}
|
||||
|
||||
/// <summary>Drops rows from the local copy and shifts the selection past them.</summary>
|
||||
private void RemoveLocal(HashSet<int> removed)
|
||||
{
|
||||
int Shift(int i) { int s = 0; foreach (int r in removed) if (r < i) s++; return i - s; }
|
||||
var keep = new List<int>();
|
||||
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<int>();
|
||||
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();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<string, string> TabLabels = new();
|
||||
|
|
|
|||
|
|
@ -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<uint>();
|
||||
public uint[] SpecializedXp = Array.Empty<uint>();
|
||||
public ulong[] LevelXp = Array.Empty<ulong>();
|
||||
/// <summary>The same arrays as one object (Compatibility/TrainingCosts).</summary>
|
||||
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) ──
|
||||
|
||||
/// <summary>True when <paramref name="ranks"/> is the table's top rank (nothing left to buy).</summary>
|
||||
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);
|
||||
|
||||
/// <summary>XP to buy <paramref name="n"/> more ranks from <paramref name="ranks"/> with <paramref name="spent"/> already spent; -1 past the top.</summary>
|
||||
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);
|
||||
|
||||
/// <summary>How many ranks in a row <paramref name="available"/> XP buys (0 when not even one), up to the top rank.</summary>
|
||||
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);
|
||||
|
||||
/// <summary>Bounds-checked little-endian reader; Ok turns false on overrun.</summary>
|
||||
private ref struct Reader
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>Label, then the slider; saves on release (or after Ctrl+click typing). True while in use.</summary>
|
||||
private bool Slider(Field f, ref double value, double min, double max, string format)
|
||||
{
|
||||
|
|
|
|||
|
|
@ -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}.");
|
||||
})
|
||||
|
|
|
|||
135
src/RynthCore.Engine/ImGui/UiDropTargets.cs
Normal file
135
src/RynthCore.Engine/ImGui/UiDropTargets.cs
Normal file
|
|
@ -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<string, Target> Targets = new(StringComparer.Ordinal);
|
||||
private static readonly object Sync = new();
|
||||
|
||||
/// <summary>
|
||||
/// Once per frame from a face's Draw: <paramref name="min"/>..<paramref name="max"/> is the
|
||||
/// body in screen coordinates as ImGui sees them (FaceKit.Begin's origin and size).
|
||||
/// <paramref name="accepting"/> 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The face's draw: an item dropped on it since the last call.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The cursor is over the target now (the face's "drop here" highlight).</summary>
|
||||
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<string>();
|
||||
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) + ".";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -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();
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
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
|
||||
|
|
|
|||
157
src/RynthCore.Engine/Net/AcPacketWire.cs
Normal file
157
src/RynthCore.Engine/Net/AcPacketWire.cs
Normal file
|
|
@ -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;
|
||||
|
||||
/// <summary>Packet header flag bits the reader needs.</summary>
|
||||
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
|
||||
|
||||
/// <summary>Flags whose optional header this reader can't size; a fragment datagram carrying one is skipped.</summary>
|
||||
public const uint Unsized = LogonServerAddr | Referral | LoginRequest | 0x00800000u | 0xF0000000u | 0x000000F8u;
|
||||
}
|
||||
|
||||
internal enum PacketWalk : byte
|
||||
{
|
||||
/// <summary>Fragments located.</summary>
|
||||
Ok,
|
||||
/// <summary>No BlobFragments flag: nothing to reassemble (acks, pings, time sync...).</summary>
|
||||
NoFragments,
|
||||
/// <summary>Shorter than a header, or the sizes don't add up.</summary>
|
||||
Malformed,
|
||||
/// <summary>Carries an optional header this reader can't size.</summary>
|
||||
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));
|
||||
|
||||
/// <summary>The datagram's flags, or 0 when it is shorter than a header.</summary>
|
||||
public static uint Flags(byte* data, int length) => length >= HeaderSize ? ReadU32(data + 4) : 0;
|
||||
|
||||
/// <summary>
|
||||
/// Finds the fragment area of one datagram: [fragStart, fragEnd). Never reads past
|
||||
/// <paramref name="length"/>. Ok only when the optional headers sized and fragEnd is
|
||||
/// exactly where the header's size says the datagram ends.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
307
src/RynthCore.Engine/Net/FragmentReassembler.cs
Normal file
307
src/RynthCore.Engine/Net/FragmentReassembler.cs
Normal file
|
|
@ -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;
|
||||
|
||||
/// <summary>Receives each completed message. <paramref name="message"/> starts with the u32 opcode and is valid only during the call.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Forget everything in progress and the done window (a new session, or the stream switched on).</summary>
|
||||
public void Reset()
|
||||
{
|
||||
foreach (Slot s in _slots)
|
||||
s.InUse = false;
|
||||
Array.Clear(_done);
|
||||
_maxDone = 0;
|
||||
_anyDone = false;
|
||||
}
|
||||
|
||||
/// <summary>One received datagram. <paramref name="nowMs"/> is any monotonic millisecond clock.</summary>
|
||||
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<byte>(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);
|
||||
}
|
||||
}
|
||||
139
src/RynthCore.Engine/Net/PacketRing.cs
Normal file
139
src/RynthCore.Engine/Net/PacketRing.cs
Normal file
|
|
@ -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
|
||||
|
||||
/// <summary>Largest datagram accepted; anything longer is dropped (AC's are under 500 bytes).</summary>
|
||||
public const int MaxDatagram = 2048;
|
||||
|
||||
public long Written;
|
||||
public long DroppedFull;
|
||||
public long DroppedContended;
|
||||
public long DroppedTooLong;
|
||||
|
||||
/// <summary>The ring's memory is never freed: the detour may still be running at teardown.</summary>
|
||||
/// <param name="startCounter">Where the wrapping byte counters start (tests start them near int.MaxValue).</param>
|
||||
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;
|
||||
|
||||
/// <summary>Bytes in use (approximate when read from another thread).</summary>
|
||||
public int Used => unchecked(Volatile.Read(ref _head) - Volatile.Read(ref _tail));
|
||||
|
||||
/// <summary>Producer: copy one datagram in. Never blocks; false = dropped (counted).</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Consumer: the oldest record, in place. Call <see cref="Release"/> with the returned
|
||||
/// token when done with it (the bytes stay valid until then).
|
||||
/// </summary>
|
||||
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);
|
||||
|
||||
/// <summary>Consumer: drop everything queued (used when the stream is switched on again).</summary>
|
||||
public void Clear() => Volatile.Write(ref _tail, Volatile.Read(ref _head));
|
||||
}
|
||||
84
src/RynthCore.Engine/Net/ServerMessageInterest.cs
Normal file
84
src/RynthCore.Engine/Net/ServerMessageInterest.cs
Normal file
|
|
@ -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;
|
||||
|
||||
/// <summary>Replaces the set. False (set left empty) for an entry out of range or too many entries.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary><paramref name="eventType"/> is only looked at for opcode 0xF7B0.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
336
src/RynthCore.Engine/Net/ServerMessageStream.cs
Normal file
336
src/RynthCore.Engine/Net/ServerMessageStream.cs
Normal file
|
|
@ -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<string, KindStats> Kinds = new();
|
||||
private static readonly Dictionary<uint, long> 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;
|
||||
}
|
||||
|
||||
/// <summary>True while the detour copies datagrams.</summary>
|
||||
public static bool Capturing => _capturing;
|
||||
|
||||
// ── receive hook side ───────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Called by the RecvFrom detour after the real recvfrom, with the bytes it returned.</summary>
|
||||
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 ───────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Once per ProcessPendingActions (the single TickAll driver). <paramref name="pluginsWant"/>:
|
||||
/// some initialized plugin has a non-empty interest.
|
||||
/// </summary>
|
||||
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<string>
|
||||
{
|
||||
$"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<byte>(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<byte>(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<byte> 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<byte>(data, len));
|
||||
_captureBytes += 6 + len;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
StopCapture($"failed ({ex.Message})");
|
||||
return;
|
||||
}
|
||||
if (_captureBytes >= MaxCaptureBytes)
|
||||
StopCapture("reached its size cap");
|
||||
}
|
||||
|
||||
/// <summary>Engine shutdown: close a capture file. The ring stays allocated (see PacketRing).</summary>
|
||||
public static void Shutdown()
|
||||
{
|
||||
_capturing = false;
|
||||
if (_capture != null) StopCapture("closed at shutdown");
|
||||
}
|
||||
}
|
||||
|
|
@ -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<string> _disabledUiHooks = new(StringComparer.OrdinalIgnoreCase);
|
||||
private static bool _serverMessageStream = true;
|
||||
private static bool _loaded;
|
||||
|
||||
public static IReadOnlyList<string> PluginPaths
|
||||
|
|
@ -279,6 +282,39 @@ internal static class EngineSettings
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>"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.</summary>
|
||||
public static bool IsUiHookEnabled(string name)
|
||||
{
|
||||
EnsureLoaded();
|
||||
return !_disabledUiHooks.Contains(name);
|
||||
}
|
||||
|
||||
/// <summary>Switches a UI hook on or off for the next start, and saves engine.json.</summary>
|
||||
public static void SetUiHookEnabled(string name, bool enabled)
|
||||
{
|
||||
EnsureLoaded();
|
||||
bool changed = enabled ? _disabledUiHooks.Remove(name) : _disabledUiHooks.Add(name);
|
||||
if (changed)
|
||||
Save();
|
||||
}
|
||||
|
||||
/// <summary>"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.</summary>
|
||||
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());
|
||||
|
|
|
|||
|
|
@ -60,6 +60,21 @@ internal sealed class LoadedPlugin
|
|||
/// <summary>Set after the first RenderOverlay call has been logged (render thread only).</summary>
|
||||
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) ──
|
||||
/// <summary><c>void RynthPluginOnServerMessage(uint opcode, byte* data, int length)</c>, Cdecl.</summary>
|
||||
public IntPtr OnServerMessagePtr { get; set; }
|
||||
/// <summary>What the plugin asked for; null or empty = nothing.</summary>
|
||||
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; } = "";
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public RynthCore.PluginSdk.Manifest.RynthPluginManifest? Manifest { get; set; }
|
||||
/// <summary>Why the plugin was not started (a required plugin missing or failed); empty otherwise.</summary>
|
||||
public string NotStartedReason { get; set; } = "";
|
||||
|
||||
/// <summary>
|
||||
/// Drops managed delegates wrapping exports so the native module can fully unload after
|
||||
/// the host calls FreeLibrary (hot-reload / rescan).
|
||||
|
|
|
|||
|
|
@ -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+.</summary>
|
||||
public IntPtr CloseContainerFn;
|
||||
|
||||
/// <summary>v77: <c>int GetMergeStackResult(uint sourceObjectId, uint targetObjectId, int* amount, int* ageMs)</c>:
|
||||
/// <summary>v77: <c>int GetScreenMode(int* previousMode)</c>: 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+.</summary>
|
||||
public IntPtr GetScreenModeFn;
|
||||
|
||||
/// <summary>v77: <c>uint GetUiHookFlags(void)</c>: 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+.</summary>
|
||||
public IntPtr GetUiHookFlagsFn;
|
||||
|
||||
/// <summary>v78: <c>int SetServerMessageInterest(uint* opcodes, int opcodeCount, uint* gameEvents,
|
||||
/// int eventCount)</c>: which reassembled server messages the calling plugin wants on its
|
||||
/// <c>void RynthPluginOnServerMessage(uint opcode, byte* data, int length)</c> 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+.</summary>
|
||||
public IntPtr SetServerMessageInterestFn;
|
||||
|
||||
/// <summary>v79: <c>int GetTrainingInfo(TrainingInfoNative* info, TrainingEntryNative* entries,
|
||||
/// int maxEntries)</c>: 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+.</summary>
|
||||
public IntPtr GetTrainingInfoFn;
|
||||
|
||||
/// <summary>v79: <c>int Raise(uint kind, uint stype, uint ranks, long expectedXp, long* xpSent)</c>:
|
||||
/// 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+.</summary>
|
||||
public IntPtr RaiseFn;
|
||||
|
||||
/// <summary>v79: <c>int TrainSkill(uint stype, int expectedCredits)</c>: 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+.</summary>
|
||||
public IntPtr TrainSkillFn;
|
||||
|
||||
/// <summary>v80: <c>int GetMergeStackResult(uint sourceObjectId, uint targetObjectId, int* amount, int* ageMs)</c>:
|
||||
/// 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.</summary>
|
||||
/// 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).</summary>
|
||||
public IntPtr GetMergeStackResultFn;
|
||||
}
|
||||
|
||||
/// <summary>v79 <see cref="TrainingInfoNative.Flags"/> bits.</summary>
|
||||
internal static class TrainingInfoFlags
|
||||
{
|
||||
public const uint InWorld = 1u << 0;
|
||||
/// <summary>The attribute, vital and skill raise senders are bound on this client.</summary>
|
||||
public const uint RaiseBound = 1u << 1;
|
||||
/// <summary>The train-with-credits sender is bound.</summary>
|
||||
public const uint TrainBound = 1u << 2;
|
||||
/// <summary>The player's numbers have been read (entries follow).</summary>
|
||||
public const uint HaveNumbers = 1u << 3;
|
||||
/// <summary>The portal SkillTable and XpTable are loaded.</summary>
|
||||
public const uint HaveTables = 1u << 4;
|
||||
/// <summary>A raise or train from the API hasn't shown up in the numbers yet.</summary>
|
||||
public const uint Busy = 1u << 5;
|
||||
}
|
||||
|
||||
/// <summary>v79 <see cref="TrainingEntryNative.Flags"/> bits.</summary>
|
||||
internal static class TrainingEntryFlags
|
||||
{
|
||||
/// <summary>Can be raised with XP (an attribute, a vital, a trained or specialized skill below the top rank).</summary>
|
||||
public const uint Raisable = 1u << 0;
|
||||
public const uint AtTop = 1u << 1;
|
||||
/// <summary>Skills: usable untrained (the SkillTable's min level 1).</summary>
|
||||
public const uint UsableUntrained = 1u << 2;
|
||||
/// <summary>Skills: untrained, and the SkillTable prices training it (TrainCredits).</summary>
|
||||
public const uint Trainable = 1u << 3;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// v79 <c>GetTrainingInfo</c> header. Pack 4, 64 bytes; later versions only append.
|
||||
/// Mirrored by RynthCore.PluginSdk (TrainingInfoNative in RynthCoreApiNative.cs).
|
||||
/// </summary>
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
||||
internal unsafe struct TrainingInfoNative
|
||||
{
|
||||
/// <summary>In: the caller's sizeof. Out: bytes written.</summary>
|
||||
public uint Size;
|
||||
/// <summary><see cref="TrainingInfoFlags"/>.</summary>
|
||||
public uint Flags;
|
||||
/// <summary>Changes whenever any number changes.</summary>
|
||||
public uint SnapshotVersion;
|
||||
/// <summary>Milliseconds since the numbers were read; 0xFFFFFFFF = never.</summary>
|
||||
public uint AgeMs;
|
||||
/// <summary>-1 when unknown.</summary>
|
||||
public long UnassignedXp;
|
||||
/// <summary>-1 when unknown.</summary>
|
||||
public long TotalXp;
|
||||
public int Level;
|
||||
/// <summary>-1 when unknown.</summary>
|
||||
public int SkillCredits;
|
||||
public int EntryCount;
|
||||
/// <summary>Raise refuses numbers older than this (Stale).</summary>
|
||||
public int StaleAfterMs;
|
||||
public fixed uint Reserved[4];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// v79 <c>GetTrainingInfo</c> entry: one attribute, vital or skill. Pack 4, 64 bytes; later
|
||||
/// versions only append. Mirrored by RynthCore.PluginSdk (TrainingEntryNative).
|
||||
/// </summary>
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
||||
internal struct TrainingEntryNative
|
||||
{
|
||||
/// <summary>1 attribute, 2 vital, 3 skill.</summary>
|
||||
public uint Kind;
|
||||
/// <summary>Attribute 1..6, vital maximum 1 / 3 / 5, skill id.</summary>
|
||||
public uint Stype;
|
||||
/// <summary>Skills: 0 not in the table, 1 untrained, 2 trained, 3 specialized. 0 otherwise.</summary>
|
||||
public uint Class;
|
||||
public uint Ranks;
|
||||
public uint XpSpent;
|
||||
/// <summary>The innate (starting) level.</summary>
|
||||
public uint Innate;
|
||||
/// <summary>Without enchantments (a vital's maximum).</summary>
|
||||
public int Base;
|
||||
public int Buffed;
|
||||
/// <summary>XP for one more rank; -1 at the top or not raisable.</summary>
|
||||
public long CostOne;
|
||||
/// <summary>XP for ten more ranks; -1 when fewer than ten are left or not raisable.</summary>
|
||||
public long CostTen;
|
||||
public int RanksLeft;
|
||||
/// <summary>Ranks in a row the unassigned XP buys now.</summary>
|
||||
public int Affordable;
|
||||
/// <summary>Untrained skills: the credits to train it (0 = can't be trained from the client).</summary>
|
||||
public int TrainCredits;
|
||||
/// <summary><see cref="TrainingEntryFlags"/>.</summary>
|
||||
public uint Flags;
|
||||
}
|
||||
|
||||
/// <summary>v72 <see cref="TradeStateNative.Flags"/> bits.</summary>
|
||||
internal static class TradeStateFlags
|
||||
{
|
||||
|
|
@ -976,11 +1130,8 @@ internal unsafe struct VendorTradeStatusNative
|
|||
|
||||
|
||||
|
||||
/// <summary>Current API version. Bump when adding fields to RynthCoreAPI.</summary>
|
||||
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);
|
||||
|
|
|
|||
20
src/RynthCore.Engine/Plugins/PluginContractVersion.cs
Normal file
20
src/RynthCore.Engine/Plugins/PluginContractVersion.cs
Normal file
|
|
@ -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;
|
||||
|
||||
/// <summary>Current API version. Bump when adding fields to RynthCoreAPI (and the SDK's RynthCoreApiNative).</summary>
|
||||
internal static class PluginContractVersion
|
||||
{
|
||||
// v80: GetMergeStackResult (was v77 on QOL-items, renumbered after upstream's v77-v79).
|
||||
public const uint Current = 80;
|
||||
}
|
||||
282
src/RynthCore.Engine/Plugins/PluginManager.UiHooks.cs
Normal file
282
src/RynthCore.Engine/Plugins/PluginManager.UiHooks.cs
Normal file
|
|
@ -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
|
||||
|
||||
/// <summary>The thread that ran TickAll last (the plugin pump).</summary>
|
||||
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<PendingUiEvent> _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]<int, int, void>)fn)((int)evt.A, (int)evt.B);
|
||||
break;
|
||||
case UiEventKind.TooltipShow:
|
||||
((delegate* unmanaged[Cdecl]<uint, uint, void>)fn)(evt.A, evt.B);
|
||||
break;
|
||||
case UiEventKind.TooltipHide:
|
||||
((delegate* unmanaged[Cdecl]<void>)fn)();
|
||||
break;
|
||||
case UiEventKind.DragStart:
|
||||
case UiEventKind.ItemDropped:
|
||||
((delegate* unmanaged[Cdecl]<uint, uint, uint, void>)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 ──────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// <paramref name="timeoutMs"/>. 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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
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]<void>)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 ──────────────────────────────────────────────────
|
||||
|
||||
/// <summary>v77: see PluginContract.GetScreenModeFn.</summary>
|
||||
private static unsafe int GetScreenModeAction(int* previousMode)
|
||||
{
|
||||
if (previousMode != null)
|
||||
*previousMode = UiFlowHooks.PreviousMode;
|
||||
return UiFlowHooks.CurrentMode;
|
||||
}
|
||||
|
||||
/// <summary>v77: see PluginContract.GetUiHookFlagsFn.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
|
@ -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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reload deferral (2026-10-05, ReloadDeferral): asks every running plugin's optional
|
||||
/// <c>const char* RynthPluginReloadBlocker(void)</c> 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.
|
||||
/// </summary>
|
||||
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]<IntPtr>)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<string>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
var extraPaths = EngineSettings.PluginPaths;
|
||||
var candidates = new List<string>(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 ─────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Refusals not yet said in chat; said once each, at login (see AnnouncePluginRefusals).</summary>
|
||||
private static readonly List<string> _pendingRefusalNotices = new();
|
||||
private static readonly HashSet<string> _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();
|
||||
}
|
||||
|
||||
/// <summary>Says each refusal once in chat ("[RynthCore] RynthOracle needs a newer RynthCore (API 77) - not started."). Pump thread.</summary>
|
||||
private static void AnnouncePluginRefusals()
|
||||
{
|
||||
List<string> lines;
|
||||
lock (_pendingRefusalNotices)
|
||||
{
|
||||
if (_pendingRefusalNotices.Count == 0) return;
|
||||
lines = new List<string>(_pendingRefusalNotices);
|
||||
_pendingRefusalNotices.Clear();
|
||||
foreach (string l in lines) _announcedRefusals.Add(l);
|
||||
}
|
||||
foreach (string line in lines)
|
||||
AcMainThreadQueue.EnqueueWriteToChat($"[RynthCore] {line} - not started.", 1);
|
||||
}
|
||||
|
||||
/// <summary>The loaded plugin going by <paramref name="name"/>: manifest name, else its file's name, else RynthPluginName.</summary>
|
||||
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
|
|||
/// <summary>v72: see PluginContract.TradeCloseFn.</summary>
|
||||
private static int TradeCloseAction() => ToAbiBool(PlayerTrade.Close());
|
||||
|
||||
// ── v79: spending experience (Compatibility/TrainingApi.cs) ─────────
|
||||
|
||||
/// <summary>v79: see PluginContract.GetTrainingInfoFn.</summary>
|
||||
private static unsafe int GetTrainingInfoAction(TrainingInfoNative* info, TrainingEntryNative* entries, int maxEntries)
|
||||
{
|
||||
try
|
||||
{
|
||||
return TrainingApi.GetInfo(info, entries, maxEntries);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>v79: see PluginContract.RaiseFn.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>v79: see PluginContract.TrainSkillFn.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>v78: see PluginContract.SetServerMessageInterestFn.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>v78: initialized, healthy plugins with a non-empty server-message interest.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// v78: one reassembled server message to the plugins that asked for it (called from
|
||||
/// ServerMessageStream.Pump, on this pump). <paramref name="body"/> is the message after
|
||||
/// its opcode, valid only during the call. Returns how many plugins were called.
|
||||
/// </summary>
|
||||
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]<uint, byte*, int, void>)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;
|
||||
}
|
||||
|
||||
/// <summary>v76: close an external container (see PluginContract.CloseContainerFn).</summary>
|
||||
private static int CloseContainerAction(uint containerId)
|
||||
{
|
||||
|
|
|
|||
119
src/RynthCore.Engine/Plugins/PluginManifestGate.cs
Normal file
119
src/RynthCore.Engine/Plugins/PluginManifestGate.cs
Normal file
|
|
@ -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
|
||||
{
|
||||
/// <summary>Paths to load, in order, with their manifests (null for a plugin without one).</summary>
|
||||
public List<(string Path, RynthPluginManifest? Manifest)> Load { get; } = new();
|
||||
/// <summary>Plugins not loaded, with the reason (one sentence, fit for chat).</summary>
|
||||
public List<PluginRefusal> Refused { get; } = new();
|
||||
/// <summary>Log lines: manifests found, broken manifests, notes.</summary>
|
||||
public List<string> Log { get; } = new();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the manifests of <paramref name="paths"/> and resolves them against
|
||||
/// <paramref name="engineApi"/>. <paramref name="fileVersion"/> gives a DLL's version resource
|
||||
/// (for dependency versions of plugins whose manifest has none); null skips it.
|
||||
/// </summary>
|
||||
public static LoadPlan Plan(IReadOnlyList<string> paths, uint engineApi, Func<string, string>? fileVersion = null)
|
||||
{
|
||||
var plan = new LoadPlan();
|
||||
var candidates = new List<PluginCandidate>(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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Null when every plugin <paramref name="manifest"/> requires has started; otherwise why not.
|
||||
/// <paramref name="started"/> answers by plugin name: true started, false loaded but not
|
||||
/// started (failed or refused at Init), null not loaded at all.
|
||||
/// </summary>
|
||||
public static string? CheckRequiredStarted(RynthPluginManifest? manifest, Func<string, bool?> 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;
|
||||
}
|
||||
|
||||
/// <summary>"RynthOracle 2026.10.5.1, API 71+, needs RynthAi (optional)".</summary>
|
||||
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<string>(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;
|
||||
}
|
||||
}
|
||||
113
src/RynthCore.Engine/ReloadDeferral.cs
Normal file
113
src/RynthCore.Engine/ReloadDeferral.cs
Normal file
|
|
@ -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
|
||||
{
|
||||
/// <summary>Longest a reload waits for the plugins (then it goes ahead, and says so).</summary>
|
||||
public static readonly TimeSpan DefaultCap = TimeSpan.FromMinutes(2);
|
||||
/// <summary>How often the plugins are asked again while one blocks.</summary>
|
||||
public static readonly TimeSpan DefaultPoll = TimeSpan.FromMilliseconds(500);
|
||||
/// <summary>While waiting, the "still waiting" line repeats this often (the first line is at once).</summary>
|
||||
public static readonly TimeSpan DefaultLogEvery = TimeSpan.FromSeconds(15);
|
||||
|
||||
public enum Outcome
|
||||
{
|
||||
/// <summary>No plugin objected: reload at once.</summary>
|
||||
Clear,
|
||||
/// <summary>A plugin objected, then cleared within the cap.</summary>
|
||||
ClearedAfterWait,
|
||||
/// <summary>Still objecting at the cap: reload anyway.</summary>
|
||||
TimedOut,
|
||||
}
|
||||
|
||||
/// <summary>The plugins that object now, each with its reason (empty = safe).</summary>
|
||||
public required Func<IReadOnlyList<(string Plugin, string Reason)>> Query { get; init; }
|
||||
public required Action<string> Log { get; init; }
|
||||
/// <summary>Told once, when the wait starts (the engine puts it in chat).</summary>
|
||||
public Action<string>? Notify { get; init; }
|
||||
public Func<DateTime> Clock { get; init; } = () => DateTime.UtcNow;
|
||||
public Action<TimeSpan> 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;
|
||||
|
||||
/// <summary>Asks the plugins until none objects or <see cref="Cap"/> has passed.</summary>
|
||||
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).");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>"RynthAi in combat (a monster engaged)", several joined with "; ".</summary>
|
||||
public static string Describe(IReadOnlyList<(string Plugin, string Reason)> blockers)
|
||||
{
|
||||
var parts = new List<string>(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)>();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -78,10 +78,14 @@
|
|||
<Compile Include="..\RynthCore.App\CharacterCacheStore.cs" Link="Shared\CharacterCacheStore.cs" />
|
||||
<Compile Include="..\RynthCore.App\SessionStateStore.cs" Link="Shared\SessionStateStore.cs" />
|
||||
<Compile Include="..\RynthCore.App\BuildVersion.cs" Link="Shared\BuildVersion.cs" />
|
||||
<!-- DXT1/3/5 for AC icons in script windows (UI/ScriptWindows/AcIconDecoder.cs); the StatusAgent's copy (MonoGame, Ms-PL). -->
|
||||
<!-- DXT1/3/5 for AC icons in script windows (UI/ScriptWindows/AcIconDecoder.cs); the StatusAgent's decoder (RynthCore's own, MIT). -->
|
||||
<Compile Include="..\RynthCore.StatusAgent\Dat\DxtUtil.cs" Link="Shared\DxtUtil.cs" />
|
||||
<!-- The byte-ring protocol shared with the Decal bridge plugin (docs/DECAL_BRIDGE_PLAN.md). -->
|
||||
<Compile Include="..\RynthCore.DecalBridge\BridgeProtocol.cs" Link="Shared\BridgeProtocol.cs" />
|
||||
<!-- Plugin manifests: read from each plugin DLL before loading it (Plugins/PluginManifestGate.cs). -->
|
||||
<Compile Include="..\RynthCore.PluginSdk\Manifest\*.cs" Link="Shared\Manifest\%(Filename)%(Extension)" />
|
||||
<!-- The SDK's server-message parsers: /rc netmsg log checks them against the live server (Net/ServerMessageStream.cs). -->
|
||||
<Compile Include="..\RynthCore.PluginSdk\Net\*.cs" Link="Shared\Net\%(Filename)%(Extension)" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- Prevent trimmer from removing ImGui.NET's DllImport methods -->
|
||||
|
|
|
|||
|
|
@ -39,7 +39,7 @@ internal static class RynthLog
|
|||
/// <summary>Uncategorised line (General category, Info by default).</summary>
|
||||
internal static void Info(string msg) => WriteCategory(LogCategory.General, msg);
|
||||
|
||||
/// <summary>Alias kept for SK-local call sites; same as <see cref="Warn"/>.</summary>
|
||||
/// <summary>Same as <see cref="Warn"/>.</summary>
|
||||
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");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal static void Heartbeat(string msg) => EntryPoint.LogTagged("engine", msg, "INF");
|
||||
|
||||
/// <summary>Always-on ERROR line — a fault/crash/disable, written even at level Off. Triage with grep "[ERR]".</summary>
|
||||
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.
|
||||
|
||||
/// <summary>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.</summary>
|
||||
internal static bool MoveTraceEnabled = true;
|
||||
|
||||
/// <summary>Every server UseDone (0x01C7) with its sequence number and error code
|
||||
/// (before: the first 25 of a session).</summary>
|
||||
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 = "";
|
||||
|
||||
/// <summary>
|
||||
/// One plugin movement call (see <see cref="MoveTraceEnabled"/>). <paramref name="name"/>
|
||||
/// must be a string literal (it also goes into AcActionTrace, which keeps the last 256
|
||||
/// actions for crash dumps); <paramref name="a"/>/<paramref name="b"/> are its trace args.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>The plugin whose tick or event is calling, else the thread.</summary>
|
||||
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}";
|
||||
}
|
||||
|
||||
/// <summary>True when a line in <paramref name="category"/> would be written (guard expensive messages).</summary>
|
||||
internal static bool IsEnabled(LogCategory category) => LogSettings.IsEnabled(category);
|
||||
|
||||
// ── Sink ─────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Uncategorised line (General category); used by the Move/UseDone traces.</summary>
|
||||
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);
|
||||
|
||||
|
|
|
|||
28
src/RynthCore.Engine/UI/Data/ArgbOpacity.cs
Normal file
28
src/RynthCore.Engine/UI/Data/ArgbOpacity.cs
Normal file
|
|
@ -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
|
||||
{
|
||||
/// <summary>The colour's alpha as 0..100 %.</summary>
|
||||
public static float Percent(uint argb) => (argb >> 24) * 100f / 255f;
|
||||
|
||||
/// <summary>The colour with its alpha set from <paramref name="percent"/> (clamped to 0..100); RGB kept.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -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();
|
||||
|
|
|
|||
|
|
@ -139,6 +139,8 @@ internal sealed class LootEditItemRequestDto
|
|||
public string RuleName { get; set; } = string.Empty;
|
||||
/// <summary>True: the profile open in the Loot Editor; false: the one RynthAi loots with.</summary>
|
||||
public bool ToOpenProfile { get; set; }
|
||||
/// <summary>Also require the item's T11 attributes (added 2026-10-07; an older RynthAi ignores it).</summary>
|
||||
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; }
|
||||
/// <summary>The rule includes the item's T11 attributes (added 2026-10-07; false from an older RynthAi).</summary>
|
||||
public bool IncludeT11 { get; set; }
|
||||
/// <summary>The item is T11 gear (added 2026-10-07; false from an older RynthAi).</summary>
|
||||
public bool IsT11 { get; set; }
|
||||
public int Action { get; set; }
|
||||
public int KeepCount { get; set; }
|
||||
public string RuleName { get; set; } = string.Empty;
|
||||
|
|
|
|||
|
|
@ -43,6 +43,13 @@ internal sealed class NavPayload
|
|||
public bool TrackBreadcrumbs { get; set; }
|
||||
/// <summary>RynthAi draws the route overlay (rings / lines, waypoint labels, guide line).</summary>
|
||||
public bool ShowRouteOverlay { get; set; }
|
||||
/// <summary>Route recording is on (points are added as you walk). Older plugins omit it.</summary>
|
||||
public bool IsRecording { get; set; }
|
||||
/// <summary>Breadcrumb trail size, for "Trail to route" / "Backtrack".</summary>
|
||||
public int TrailPoints { get; set; }
|
||||
public double TrailYards { get; set; }
|
||||
/// <summary>The last route edit's result, for a few seconds after it (empty otherwise).</summary>
|
||||
public string EditStatus { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>A copy a face may change (its own point list); the points themselves are shared.</summary>
|
||||
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<int>? 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)",
|
||||
};
|
||||
|
||||
/// <summary>Route picker index for the plugin's RouteType (1 Circular, 2 Linear, 3 Follow, else Once).</summary>
|
||||
public static int RouteIndex(int routeType) => routeType switch { 1 => 1, 2 => 2, 3 => 3, _ => 0 };
|
||||
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
/// <summary>"Name=Level" per trace category, ','-joined; Level 0 Off, 1 Trace, 2 Info. See <see cref="TraceCategoryLevels"/>.</summary>
|
||||
public string DiagCategories { get; set; } = string.Empty;
|
||||
/// <summary>Read-only (RynthAi ignores it on save): the diagnostics folder.</summary>
|
||||
public string DiagFolder { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>A private copy for a face to edit (all members are values or strings).</summary>
|
||||
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 }
|
||||
|
||||
/// <summary>
|
||||
/// Reads and edits <see cref="RynthAiSettings.DiagCategories"/> ("Name=Level,..."). The category
|
||||
/// list comes from RynthAi, so a category it adds shows up without an engine change.
|
||||
/// </summary>
|
||||
internal static class TraceCategoryLevels
|
||||
{
|
||||
public const int Off = 0, Trace = 1, Info = 2;
|
||||
|
||||
/// <summary>The categories in RynthAi's order; malformed entries are skipped.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Turns tracing on or off for one category (empty <paramref name="name"/> with a
|
||||
/// <paramref name="prefix"/>: every category starting with it; both empty: all). On keeps
|
||||
/// a category already at Info at Info, the same rule as /ra trace.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Checkbox label: the name, plus " +log" at Info (trace lines also go to the normal log).</summary>
|
||||
public static string Label(string name, int level) => level == Info ? name + " +log" : name;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 <you>\") 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_<date>.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\\<Category>_<date>.txt (/ra trace <category> 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_<date>.txt with full stack traces (throttled). Settings here are for this PC, not the profile."),
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// [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.
|
||||
/// </summary>
|
||||
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<string> 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
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
||||
/// <summary>A read-only portal.dat opened for a batch of reads. Not thread-safe.</summary>
|
||||
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<byte> 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<byte> 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));
|
||||
|
||||
/// <summary>A block chain: each block starts with the next block's offset (0 = last).</summary>
|
||||
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<byte> dest)
|
||||
{
|
||||
if ((long)offset + 4 > _fs.Length) return null;
|
||||
var buffer = new byte[size];
|
||||
Span<byte> 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<byte> 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<byte> 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
|
|||
|
||||
/// <summary>
|
||||
/// A 0x06 Texture as RGBA, or null (not a texture id, missing, an unsupported format, larger
|
||||
/// than <see cref="MaxSide"/>, or short data). Layout: id u32, unknown i32, width i32,
|
||||
/// than <see cref="MaxSide"/>, 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.
|
||||
/// </summary>
|
||||
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;
|
||||
|
||||
/// <summary>A Texture file's bytes as RGBA (see <see cref="Decode(AcDatFile, uint)"/>); <paramref name="readPalette"/> loads a 0x04 palette.</summary>
|
||||
internal static AcIconImage? DecodeTextureFile(byte[] data, Func<uint, byte[]?> readPalette, int maxSide = MaxSide)
|
||||
{
|
||||
if (data.Length < 24) return null;
|
||||
maxSide = Math.Clamp(maxSide, 1, MaxUiSide);
|
||||
ReadOnlySpan<byte> 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<byte>(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<byte[], int, int, byte[]> 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<byte> src, int w, int h, int blockBytes, Func<byte[], int, int, byte[]> 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) };
|
||||
}
|
||||
|
||||
/// <summary>Palette (0x04): id u32, count i32, count x u32 ARGB.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,7 +6,25 @@ namespace RynthCore.PluginCore;
|
|||
|
||||
public abstract class RynthPluginBase
|
||||
{
|
||||
public virtual uint MinimumApiVersion => RynthCoreHost.BaselineApiVersion;
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public virtual uint MinimumApiVersion => ManifestMinimum(GetType()) ?? RynthCoreHost.BaselineApiVersion;
|
||||
|
||||
private static uint? ManifestMinimum(Type pluginType)
|
||||
{
|
||||
try
|
||||
{
|
||||
return System.Reflection.CustomAttributeExtensions.GetCustomAttribute<RynthPluginManifestAttribute>(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.
|
||||
|
||||
/// <summary>The client changed screens (<see cref="RynthScreenMode"/>): e.g. World to CharacterSelect at logout.</summary>
|
||||
public virtual void OnScreenChanged(int oldMode, int newMode) { }
|
||||
/// <summary>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).</summary>
|
||||
public virtual void OnClientCleanup() { }
|
||||
/// <summary>AC shows a tooltip for an item (objectId) or a spell icon (spellId); both 0 for any other element.</summary>
|
||||
public virtual void OnTooltipShow(uint objectId, uint spellId) { }
|
||||
/// <summary>The tooltip from <see cref="OnTooltipShow"/> is gone.</summary>
|
||||
public virtual void OnTooltipHide() { }
|
||||
/// <summary>The player started dragging an item (objectId, its icon) or a spell (spellId) in AC's UI.</summary>
|
||||
public virtual void OnDragStart(uint objectId, uint spellId, uint iconId) { }
|
||||
/// <summary>AC took a dropped item or spell; targetElementId is the AC UI element it landed on.</summary>
|
||||
public virtual void OnItemDropped(uint objectId, uint spellId, uint targetElementId) { }
|
||||
}
|
||||
|
|
|
|||
|
|
@ -279,6 +279,53 @@ public unsafe sealed class RynthPluginRuntime<TPlugin>
|
|||
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)
|
||||
|
|
|
|||
196
src/RynthCore.PluginSdk/Manifest/PluginManifestReader.cs
Normal file
196
src/RynthCore.PluginSdk/Manifest/PluginManifestReader.cs
Normal file
|
|
@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// The plugin's manifest; null when the DLL has none (a plugin from before manifests: it
|
||||
/// keeps working as before). Throws <see cref="InvalidDataException"/> when there is one but
|
||||
/// it is broken, and IO exceptions when the file can't be read.
|
||||
/// </summary>
|
||||
public static RynthPluginManifest? Read(string dllPath)
|
||||
{
|
||||
string? json = ReadJson(dllPath);
|
||||
return json == null ? null : RynthPluginManifest.Parse(json);
|
||||
}
|
||||
|
||||
/// <summary>The embedded manifest's text, or null when the file has none.</summary>
|
||||
public static string? ReadJson(string dllPath)
|
||||
{
|
||||
using var fs = new FileStream(dllPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
|
||||
return ReadJson(fs);
|
||||
}
|
||||
|
||||
/// <summary>The embedded manifest's text, or null when the image has none.</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>A minimal reader for a PE file's resource directory (no Win32 calls).</summary>
|
||||
public static class PeResources
|
||||
{
|
||||
/// <summary>
|
||||
/// The data of resource <paramref name="type"/>/<paramref name="name"/> (first language), or null
|
||||
/// when the file has no such resource. Throws <see cref="InvalidDataException"/> on a malformed image.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds an entry in the directory at <paramref name="dir"/> by id (or, with <paramref name="name"/>,
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
180
src/RynthCore.PluginSdk/Manifest/PluginManifestResolver.cs
Normal file
180
src/RynthCore.PluginSdk/Manifest/PluginManifestResolver.cs
Normal file
|
|
@ -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;
|
||||
|
||||
/// <summary>One plugin to consider: its path (or any key), and its manifest if it has one.</summary>
|
||||
public sealed class PluginCandidate
|
||||
{
|
||||
/// <param name="fileVersion">The DLL's version resource (ProductVersion), used when the manifest has no version or there is no manifest.</param>
|
||||
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; }
|
||||
/// <summary>The manifest name, or for a plugin without one the name from its file.</summary>
|
||||
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; }
|
||||
/// <summary>One sentence, fit for chat: "RynthOracle needs a newer RynthCore (API 77)".</summary>
|
||||
public string Reason { get; }
|
||||
/// <summary>True for an engine API mismatch, false for a dependency problem.</summary>
|
||||
public bool IsEngineMismatch { get; }
|
||||
}
|
||||
|
||||
public sealed class PluginResolution
|
||||
{
|
||||
/// <summary>The plugins to load and start, in order.</summary>
|
||||
public List<PluginCandidate> Order { get; } = new();
|
||||
public List<PluginRefusal> Refused { get; } = new();
|
||||
/// <summary>Things worth a log line that refuse nothing (a missing optional dependency, a dev build, a cycle).</summary>
|
||||
public List<string> Notes { get; } = new();
|
||||
}
|
||||
|
||||
public static class PluginManifestResolver
|
||||
{
|
||||
public static PluginResolution Resolve(IReadOnlyList<PluginCandidate> candidates, uint engineApi)
|
||||
{
|
||||
var result = new PluginResolution();
|
||||
var refused = new Dictionary<PluginCandidate, string>();
|
||||
|
||||
// 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<PluginCandidate>();
|
||||
foreach (PluginCandidate c in candidates)
|
||||
if (!refused.ContainsKey(c)) accepted.Add(c);
|
||||
|
||||
var placed = new HashSet<PluginCandidate>();
|
||||
var visiting = new HashSet<PluginCandidate>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Null when <paramref name="d"/> is satisfied by a plugin in <paramref name="available"/>
|
||||
/// (by name; a dev build satisfies any version), else why not.
|
||||
/// </summary>
|
||||
public static string? CheckDependency(IReadOnlyList<PluginCandidate> available, IReadOnlyDictionary<PluginCandidate, string>? 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<PluginCandidate> 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<PluginCandidate, string> refused, PluginCandidate c, string why, bool engine)
|
||||
{
|
||||
if (refused.ContainsKey(c)) return;
|
||||
refused[c] = why;
|
||||
result.Refused.Add(new PluginRefusal(c, why, engine));
|
||||
}
|
||||
}
|
||||
232
src/RynthCore.PluginSdk/Manifest/RynthPluginManifest.cs
Normal file
232
src/RynthCore.PluginSdk/Manifest/RynthPluginManifest.cs
Normal file
|
|
@ -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;
|
||||
|
||||
/// <summary>One plugin another needs (or can use).</summary>
|
||||
public sealed class RynthPluginDependency
|
||||
{
|
||||
/// <summary>The other plugin's manifest name (for a plugin without a manifest: its file name without "RynthCore.Plugin." and ".dll").</summary>
|
||||
public string Name { get; set; } = "";
|
||||
/// <summary>The lowest version that will do; empty for any.</summary>
|
||||
public string MinVersion { get; set; } = "";
|
||||
/// <summary>True: used when present, the plugin still runs without it. False: required, the plugin isn't started without it.</summary>
|
||||
public bool Optional { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>A plugin's manifest (schema 1). Unknown JSON fields are ignored, so later schemas can add fields.</summary>
|
||||
public sealed class RynthPluginManifest
|
||||
{
|
||||
/// <summary>Windows resource type the manifest is stored under (RT_RCDATA).</summary>
|
||||
public const int ResourceType = 10;
|
||||
/// <summary>Windows resource name the manifest is stored under.</summary>
|
||||
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; } = "";
|
||||
/// <summary>The oldest engine API the plugin runs on: its highest unguarded API use.</summary>
|
||||
public uint MinEngineApi { get; set; }
|
||||
/// <summary>The newest engine API the plugin is known to work with; 0 = no upper limit (the usual case: the table is append-only).</summary>
|
||||
public uint MaxEngineApi { get; set; }
|
||||
public List<RynthPluginDependency> Dependencies { get; set; } = new();
|
||||
public string Author { get; set; } = "";
|
||||
public string Description { get; set; } = "";
|
||||
public string Homepage { get; set; } = "";
|
||||
public string License { get; set; } = "";
|
||||
|
||||
/// <summary>Parses a manifest; throws <see cref="InvalidDataException"/> with the reason when it isn't one.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Parses, or returns null with the reason in <paramref name="error"/>.</summary>
|
||||
public static RynthPluginManifest? TryParse(string json, out string error)
|
||||
{
|
||||
try { error = ""; return Parse(json); }
|
||||
catch (InvalidDataException ex) { error = ex.Message; return null; }
|
||||
}
|
||||
|
||||
/// <summary>The manifest as JSON (UTF-8, indented): what the build embeds.</summary>
|
||||
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());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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)".
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>"RynthCore.Plugin.RynthNav.dll" -> "RynthNav": the name a plugin without a manifest goes by.</summary>
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Plugin version strings: "2026.10.5.1", "1.2", "2026.10.5.1+8ca322f".</summary>
|
||||
public static class PluginVersion
|
||||
{
|
||||
/// <summary>Parses the numeric part (build metadata after '+' and a '-prerelease' tail are ignored).</summary>
|
||||
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!);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static bool IsDevBuild(string? text) =>
|
||||
TryParse(text, out Version v) && v.Major == 1 && v.Minor == 0 && v.Build <= 0 && v.Revision <= 0;
|
||||
|
||||
/// <summary>True when <paramref name="actual"/> is at least <paramref name="minimum"/> (or either is missing, or actual is a dev build).</summary>
|
||||
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));
|
||||
}
|
||||
350
src/RynthCore.PluginSdk/Net/Messages.cs
Normal file
350
src/RynthCore.PluginSdk/Net/Messages.cs
Normal file
|
|
@ -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 ───────────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>0x02BB: local speech. Text, sender name, sender id, chat type.</summary>
|
||||
public sealed record HearSpeech(string Text, string SenderName, uint SenderId, uint ChatType)
|
||||
{
|
||||
public static bool TryParse(ReadOnlySpan<byte> body, out HearSpeech msg) => TryParse(body, out msg, out _);
|
||||
|
||||
public static bool TryParse(ReadOnlySpan<byte> 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>0x02BC: ranged speech (shouts, NPC speech). Text, sender name, sender id, range, chat type.</summary>
|
||||
public sealed record HearRangedSpeech(string Text, string SenderName, uint SenderId, float Range, uint ChatType)
|
||||
{
|
||||
public static bool TryParse(ReadOnlySpan<byte> body, out HearRangedSpeech msg) => TryParse(body, out msg, out _);
|
||||
|
||||
public static bool TryParse(ReadOnlySpan<byte> 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>0x01E0 (emote) and 0x01E2 (soul emote): sender id, sender name, text.</summary>
|
||||
public sealed record HearEmote(uint SenderId, string SenderName, string Text, bool Soul)
|
||||
{
|
||||
public static bool TryParse(ReadOnlySpan<byte> body, bool soul, out HearEmote msg) => TryParse(body, soul, out msg, out _);
|
||||
|
||||
public static bool TryParse(ReadOnlySpan<byte> 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Game event 0x02BD: a tell. Text, sender name, sender id, target id, chat type, then a u32 of flags.</summary>
|
||||
public sealed record HearDirectSpeech(string Text, string SenderName, uint SenderId, uint TargetId, uint ChatType, uint Flags)
|
||||
{
|
||||
public static bool TryParse(ReadOnlySpan<byte> body, out HearDirectSpeech msg) => TryParse(body, out msg, out _);
|
||||
|
||||
public static bool TryParse(ReadOnlySpan<byte> 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Game event 0x0147: a chat channel line (allegiance, fellowship, ...). Channel id, sender name (empty for your own), text.</summary>
|
||||
public sealed record ChannelBroadcast(uint Channel, string SenderName, string Text)
|
||||
{
|
||||
public static bool TryParse(ReadOnlySpan<byte> body, out ChannelBroadcast msg) => TryParse(body, out msg, out _);
|
||||
|
||||
public static bool TryParse(ReadOnlySpan<byte> 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Game events 0x0004 (popup box) and 0x02EB (transient text): one string.</summary>
|
||||
public sealed record SystemText(string Text, bool Transient)
|
||||
{
|
||||
public static bool TryParse(ReadOnlySpan<byte> body, bool transient, out SystemText msg) => TryParse(body, transient, out msg, out _);
|
||||
|
||||
public static bool TryParse(ReadOnlySpan<byte> 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Game event 0x0274: a yes/no prompt (fellowship invite, swear allegiance, crafting...). Type, context id, text.</summary>
|
||||
public sealed record ConfirmationRequest(uint ConfirmationType, uint ContextId, string Text)
|
||||
{
|
||||
public static bool TryParse(ReadOnlySpan<byte> body, out ConfirmationRequest msg) => TryParse(body, out msg, out _);
|
||||
|
||||
public static bool TryParse(ReadOnlySpan<byte> 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 ────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Game event 0x027A: an allegiance member logged in or out. Character id, logged in (u32 flag).</summary>
|
||||
public sealed record AllegianceLoginNotification(uint CharacterId, bool LoggedIn)
|
||||
{
|
||||
public static bool TryParse(ReadOnlySpan<byte> body, out AllegianceLoginNotification msg) => TryParse(body, out msg, out _);
|
||||
|
||||
public static bool TryParse(ReadOnlySpan<byte> 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One friends-list entry: id, online, appearing offline, name, and the two id lists the server keeps with it.</summary>
|
||||
public sealed record FriendData(uint Id, bool Online, bool AppearOffline, string Name, uint[] OutFriends, uint[] InFriends);
|
||||
|
||||
/// <summary>Game event 0x0021: the friends list, whole or changed. A packed list of entries, then the update type.</summary>
|
||||
public sealed record FriendsUpdate(IReadOnlyList<FriendData> Friends, uint UpdateType)
|
||||
{
|
||||
public const uint Full = 0, Added = 1, Removed = 2, LoginChange = 4;
|
||||
|
||||
public static bool TryParse(ReadOnlySpan<byte> body, out FriendsUpdate msg) => TryParse(body, out msg, out _);
|
||||
|
||||
public static bool TryParse(ReadOnlySpan<byte> 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<FriendData>(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 ─────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>A fellowship member: cached XP and luminance shares, level, max and current vitals, share-loot flag, name.</summary>
|
||||
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)
|
||||
{
|
||||
/// <summary>Fellow body: 9 u32 (xp, lum, level, max h/s/m, current h/s/m), u32 share-loot flag, name.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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 (<see cref="TailParsed"/>), and the members are returned either way.
|
||||
/// </summary>
|
||||
public sealed record FellowshipFullUpdate(string Name, uint LeaderId, bool ShareXp, bool EvenXpSplit, bool Open, bool Locked,
|
||||
IReadOnlyList<Fellow> Fellows, IReadOnlyDictionary<uint, int> RecentlyDeparted, IReadOnlyList<string> LockNames, bool TailParsed)
|
||||
{
|
||||
public static bool TryParse(ReadOnlySpan<byte> body, out FellowshipFullUpdate msg) => TryParse(body, out msg, out _);
|
||||
|
||||
public static bool TryParse(ReadOnlySpan<byte> 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<Fellow>(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<uint, int>();
|
||||
var locks = new List<string>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Game event 0x02C0: one member changed. Fellow id, the fellow, update type (1 full, 2 stats, 3 vitals).</summary>
|
||||
public sealed record FellowshipUpdateFellow(Fellow Fellow, uint UpdateType)
|
||||
{
|
||||
public static bool TryParse(ReadOnlySpan<byte> body, out FellowshipUpdateFellow msg) => TryParse(body, out msg, out _);
|
||||
|
||||
public static bool TryParse(ReadOnlySpan<byte> 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Game events 0x00A3 (a member quit) and 0x00A4 (a member was dismissed): the member's id.</summary>
|
||||
public sealed record FellowshipMemberLeft(uint FellowId, bool Dismissed)
|
||||
{
|
||||
public static bool TryParse(ReadOnlySpan<byte> body, bool dismissed, out FellowshipMemberLeft msg) => TryParse(body, dismissed, out msg, out _);
|
||||
|
||||
public static bool TryParse(ReadOnlySpan<byte> 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Game event 0x02BF: the fellowship was disbanded (no body).</summary>
|
||||
public sealed record FellowshipDisband
|
||||
{
|
||||
public static readonly FellowshipDisband Instance = new();
|
||||
}
|
||||
121
src/RynthCore.PluginSdk/Net/NetMessages.cs
Normal file
121
src/RynthCore.PluginSdk/Net/NetMessages.cs
Normal file
|
|
@ -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;
|
||||
|
||||
/// <summary>The result of <see cref="NetMessages.Inspect"/>.</summary>
|
||||
public readonly record struct NetMessageInfo(string Kind, bool Known, bool Parsed, int Leftover, string Summary, object? Value);
|
||||
|
||||
public static class NetMessages
|
||||
{
|
||||
/// <summary>
|
||||
/// Parses <paramref name="m"/> if the SDK knows it. Leftover is the bytes the layout
|
||||
/// didn't account for (non-zero means the layout and the server disagree).
|
||||
/// </summary>
|
||||
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<byte> 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<byte> 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<byte> body, int used, string summary, object? value)
|
||||
=> new(kind, true, ok, ok ? body.Length - used : body.Length, summary, ok ? value : null);
|
||||
}
|
||||
160
src/RynthCore.PluginSdk/Net/NetReader.cs
Normal file
160
src/RynthCore.PluginSdk/Net/NetReader.cs
Normal file
|
|
@ -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;
|
||||
|
||||
/// <summary>Reads AC wire types from a span: u16/u32/f32/f64, 16-bit-length strings, packed lists and tables.</summary>
|
||||
public ref struct NetReader
|
||||
{
|
||||
private readonly ReadOnlySpan<byte> _s;
|
||||
private int _pos;
|
||||
|
||||
public NetReader(ReadOnlySpan<byte> 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;
|
||||
}
|
||||
|
||||
/// <summary>A u32 used as a flag: any non-zero value is true.</summary>
|
||||
public bool Bool32(out bool v)
|
||||
{
|
||||
v = false;
|
||||
if (!U32(out uint raw)) return false;
|
||||
v = raw != 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>A packed list's header: u32 count, sanity-checked against the bytes left (each item at least <paramref name="minItemSize"/> bytes).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>A packed hash table's header: u16 count, u16 bucket count (ignored), sanity-checked like <see cref="ListCount"/>.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>A packed list of u32 (u32 count, then the values).</summary>
|
||||
public bool U32List(out uint[] values)
|
||||
{
|
||||
values = Array.Empty<uint>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
104
src/RynthCore.PluginSdk/Net/ServerMessage.cs
Normal file
104
src/RynthCore.PluginSdk/Net/ServerMessage.cs
Normal file
|
|
@ -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;
|
||||
|
||||
/// <summary>A server message: its opcode and the bytes after the opcode. For game events (0xF7B0) also the event header.</summary>
|
||||
public readonly ref struct ServerMessage
|
||||
{
|
||||
public const uint GameEventOpcode = 0xF7B0;
|
||||
|
||||
public uint Opcode { get; }
|
||||
|
||||
/// <summary>The bytes after the u32 opcode.</summary>
|
||||
public ReadOnlySpan<byte> Body { get; }
|
||||
|
||||
public ServerMessage(uint opcode, ReadOnlySpan<byte> body)
|
||||
{
|
||||
Opcode = opcode;
|
||||
Body = body;
|
||||
}
|
||||
|
||||
/// <summary>Wraps RynthPluginOnServerMessage's arguments (no copy).</summary>
|
||||
public static unsafe ServerMessage FromCallback(uint opcode, byte* data, int length)
|
||||
=> new(opcode, data != null && length > 0 ? new ReadOnlySpan<byte>(data, length) : ReadOnlySpan<byte>.Empty);
|
||||
|
||||
/// <summary>From a whole message as it is on the wire (u32 opcode first).</summary>
|
||||
public static bool TryFromWire(ReadOnlySpan<byte> message, out ServerMessage m)
|
||||
{
|
||||
if (message.Length < 4)
|
||||
{
|
||||
m = default;
|
||||
return false;
|
||||
}
|
||||
m = new ServerMessage(BinaryPrimitives.ReadUInt32LittleEndian(message), message.Slice(4));
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>True for a game event (opcode 0xF7B0) with its 12-byte event header.</summary>
|
||||
public bool IsGameEvent => Opcode == GameEventOpcode && Body.Length >= 12;
|
||||
|
||||
/// <summary>Game event: the object it is for (the player).</summary>
|
||||
public uint EventObjectId => IsGameEvent ? BinaryPrimitives.ReadUInt32LittleEndian(Body) : 0;
|
||||
|
||||
/// <summary>Game event: the server's per-player game event sequence.</summary>
|
||||
public uint EventSequence => IsGameEvent ? BinaryPrimitives.ReadUInt32LittleEndian(Body.Slice(4)) : 0;
|
||||
|
||||
/// <summary>Game event: its type (see <see cref="GameEventType"/>); 0 for other messages.</summary>
|
||||
public uint EventType => IsGameEvent ? BinaryPrimitives.ReadUInt32LittleEndian(Body.Slice(8)) : 0;
|
||||
|
||||
/// <summary>Game event: the bytes after the event type.</summary>
|
||||
public ReadOnlySpan<byte> EventBody => IsGameEvent ? Body.Slice(12) : ReadOnlySpan<byte>.Empty;
|
||||
}
|
||||
|
||||
/// <summary>Top-level server message opcodes the SDK parses (and a few landmarks).</summary>
|
||||
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;
|
||||
/// <summary>Pass in the opcode list to get every message.</summary>
|
||||
public const uint All = 0xFFFFFFFF;
|
||||
}
|
||||
|
||||
/// <summary>Game event types (inside opcode 0xF7B0) the SDK parses.</summary>
|
||||
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;
|
||||
}
|
||||
|
|
@ -18,4 +18,16 @@
|
|||
<AssemblyName>RynthCore.PluginSdk</AssemblyName>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- The engine's API version, compiled in so RynthCoreHost.CurrentApiVersion can't drift from it. -->
|
||||
<Compile Include="..\RynthCore.Engine\Plugins\PluginContractVersion.cs" Link="Shared\PluginContractVersion.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!-- Plugin manifests: generated from the plugin's csproj and embedded in its DLL (see the file).
|
||||
Packed as build\RynthCore.PluginSdk.targets so a PackageReference imports it by itself; with
|
||||
a ProjectReference, Directory.Build.targets imports it (RynthSuite\Plugins does). -->
|
||||
<None Include="build\RynthCore.PluginSdk.targets" Pack="true" PackagePath="build\" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -6,7 +6,13 @@ namespace RynthCore.PluginSdk;
|
|||
|
||||
public readonly unsafe struct RynthCoreHost
|
||||
{
|
||||
public const uint CurrentApiVersion = 77; // v77: GetMergeStackResult
|
||||
/// <summary>
|
||||
/// The engine API this SDK's table (<see cref="RynthCoreApiNative"/>) 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.
|
||||
/// </summary>
|
||||
public const uint CurrentApiVersion = RynthCore.Engine.Plugins.PluginContractVersion.Current;
|
||||
|
||||
/// <summary>
|
||||
/// 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;
|
||||
/// <summary>v76: <see cref="CloseContainer"/> (close a corpse or chest like the client's window close).</summary>
|
||||
public bool HasCloseContainer => _api.Version >= 76 && _api.CloseContainerFn != IntPtr.Zero;
|
||||
/// <summary>v77: <see cref="GetScreenMode"/>, <see cref="GetUiHookFlags"/> and the UI callbacks
|
||||
/// (OnScreenChanged, OnClientCleanup, OnTooltipShow/Hide, OnDragStart, OnItemDropped).</summary>
|
||||
public bool HasUiHooks => _api.Version >= 77 && _api.GetScreenModeFn != IntPtr.Zero && _api.GetUiHookFlagsFn != IntPtr.Zero;
|
||||
|
||||
/// <summary>v78: <see cref="SetServerMessageInterest"/> (reassembled server messages on RynthPluginOnServerMessage).</summary>
|
||||
public bool HasServerMessages => _api.Version >= 78 && _api.SetServerMessageInterestFn != IntPtr.Zero;
|
||||
|
||||
/// <summary>v79: <see cref="TryGetTrainingInfo"/>, <see cref="Raise"/> and <see cref="TrainSkill"/>
|
||||
/// (spend unassigned XP and skill credits like the character window).</summary>
|
||||
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]<uint, int>)_api.CloseContainerFn)(containerId) != 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// v77: the client's screen, the UIFlow mode (<see cref="RynthScreenMode"/>): the world,
|
||||
/// character select, the intro... <see cref="RynthScreenMode.Unknown"/> before the engine
|
||||
/// has seen one, and on an engine before v77 (check <see cref="HasUiHooks"/>).
|
||||
/// <paramref name="previousMode"/> is the screen before it. Any thread.
|
||||
/// </summary>
|
||||
public int GetScreenMode(out int previousMode)
|
||||
{
|
||||
previousMode = 0;
|
||||
if (!HasUiHooks) return 0;
|
||||
int prev = 0;
|
||||
int mode = ((delegate* unmanaged[Cdecl]<int*, int>)_api.GetScreenModeFn)(&prev);
|
||||
previousMode = prev;
|
||||
return mode;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// v77: which UI hooks are live on this client (<see cref="RynthUiHookFlags"/>), i.e. which of
|
||||
/// the v77 callbacks can arrive. <see cref="RynthUiHookFlags.None"/> on an engine before v77.
|
||||
/// Any thread.
|
||||
/// </summary>
|
||||
public RynthUiHookFlags GetUiHookFlags()
|
||||
=> HasUiHooks ? (RynthUiHookFlags)((delegate* unmanaged[Cdecl]<uint>)_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".
|
||||
|
||||
/// <summary>
|
||||
/// v79: unassigned XP, credits and, in <paramref name="entries"/> (may be null), one entry per
|
||||
/// attribute, vital and skill with the XP for +1 and +10. <paramref name="entryCount"/> = 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.
|
||||
/// </summary>
|
||||
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]<TrainingInfoNative*, TrainingEntryNative*, int, int>)_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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// v79: raise one attribute (1..6), vital (1 health, 3 stamina, 5 mana) or trained/specialized
|
||||
/// skill by <paramref name="ranks"/> (1..100) with unassigned XP, like the character window's
|
||||
/// "+". <paramref name="expectedXp"/> is the cost the user confirmed (the entry's CostOne /
|
||||
/// CostTen); the engine refuses with <see cref="RaiseResult.CostChanged"/> when the cost now
|
||||
/// differs (0 skips that check). <paramref name="xpSent"/> = the XP sent. Any thread.
|
||||
/// </summary>
|
||||
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]<uint, uint, uint, long, long*, int>)_api.RaiseFn)((uint)kind, stype, ranks, expectedXp, &sent);
|
||||
xpSent = sent;
|
||||
return (RaiseResult)r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// v79: train an untrained skill with skill credits (exactly the entry's TrainCredits, which
|
||||
/// the caller passes as <paramref name="expectedCredits"/>; 0 skips that check). Any thread.
|
||||
/// </summary>
|
||||
public RaiseResult TrainSkill(uint stype, int expectedCredits)
|
||||
=> HasTraining
|
||||
? (RaiseResult)((delegate* unmanaged[Cdecl]<uint, int, int>)_api.TrainSkillFn)(stype, expectedCredits)
|
||||
: RaiseResult.EngineTooOld;
|
||||
|
||||
/// <summary>
|
||||
/// v78: which reassembled server messages this plugin wants on its
|
||||
/// <c>RynthPluginOnServerMessage(uint opcode, byte* data, int length)</c> export (Cdecl;
|
||||
/// see <see cref="Net.ServerMessage"/> for the export and <see cref="Net.ServerOpcode"/> /
|
||||
/// <see cref="Net.GameEventType"/> for the ids the SDK parses). Replaces the previous set;
|
||||
/// two empty lists turn it off. <paramref name="opcodes"/>: top-level opcodes, 0xF7B0 for
|
||||
/// every game event, <see cref="Net.ServerOpcode.All"/> for everything.
|
||||
/// <paramref name="gameEvents"/>: 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 <see cref="HasServerMessages"/>.
|
||||
/// </summary>
|
||||
public int SetServerMessageInterest(ReadOnlySpan<uint> opcodes, ReadOnlySpan<uint> gameEvents)
|
||||
{
|
||||
if (!HasServerMessages)
|
||||
return -4;
|
||||
fixed (uint* ops = opcodes)
|
||||
fixed (uint* evs = gameEvents)
|
||||
{
|
||||
return ((delegate* unmanaged[Cdecl]<uint*, int, uint*, int, int>)_api.SetServerMessageInterestFn)(
|
||||
ops, opcodes.Length, evs, gameEvents.Length);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
|
|
|
|||
18
src/RynthCore.PluginSdk/RynthPluginManifestAttribute.cs
Normal file
18
src/RynthCore.PluginSdk/RynthPluginManifestAttribute.cs
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
using System;
|
||||
|
||||
namespace RynthCore.PluginSdk;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
|
||||
public sealed class RynthPluginManifestAttribute : Attribute
|
||||
{
|
||||
public RynthPluginManifestAttribute(uint minEngineApi) => MinEngineApi = minEngineApi;
|
||||
|
||||
/// <summary>The manifest's minEngineApi.</summary>
|
||||
public uint MinEngineApi { get; }
|
||||
}
|
||||
158
src/RynthCore.PluginSdk/TrainingTypes.cs
Normal file
158
src/RynthCore.PluginSdk/TrainingTypes.cs
Normal file
|
|
@ -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.
|
||||
|
||||
/// <summary>What a raise targets (the API's kind numbers).</summary>
|
||||
public enum TrainingKind : uint
|
||||
{
|
||||
/// <summary>Strength 1, Endurance 2, Quickness 3, Coordination 4, Focus 5, Self 6.</summary>
|
||||
Attribute = 1,
|
||||
/// <summary>A vital's maximum: 1 health, 3 stamina, 5 mana.</summary>
|
||||
Vital = 2,
|
||||
/// <summary>A skill by its id (trained or specialized to raise; untrained to train).</summary>
|
||||
Skill = 3,
|
||||
}
|
||||
|
||||
/// <summary>The engine's answer to <see cref="RynthCoreHost.Raise"/> / <see cref="RynthCoreHost.TrainSkill"/>.</summary>
|
||||
public enum RaiseResult
|
||||
{
|
||||
/// <summary>Sent, or queued for AC's main thread. The new numbers follow within a second or two.</summary>
|
||||
Sent = 1,
|
||||
/// <summary>The client's raise (or train) sender isn't bound on this client build.</summary>
|
||||
Unavailable = 0,
|
||||
NotInWorld = -1,
|
||||
BadArguments = -2,
|
||||
/// <summary>No numbers yet (the engine is reading them); try again in a second.</summary>
|
||||
NotReady = -3,
|
||||
/// <summary>The numbers were too old; a fresh read was asked for. Try again in a moment.</summary>
|
||||
Stale = -4,
|
||||
/// <summary>The cost isn't the one the caller passed: something changed. Refresh and confirm again.</summary>
|
||||
CostChanged = -5,
|
||||
/// <summary>Not enough unassigned XP (or skill credits).</summary>
|
||||
NotEnough = -6,
|
||||
/// <summary>At the top rank, an untrained skill (raise), an already trained skill (train), or no price.</summary>
|
||||
NotRaisable = -7,
|
||||
/// <summary>An earlier raise or train hasn't shown up in the numbers yet (up to 5 s).</summary>
|
||||
Busy = -8,
|
||||
/// <summary>The send failed or the engine's action queue was full.</summary>
|
||||
SendFailed = -9,
|
||||
/// <summary>The engine predates API v79 (SDK-side; the engine never returns it).</summary>
|
||||
EngineTooOld = -100,
|
||||
}
|
||||
|
||||
/// <summary>v79 <see cref="TrainingInfoNative.Flags"/> bits.</summary>
|
||||
public static class TrainingInfoFlags
|
||||
{
|
||||
public const uint InWorld = 1u << 0;
|
||||
/// <summary>The attribute, vital and skill raise senders are bound.</summary>
|
||||
public const uint RaiseBound = 1u << 1;
|
||||
/// <summary>The train-with-credits sender is bound.</summary>
|
||||
public const uint TrainBound = 1u << 2;
|
||||
/// <summary>The player's numbers have been read (entries follow).</summary>
|
||||
public const uint HaveNumbers = 1u << 3;
|
||||
/// <summary>The portal SkillTable and XpTable are loaded.</summary>
|
||||
public const uint HaveTables = 1u << 4;
|
||||
/// <summary>A raise or train from the API hasn't landed yet.</summary>
|
||||
public const uint Busy = 1u << 5;
|
||||
}
|
||||
|
||||
/// <summary>v79 <see cref="TrainingEntryNative.Flags"/> bits.</summary>
|
||||
public static class TrainingEntryFlags
|
||||
{
|
||||
/// <summary>Can be raised with XP (attribute, vital, trained or specialized skill below the top).</summary>
|
||||
public const uint Raisable = 1u << 0;
|
||||
public const uint AtTop = 1u << 1;
|
||||
/// <summary>Skills: usable untrained.</summary>
|
||||
public const uint UsableUntrained = 1u << 2;
|
||||
/// <summary>Skills: untrained and trainable with <see cref="TrainingEntryNative.TrainCredits"/> credits.</summary>
|
||||
public const uint Trainable = 1u << 3;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// v79 GetTrainingInfo header (Pack 4, 64 bytes; later versions only append).
|
||||
/// Mirrors RynthCore.Engine/Plugins/PluginContract.cs TrainingInfoNative exactly.
|
||||
/// </summary>
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
||||
public unsafe struct TrainingInfoNative
|
||||
{
|
||||
/// <summary>In: sizeof(TrainingInfoNative). Out: bytes the engine wrote.</summary>
|
||||
public uint Size;
|
||||
/// <summary><see cref="TrainingInfoFlags"/>.</summary>
|
||||
public uint Flags;
|
||||
/// <summary>Changes whenever any number changes.</summary>
|
||||
public uint SnapshotVersion;
|
||||
/// <summary>Milliseconds since the numbers were read; 0xFFFFFFFF = never.</summary>
|
||||
public uint AgeMs;
|
||||
/// <summary>-1 when unknown.</summary>
|
||||
public long UnassignedXp;
|
||||
/// <summary>-1 when unknown.</summary>
|
||||
public long TotalXp;
|
||||
public int Level;
|
||||
/// <summary>-1 when unknown.</summary>
|
||||
public int SkillCredits;
|
||||
public int EntryCount;
|
||||
/// <summary>Raise refuses numbers older than this (<see cref="RaiseResult.Stale"/>).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// v79 GetTrainingInfo entry: one attribute, vital or skill (Pack 4, 64 bytes; later
|
||||
/// versions only append). Mirrors the engine's TrainingEntryNative exactly.
|
||||
/// </summary>
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 4)]
|
||||
public struct TrainingEntryNative
|
||||
{
|
||||
/// <summary>1 attribute, 2 vital, 3 skill (<see cref="TrainingKind"/>).</summary>
|
||||
public TrainingKind Kind;
|
||||
/// <summary>Attribute 1..6, vital maximum 1 / 3 / 5, skill id.</summary>
|
||||
public uint Stype;
|
||||
/// <summary>Skills: 0 not in the table, 1 untrained, 2 trained, 3 specialized. 0 otherwise.</summary>
|
||||
public uint Class;
|
||||
public uint Ranks;
|
||||
public uint XpSpent;
|
||||
/// <summary>The innate (starting) level.</summary>
|
||||
public uint Innate;
|
||||
/// <summary>Without enchantments (a vital's maximum).</summary>
|
||||
public int Base;
|
||||
public int Buffed;
|
||||
/// <summary>XP for one more rank; -1 at the top or not raisable.</summary>
|
||||
public long CostOne;
|
||||
/// <summary>XP for ten more ranks; -1 when fewer than ten are left or not raisable.</summary>
|
||||
public long CostTen;
|
||||
public int RanksLeft;
|
||||
/// <summary>Ranks in a row the unassigned XP buys now.</summary>
|
||||
public int Affordable;
|
||||
/// <summary>Untrained skills: the credits to train it (0 = not trainable from the client).</summary>
|
||||
public int TrainCredits;
|
||||
/// <summary><see cref="TrainingEntryFlags"/>.</summary>
|
||||
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;
|
||||
}
|
||||
59
src/RynthCore.PluginSdk/UiTypes.cs
Normal file
59
src/RynthCore.PluginSdk/UiTypes.cs
Normal file
|
|
@ -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.
|
||||
|
||||
/// <summary>The client's screen: its UIFlow mode (the client's own ids).</summary>
|
||||
public static class RynthScreenMode
|
||||
{
|
||||
/// <summary>Not known yet (or an engine before v77).</summary>
|
||||
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;
|
||||
/// <summary>The world: the character is logged in.</summary>
|
||||
public const int World = 0x10000008;
|
||||
public const int Epilogue = 0x10000009;
|
||||
public const int CharacterSelect = 0x1000000A;
|
||||
public const int CharacterCreation = 0x1000000B;
|
||||
|
||||
/// <summary>A short name for logs.</summary>
|
||||
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}",
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Which UI hooks are live (RynthCoreHost.GetUiHookFlags), so which callbacks can arrive.</summary>
|
||||
[Flags]
|
||||
public enum RynthUiHookFlags : uint
|
||||
{
|
||||
None = 0,
|
||||
/// <summary>OnScreenChanged comes from the screen-change hook, as it happens.</summary>
|
||||
ScreenHook = 1u << 0,
|
||||
/// <summary>OnScreenChanged comes from the engine's mode poll instead (a tick late).</summary>
|
||||
ScreenPoll = 1u << 1,
|
||||
/// <summary>OnClientCleanup will come when the client shuts down.</summary>
|
||||
ClientCleanup = 1u << 2,
|
||||
TooltipShow = 1u << 3,
|
||||
TooltipHide = 1u << 4,
|
||||
DragStart = 1u << 5,
|
||||
ItemDropped = 1u << 6,
|
||||
/// <summary>The client's cleanup has started: no more ticks or events.</summary>
|
||||
CleanupStarted = 1u << 7,
|
||||
}
|
||||
259
src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets
Normal file
259
src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets
Normal file
|
|
@ -0,0 +1,259 @@
|
|||
<Project>
|
||||
<!--
|
||||
RynthCore plugin manifests, generated from the plugin's csproj.
|
||||
|
||||
A plugin opts in by setting RynthPluginMinEngineApi (the oldest engine API it runs on: its
|
||||
highest API use that is NOT behind a Has*/version check). The build then
|
||||
1. writes obj\...\rynth-plugin.json from the csproj:
|
||||
name RynthPluginName (default: AssemblyName without "RynthCore.Plugin.")
|
||||
version Version (Publish-Update.ps1 passes -p:Version=yyyy.m.d.n)
|
||||
minEngineApi RynthPluginMinEngineApi
|
||||
maxEngineApi RynthPluginMaxEngineApi (optional; leave unset - the table is append-only)
|
||||
dependencies @(RynthPluginDependency) Include = plugin name, metadata MinVersion, Optional="true"
|
||||
author RynthPluginAuthor (default: Authors, then Company)
|
||||
description RynthPluginDescription (default: Description)
|
||||
homepage RynthPluginHomepage (default: PackageProjectUrl)
|
||||
license RynthPluginLicense (default: PackageLicenseExpression)
|
||||
2. adds [assembly: RynthPluginManifest(minEngineApi)], which RynthPluginBase.MinimumApiVersion
|
||||
defaults to (the plugin's own runtime check, which also covers engines from before
|
||||
manifests), and generates RynthPluginInfo (Name, Version, MinEngineApi constants) in the
|
||||
plugin's root namespace for code that wants them;
|
||||
3. embeds the JSON in the compiled assembly as a Windows resource (RCDATA
|
||||
"RYNTH_PLUGIN_MANIFEST"). NativeAOT copies the assembly's Windows resources into the
|
||||
native DLL, so the published plugin carries it too. The engine and the launcher read it
|
||||
from the file without loading the DLL (RynthCore.PluginSdk.Manifest.PluginManifestReader).
|
||||
|
||||
Example:
|
||||
<RynthPluginMinEngineApi>71</RynthPluginMinEngineApi>
|
||||
<ItemGroup><RynthPluginDependency Include="RynthAi" Optional="true" /></ItemGroup>
|
||||
|
||||
RynthPluginManifest=false turns it off. A PackageReference to RynthCore.PluginSdk imports this
|
||||
file by itself (build\); a ProjectReference needs an Import (RynthSuite\Plugins\Directory.Build.targets).
|
||||
-->
|
||||
|
||||
<PropertyGroup>
|
||||
<!-- The engine API this SDK knows; tools\PluginManifestTests checks it equals PluginContractVersion.Current. -->
|
||||
<RynthCoreSdkApiVersion>80</RynthCoreSdkApiVersion>
|
||||
<_RynthPluginManifestOn Condition="'$(RynthPluginMinEngineApi)' != '' and '$(RynthPluginManifest)' != 'false'">true</_RynthPluginManifestOn>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition="'$(_RynthPluginManifestOn)' == 'true'">
|
||||
<RynthPluginName Condition="'$(RynthPluginName)' == ''">$([System.Text.RegularExpressions.Regex]::Replace('$(AssemblyName)', '^RynthCore\.Plugin\.', ''))</RynthPluginName>
|
||||
<RynthPluginAuthor Condition="'$(RynthPluginAuthor)' == '' and '$(Authors)' != '' and '$(Authors)' != '$(AssemblyName)'">$(Authors)</RynthPluginAuthor>
|
||||
<RynthPluginAuthor Condition="'$(RynthPluginAuthor)' == ''">$(Company)</RynthPluginAuthor>
|
||||
<RynthPluginDescription Condition="'$(RynthPluginDescription)' == ''">$(Description)</RynthPluginDescription>
|
||||
<RynthPluginHomepage Condition="'$(RynthPluginHomepage)' == ''">$(PackageProjectUrl)</RynthPluginHomepage>
|
||||
<RynthPluginLicense Condition="'$(RynthPluginLicense)' == ''">$(PackageLicenseExpression)</RynthPluginLicense>
|
||||
<_RynthPluginManifestJson>$(IntermediateOutputPath)rynth-plugin.json</_RynthPluginManifestJson>
|
||||
<_RynthPluginManifestEmbedded>$(IntermediateOutputPath)rynth-plugin.embedded</_RynthPluginManifestEmbedded>
|
||||
<_RynthPluginInfoSource>$(IntermediateOutputPath)RynthPluginInfo.g.cs</_RynthPluginInfoSource>
|
||||
</PropertyGroup>
|
||||
|
||||
<!-- [assembly: RynthPluginManifest(min)]: RynthPluginBase.MinimumApiVersion's default, so the
|
||||
plugin's own check matches its manifest without any code in the plugin. -->
|
||||
<ItemGroup Condition="'$(_RynthPluginManifestOn)' == 'true'">
|
||||
<AssemblyAttribute Include="RynthCore.PluginSdk.RynthPluginManifestAttribute">
|
||||
<_Parameter1>$(RynthPluginMinEngineApi)</_Parameter1>
|
||||
<_Parameter1_IsLiteral>true</_Parameter1_IsLiteral>
|
||||
</AssemblyAttribute>
|
||||
</ItemGroup>
|
||||
|
||||
<UsingTask TaskName="RynthWritePluginManifest" TaskFactory="RoslynCodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll">
|
||||
<Task>
|
||||
<Code Type="Class" Language="cs"><![CDATA[
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using Microsoft.Build.Framework;
|
||||
using Microsoft.Build.Utilities;
|
||||
|
||||
public class RynthWritePluginManifest : Task
|
||||
{
|
||||
[Required] public string Name { get; set; }
|
||||
public string Version { get; set; }
|
||||
[Required] public string MinEngineApi { get; set; }
|
||||
public string MaxEngineApi { get; set; }
|
||||
[Required] public string SdkApiVersion { get; set; }
|
||||
public string Author { get; set; }
|
||||
public string Description { get; set; }
|
||||
public string Homepage { get; set; }
|
||||
public string License { get; set; }
|
||||
public ITaskItem[] Dependencies { get; set; }
|
||||
public string RootNamespace { get; set; }
|
||||
[Required] public string JsonPath { get; set; }
|
||||
[Required] public string InfoSourcePath { get; set; }
|
||||
|
||||
public override bool Execute()
|
||||
{
|
||||
uint min, max = 0, sdk;
|
||||
if (!uint.TryParse(MinEngineApi.Trim(), out min) || min == 0)
|
||||
{ Log.LogError("RynthPluginMinEngineApi must be a positive whole number (got '{0}').", MinEngineApi); return false; }
|
||||
if (!uint.TryParse(SdkApiVersion.Trim(), out sdk)) sdk = 0;
|
||||
if (sdk != 0 && min > 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<string>(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("// <auto-generated>RynthCore.PluginSdk.targets, from the csproj's plugin manifest properties.</auto-generated>\n");
|
||||
if (ns.Length > 0) cs.Append("namespace ").Append(ns).Append(";\n\n");
|
||||
cs.Append("/// <summary>This plugin's manifest (embedded in the DLL as RYNTH_PLUGIN_MANIFEST).</summary>\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(" /// <summary>The oldest engine API this plugin runs on (its manifest's minEngineApi).</summary>\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();
|
||||
}
|
||||
}
|
||||
]]></Code>
|
||||
</Task>
|
||||
</UsingTask>
|
||||
|
||||
<UsingTask TaskName="RynthEmbedPluginManifest" TaskFactory="RoslynCodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.Core.dll">
|
||||
<Task>
|
||||
<Code Type="Class" Language="cs"><![CDATA[
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices;
|
||||
using Microsoft.Build.Framework;
|
||||
using Microsoft.Build.Utilities;
|
||||
|
||||
public class RynthEmbedPluginManifest : Task
|
||||
{
|
||||
[Required] public string AssemblyPath { get; set; }
|
||||
[Required] public string ManifestPath { get; set; }
|
||||
[Required] public string MarkerPath { get; set; }
|
||||
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
private static extern IntPtr BeginUpdateResourceW(string pFileName, bool bDeleteExistingResources);
|
||||
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
|
||||
private static extern bool UpdateResourceW(IntPtr hUpdate, IntPtr lpType, string lpName, ushort wLanguage, byte[] lpData, uint cb);
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
private static extern bool EndUpdateResourceW(IntPtr hUpdate, bool fDiscard);
|
||||
|
||||
public override bool Execute()
|
||||
{
|
||||
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
|
||||
{
|
||||
Log.LogWarning("RynthCore plugin manifest: embedding needs Windows (UpdateResource); '{0}' has no manifest.", AssemblyPath);
|
||||
return true;
|
||||
}
|
||||
byte[] data = File.ReadAllBytes(ManifestPath);
|
||||
IntPtr h = BeginUpdateResourceW(AssemblyPath, false);
|
||||
if (h == IntPtr.Zero)
|
||||
{ Log.LogError("RynthCore plugin manifest: BeginUpdateResource failed on '{0}': {1}", AssemblyPath, new Win32Exception(Marshal.GetLastWin32Error()).Message); return false; }
|
||||
// RT_RCDATA (10), "RYNTH_PLUGIN_MANIFEST", language neutral.
|
||||
if (!UpdateResourceW(h, (IntPtr)10, "RYNTH_PLUGIN_MANIFEST", 0, data, (uint)data.Length))
|
||||
{
|
||||
int err = Marshal.GetLastWin32Error();
|
||||
EndUpdateResourceW(h, true);
|
||||
Log.LogError("RynthCore plugin manifest: UpdateResource failed on '{0}': {1}", AssemblyPath, new Win32Exception(err).Message);
|
||||
return false;
|
||||
}
|
||||
if (!EndUpdateResourceW(h, false))
|
||||
{ Log.LogError("RynthCore plugin manifest: EndUpdateResource failed on '{0}': {1}", AssemblyPath, new Win32Exception(Marshal.GetLastWin32Error()).Message); return false; }
|
||||
File.WriteAllText(MarkerPath, DateTime.UtcNow.ToString("o"));
|
||||
Log.LogMessage(MessageImportance.Normal, "RynthCore plugin manifest embedded in {0}", AssemblyPath);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
]]></Code>
|
||||
</Task>
|
||||
</UsingTask>
|
||||
|
||||
<!-- 1 + 2: the JSON and RynthPluginInfo, before compiling (RynthPluginInfo is compiled in). -->
|
||||
<Target Name="RynthGeneratePluginManifest" BeforeTargets="CoreCompile" Condition="'$(_RynthPluginManifestOn)' == 'true'">
|
||||
<RynthWritePluginManifest Name="$(RynthPluginName)" Version="$(Version)" MinEngineApi="$(RynthPluginMinEngineApi)"
|
||||
MaxEngineApi="$(RynthPluginMaxEngineApi)" SdkApiVersion="$(RynthCoreSdkApiVersion)"
|
||||
Author="$(RynthPluginAuthor)" Description="$(RynthPluginDescription)"
|
||||
Homepage="$(RynthPluginHomepage)" License="$(RynthPluginLicense)"
|
||||
Dependencies="@(RynthPluginDependency)" RootNamespace="$(RootNamespace)"
|
||||
JsonPath="$(_RynthPluginManifestJson)" InfoSourcePath="$(_RynthPluginInfoSource)" />
|
||||
<ItemGroup>
|
||||
<Compile Include="$(_RynthPluginInfoSource)" />
|
||||
<FileWrites Include="$(_RynthPluginManifestJson);$(_RynthPluginInfoSource);$(_RynthPluginManifestEmbedded)" />
|
||||
</ItemGroup>
|
||||
</Target>
|
||||
|
||||
<!-- 3: into the compiled assembly, before it is copied to bin or compiled by NativeAOT (ILC reads
|
||||
@(IntermediateAssembly)). Incremental: again only when the assembly or the JSON changed. -->
|
||||
<Target Name="RynthEmbedPluginManifest" AfterTargets="CoreCompile" Condition="'$(_RynthPluginManifestOn)' == 'true'"
|
||||
Inputs="@(IntermediateAssembly);$(_RynthPluginManifestJson)" Outputs="$(_RynthPluginManifestEmbedded)">
|
||||
<RynthEmbedPluginManifest AssemblyPath="@(IntermediateAssembly->'%(FullPath)')" ManifestPath="$(_RynthPluginManifestJson)"
|
||||
MarkerPath="$(_RynthPluginManifestEmbedded)" />
|
||||
</Target>
|
||||
</Project>
|
||||
|
|
@ -105,6 +105,14 @@ internal sealed class AgentConfig
|
|||
/// /maps returns an empty list and /map 404s — no other feature is affected.</summary>
|
||||
[JsonPropertyName("MapsDirectory")] public string MapsDirectory { get; set; } = Path.Combine(RynthInstallPaths.RynthAiDir, "Maps");
|
||||
|
||||
/// <summary>cell.dat the landscape map (GET /worldmap) is drawn from, once, then cached as worldmap-v1.jpg in
|
||||
/// <see cref="StatusDirectory"/>. Absent = no world map (capabilities.worldMap false); nothing else changes.</summary>
|
||||
[JsonPropertyName("CellDatPath")] public string CellDatPath { get; set; } = @"C:\Games\RynthCore\AcClient\client_cell_1.dat";
|
||||
|
||||
/// <summary>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.</summary>
|
||||
[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");
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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. <see cref="Open"/> 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.
|
||||
/// </summary>
|
||||
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<uint, Node> _interior = new();
|
||||
private readonly Dictionary<uint, LinkedListNode<(uint At, Node Node)>> _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
|
||||
|
||||
/// <summary>Dat header FileType field.</summary>
|
||||
/// <summary>Header word at 0x140 (the dat magic).</summary>
|
||||
public uint FileType { get; private set; }
|
||||
/// <summary>Block size in bytes (typical: 1024).</summary>
|
||||
public uint BlockSize { get; private set; }
|
||||
/// <summary>Total file size from header.</summary>
|
||||
/// <summary>File size recorded in the header.</summary>
|
||||
public uint FileSize { get; private set; }
|
||||
/// <summary>DataSet field from header.</summary>
|
||||
/// <summary>The header's data set (database type) word.</summary>
|
||||
public uint DataSet { get; private set; }
|
||||
/// <summary>Byte offset of the root B-tree node.</summary>
|
||||
public uint BTreeRoot { get; private set; }
|
||||
|
|
@ -44,326 +92,75 @@ public class DatDatabase : IDisposable
|
|||
public bool IsLoaded { get; private set; }
|
||||
/// <summary>Source file path passed to <see cref="Open"/>.</summary>
|
||||
public string? FilePath { get; private set; }
|
||||
/// <summary>Number of files indexed from the B-tree.</summary>
|
||||
/// <summary>Number of files in the dat (counted at <see cref="Open"/>).</summary>
|
||||
public int RecordCount { get; private set; }
|
||||
|
||||
// All files indexed by ObjectId (populated during Open)
|
||||
private readonly Dictionary<uint, DatBTreeEntry> _allFiles = new();
|
||||
|
||||
/// <summary>Most-recent diagnostic messages (capped at 100).</summary>
|
||||
public List<string> 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
|
||||
|
||||
/// <summary>
|
||||
/// Opens the .dat file at <paramref name="path"/> for read-only random access and
|
||||
/// indexes every entry in the B-tree. Returns false on any failure.
|
||||
/// Opens the .dat file at <paramref name="path"/> for read-only random access.
|
||||
/// Returns false on any failure.
|
||||
/// </summary>
|
||||
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<byte> 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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the dat header from offset 0x140.
|
||||
/// Format matches ACE's DatDatabaseHeader.Unpack().
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Recursively reads the B-tree directory and indexes all files.
|
||||
/// Matches ACE's DatDirectory.Read() + AddFilesToList().
|
||||
/// </summary>
|
||||
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];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds a file by ID. O(1) lookup from the pre-built index.
|
||||
/// </summary>
|
||||
public DatBTreeEntry? FindFile(uint fileId)
|
||||
{
|
||||
if (!IsLoaded) return null;
|
||||
_allFiles.TryGetValue(fileId, out var entry);
|
||||
return entry;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads file data for a given entry.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Convenience: find by id then read.</summary>
|
||||
public byte[]? GetFileData(uint fileId)
|
||||
{
|
||||
var entry = FindFile(fileId);
|
||||
return entry != null ? ReadFileData(entry) : null;
|
||||
}
|
||||
|
||||
/// <summary>Returns (fileId, storedSize) for every indexed file whose id is in [lo, hi], sorted by size desc.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public List<uint> GetLandblockCellIds(uint landblockKey)
|
||||
{
|
||||
var cellIds = new List<uint>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns sample file IDs from the index for diagnostics.
|
||||
/// </summary>
|
||||
public List<uint> GetSampleIds(int maxCount = 20)
|
||||
{
|
||||
var ids = new List<uint>();
|
||||
foreach (var kvp in _allFiles)
|
||||
{
|
||||
ids.Add(kvp.Key);
|
||||
if (ids.Count >= maxCount) break;
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
/// <summary>Closes the underlying file handle and clears the index.</summary>
|
||||
/// <summary>Closes the underlying file handle and drops the cached directory nodes.</summary>
|
||||
public void Close()
|
||||
{
|
||||
_stream?.Dispose();
|
||||
_stream = null;
|
||||
IsLoaded = false;
|
||||
_allFiles.Clear();
|
||||
lock (_gate) CloseLocked();
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
|
|
@ -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
|
||||
|
||||
/// <summary>The directory entry for <paramref name="fileId"/>, or null.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The bytes of the file <paramref name="entry"/> describes, or null.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Convenience: find by id then read.</summary>
|
||||
public byte[]? GetFileData(uint fileId) => ReadFileData(FindFile(fileId));
|
||||
|
||||
/// <summary>
|
||||
/// (fileId, storedSize) for every file whose id is in [lo, hi], largest first
|
||||
/// (ties by ascending id).
|
||||
/// </summary>
|
||||
public List<(uint id, uint size)> EntriesInRange(uint lo, uint hi)
|
||||
{
|
||||
var found = new List<DatBTreeEntry>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The interior (EnvCell) ids 0xXXYY0100-0xXXYYFFFD of landblock
|
||||
/// <paramref name="landblockKey"/> (0xXXYY), ascending.
|
||||
/// </summary>
|
||||
public List<uint> GetLandblockCellIds(uint landblockKey)
|
||||
{
|
||||
var found = new List<DatBTreeEntry>();
|
||||
lock (_gate)
|
||||
{
|
||||
if (IsLoaded) Collect(BTreeRoot, (landblockKey << 16) | 0x0100, (landblockKey << 16) | 0xFFFD, found, 0);
|
||||
}
|
||||
var ids = new List<uint>(found.Count);
|
||||
foreach (var e in found) ids.Add(e.ObjectId);
|
||||
return ids;
|
||||
}
|
||||
|
||||
/// <summary>The lowest file ids in the dat (up to <paramref name="maxCount"/>), for diagnostics.</summary>
|
||||
public List<uint> GetSampleIds(int maxCount = 20)
|
||||
{
|
||||
var ids = new List<uint>();
|
||||
if (maxCount <= 0) return ids;
|
||||
var found = new List<DatBTreeEntry>();
|
||||
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<DatBTreeEntry> 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<byte> 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<byte> 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<uint> 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<byte> dest)
|
||||
{
|
||||
int payload = (int)BlockSize - 4;
|
||||
long block = first;
|
||||
int done = 0;
|
||||
Span<byte> 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<byte> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Indexed B-tree entry for one file inside a .dat archive.</summary>
|
||||
/// <summary>One directory entry of a .dat archive.</summary>
|
||||
public class DatBTreeEntry
|
||||
{
|
||||
/// <summary>Raw flag bits from the B-tree.</summary>
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
||||
/// <summary>DXT1/3/5 decompression; output is width * height * 4 bytes, R, G, B, A.</summary>
|
||||
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<byte>();
|
||||
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<byte> palette = stackalloc byte[16]; // 4 colours x RGBA
|
||||
Span<byte> alpha = stackalloc byte[16]; // per pixel (DXT3/5)
|
||||
Span<byte> 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<byte> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <summary>Decodes an AC item icon (a 0x06 Texture in portal.dat) to RGBA pixels.</summary>
|
||||
internal sealed class IconDecoder
|
||||
{
|
||||
private readonly DatDatabase _portal;
|
||||
|
|
@ -22,94 +34,113 @@ internal sealed class IconDecoder
|
|||
public byte[] Pixels = System.Array.Empty<byte>();
|
||||
}
|
||||
|
||||
// Palette (0x04): Id(u32), Colors(List<uint>: 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).
|
||||
/// <summary>The texture <paramref name="textureId"/> as RGBA, or null (missing, unsupported or damaged).</summary>
|
||||
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<byte>(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<byte> s, int at) => System.Buffers.Binary.BinaryPrimitives.ReadInt32LittleEndian(s.Slice(at));
|
||||
private static uint U32(ReadOnlySpan<byte> s, int at) => System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(s.Slice(at));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,6 +28,11 @@ internal sealed class LocalStatusServer : IDisposable
|
|||
private readonly string? _statusDir; // GET /inventory reads RynthCore.<pid>.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<int, bool> _raiseClients = new Dictionary<int, bool>();
|
||||
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
|
|||
}
|
||||
}
|
||||
|
||||
/// <summary>The clients the last cycle read, and which take the raise command (thread-safe swap).</summary>
|
||||
public void UpdateRaiseClients(IEnumerable<ClientStatus> clients)
|
||||
{
|
||||
var map = new Dictionary<int, bool>();
|
||||
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<byte>()); 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.<pid>.<kind>.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;
|
||||
|
||||
|
|
|
|||
|
|
@ -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<EnchantmentIn>? 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; }
|
||||
}
|
||||
|
||||
/// <summary>The plugin's record of the last phone travel: where to, and "sent" / "stopped" / "refused".</summary>
|
||||
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; }
|
||||
}
|
||||
|
||||
/// <summary>The phone's travel status: the plugin's record, RynthNav's latest chat note, and how far is left.</summary>
|
||||
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; }
|
||||
/// <summary>sent | arrived | stopped | refused (and "unavailable" when RynthNav isn't loaded).</summary>
|
||||
[JsonPropertyName("state")] public string State { get; set; } = "";
|
||||
[JsonPropertyName("detail")] public string Detail { get; set; } = "";
|
||||
[JsonPropertyName("sentAt")] public DateTimeOffset? SentAt { get; set; }
|
||||
/// <summary>RynthNav's latest "[RynthNav] ..." chat line, without the tag ("walking to Holtburg — ...").</summary>
|
||||
[JsonPropertyName("note")] public string Note { get; set; } = "";
|
||||
/// <summary>Straight-line distance left in RynthNav's units (yd); null indoors or with no target position.</summary>
|
||||
[JsonPropertyName("distance")] public double? Distance { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>One enchantment as the plugin writes it: spell id + seconds left (-1 = never lapses).</summary>
|
||||
internal sealed class EnchantmentIn
|
||||
{
|
||||
[JsonPropertyName("spellId")] public uint SpellId { get; set; }
|
||||
[JsonPropertyName("secondsRemaining")] public double SecondsRemaining { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>Where the character stands (plugin "opos"): absolute world units, the dungeon-map frame.</summary>
|
||||
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; }
|
||||
}
|
||||
|
||||
/// <summary>One enchantment as the phone reads it (DrakBot Remote's "enchantments" entry).</summary>
|
||||
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; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
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; }
|
||||
/// <summary>GET /nav/search + the travel / travelStop commands (RynthNav through the RynthRemote plugin).</summary>
|
||||
[JsonPropertyName("travel")] public bool Travel { get; set; }
|
||||
/// <summary>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).</summary>
|
||||
[JsonPropertyName("raiseXp")] public bool RaiseXp { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>The subset of the RynthAi snapshot the agent surfaces.</summary>
|
||||
|
|
@ -228,6 +329,17 @@ internal sealed class ClientStatus
|
|||
[JsonPropertyName("recentChat")] public List<ChatLine>? RecentChat { get; set; }
|
||||
[JsonPropertyName("lastIssue")] public string? LastIssue { get; set; }
|
||||
[JsonPropertyName("lastIssueAgeSec")] public long LastIssueAgeSec { get; set; } = -1;
|
||||
/// <summary>Every enchantment on the character, soonest to lapse first (null = the plugin doesn't say).</summary>
|
||||
[JsonPropertyName("enchantments")] public List<EnchantmentOut>? Enchantments { get; set; }
|
||||
/// <summary>Facing in degrees (0 = north, clockwise) when the plugin reports it, for the map's arrow.</summary>
|
||||
[JsonPropertyName("heading")] public double? Heading { get; set; }
|
||||
/// <summary>The last phone travel and how it stands (null when none this session).</summary>
|
||||
[JsonPropertyName("travel")] public TravelOut? Travel { get; set; }
|
||||
/// <summary>This client takes the raise command (its plugin says so and remote control is on).</summary>
|
||||
[JsonPropertyName("raiseXp")] public bool RaiseXp { get; set; }
|
||||
/// <summary>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.</summary>
|
||||
[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<ClientStatus> Clients { get; set; } = new();
|
||||
}
|
||||
|
||||
|
|
|
|||
218
src/RynthCore.StatusAgent/NavAtlasService.cs
Normal file
218
src/RynthCore.StatusAgent/NavAtlasService.cs
Normal file
|
|
@ -0,0 +1,218 @@
|
|||
using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace RynthCore.StatusAgent;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal sealed class NavAtlasService
|
||||
{
|
||||
/// <summary>RynthNav's NavCoords.UnitsPerDegree: one degree of N/S or E/W is 240 units ("yd").</summary>
|
||||
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<Place>? _places;
|
||||
private DateTime _loadedMtime;
|
||||
private string _generated = "";
|
||||
|
||||
public NavAtlasService(string path) => _path = path;
|
||||
|
||||
public bool Available => File.Exists(_path);
|
||||
|
||||
// ── loading ─────────────────────────────────────────────────────────────
|
||||
|
||||
private List<Place> 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<Place>();
|
||||
}
|
||||
return _places;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>locations.json -> places, each on-map one with its nearest town as the area.</summary>
|
||||
internal static (List<Place> 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<Place>(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 ──────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>RynthNav's Atlas.MatchScore: 0 = not a match.</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>RynthNav's Atlas.TypeRank: places before people.</summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The best matches for <paramref name="query"/> (at least 2 characters), optionally of one type: best name
|
||||
/// match, then type, then nearest to (<paramref name="fromNs"/>, <paramref name="fromEw"/>) when given,
|
||||
/// then name. At most <paramref name="max"/>.
|
||||
/// </summary>
|
||||
internal static List<(Place Place, double? Distance)> Search(IReadOnlyList<Place> 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();
|
||||
}
|
||||
|
||||
/// <summary>GET /nav/search's body (schema rynthcore.nav-search/1).</summary>
|
||||
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());
|
||||
}
|
||||
|
||||
/// <summary>RynthNav's NavCoords.Fmt: "42.1N, 33.6E".</summary>
|
||||
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");
|
||||
}
|
||||
|
||||
/// <summary>The status frame's absolute world units to map coordinates (RynthNav's own conversion).</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
|
@ -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<ClientStatus> clients = StatusReader.ReadAll(cfg);
|
||||
List<ClientStatus> 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)
|
||||
{
|
||||
|
|
|
|||
223
src/RynthCore.StatusAgent/RemoteParity.cs
Normal file
223
src/RynthCore.StatusAgent/RemoteParity.cs
Normal file
|
|
@ -0,0 +1,223 @@
|
|||
using System.Globalization;
|
||||
|
||||
namespace RynthCore.StatusAgent;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal static class RemoteParity
|
||||
{
|
||||
// ── landblocks ──────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>The short landblock (0xXXYY) from either form ("5A48", "00005A48", "5A480000", "5A48013F").</summary>
|
||||
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 ────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>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.</summary>
|
||||
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) ────────────────
|
||||
|
||||
/// <summary>
|
||||
/// 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 (<paramref name="raiseClients"/>:
|
||||
/// 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).
|
||||
/// </summary>
|
||||
public static int CheckRaise(int pid, string? value, IReadOnlyDictionary<int, bool> 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] ";
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public static TravelOut? Travel(TravelIn? t, IReadOnlyList<ChatLine>? 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 ────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>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.</summary>
|
||||
public static List<EnchantmentOut>? Enchantments(List<EnchantmentIn>? input, Func<uint, SpellTableService.SpellInfo?> lookup)
|
||||
{
|
||||
if (input == null) return null;
|
||||
var list = new List<EnchantmentOut>(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 ────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>A mouse message's lParam: y in the high word, x in the low.</summary>
|
||||
public static IntPtr MouseLParam(int x, int y) => (IntPtr)unchecked((int)(((uint)(y & 0xFFFF) << 16) | (uint)(x & 0xFFFF)));
|
||||
}
|
||||
|
|
@ -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 }
|
||||
|
||||
/// <summary>What one tap did: where it went in the client area (and how big that is), or why not.</summary>
|
||||
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);
|
||||
|
|
|
|||
150
src/RynthCore.StatusAgent/SpellTableService.cs
Normal file
150
src/RynthCore.StatusAgent/SpellTableService.cs
Normal file
|
|
@ -0,0 +1,150 @@
|
|||
using RynthCore2.TerrainData;
|
||||
|
||||
namespace RynthCore.StatusAgent;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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<uint, SpellInfo>? _table;
|
||||
private int _queued;
|
||||
|
||||
public SpellTableService(string portalDatPath) => _datPath = portalDatPath;
|
||||
|
||||
public bool Ready => _table != null;
|
||||
|
||||
/// <summary>A spell by id, once the table is in; queues the one-time load on first use. Any thread.</summary>
|
||||
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}"); }
|
||||
}
|
||||
|
||||
/// <summary>Parse the SpellTable file. Public for the agent tests (a hand-built table).</summary>
|
||||
internal static Dictionary<uint, SpellInfo> Parse(byte[] raw, out int total)
|
||||
{
|
||||
var t = new Dictionary<uint, SpellInfo>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>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.</summary>
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Bounds-checked little-endian reader; Ok turns false on overrun.</summary>
|
||||
private ref struct SpanReader
|
||||
{
|
||||
private readonly ReadOnlySpan<byte> _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; }
|
||||
|
||||
/// <summary>u16 length + bytes with nibbles swapped, then aligned to 4 from the file start (as ACE does).</summary>
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
75
src/RynthCore.StatusAgent/StatusFileCache.cs
Normal file
75
src/RynthCore.StatusAgent/StatusFileCache.cs
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
using System.Collections.Concurrent;
|
||||
using System.Text;
|
||||
|
||||
namespace RynthCore.StatusAgent;
|
||||
|
||||
/// <summary>
|
||||
/// Reading the per-client files the RynthRemote plugin rewrites several times a second, without ever
|
||||
/// dropping a client from a snapshot.
|
||||
///
|
||||
/// <para>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.</para>
|
||||
///
|
||||
/// <para>Here: a status file that can't be read or parsed is answered with the last good parse of that
|
||||
/// file for up to <see cref="KeepLastGood"/> (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.</para>
|
||||
/// </summary>
|
||||
internal static class StatusFileCache
|
||||
{
|
||||
public static readonly TimeSpan KeepLastGood = TimeSpan.FromSeconds(3);
|
||||
|
||||
private static readonly ConcurrentDictionary<string, (object Model, DateTime AtUtc)> LastGood = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>Read a whole file while letting the writer replace or rewrite it underneath.</summary>
|
||||
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('');
|
||||
|
||||
/// <summary>
|
||||
/// Parse <paramref name="path"/> with <paramref name="parse"/>; on any read or parse failure (or a null
|
||||
/// parse) answer the last good result for that path if it is younger than <see cref="KeepLastGood"/>.
|
||||
/// <paramref name="read"/> is the file reader (tests pass their own).
|
||||
/// </summary>
|
||||
public static T? Read<T>(string path, Func<string, T?> parse, DateTime nowUtc, Func<string, string>? 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;
|
||||
}
|
||||
|
||||
/// <summary>Drop what is remembered for a file that is gone (a retired dead client) or for every file
|
||||
/// not in <paramref name="keep"/>.</summary>
|
||||
public static void Forget(string path) => LastGood.TryRemove(path, out _);
|
||||
|
||||
public static void ForgetAllBut(IReadOnlyCollection<string> keep)
|
||||
{
|
||||
var set = new HashSet<string>(keep, StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var k in LastGood.Keys)
|
||||
if (!set.Contains(k)) LastGood.TryRemove(k, out _);
|
||||
}
|
||||
|
||||
internal static int CountForTests => LastGood.Count;
|
||||
}
|
||||
|
|
@ -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<ClientStatus> ReadAll(AgentConfig cfg)
|
||||
public static List<ClientStatus> ReadAll(AgentConfig cfg, SpellTableService? spells = null)
|
||||
{
|
||||
var clients = new List<ClientStatus>();
|
||||
var seenPids = new HashSet<int>();
|
||||
|
||||
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<ClientStatus> clients, HashSet<int> seenPids)
|
||||
private static void ReadStatusFiles(AgentConfig cfg, List<ClientStatus> clients, HashSet<int> seenPids, SpellTableService? spells)
|
||||
{
|
||||
string dir = cfg.StatusDirectory;
|
||||
if (!Directory.Exists(dir))
|
||||
return;
|
||||
|
||||
var listed = new List<string>();
|
||||
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 ──────────────────
|
||||
|
|
|
|||
231
src/RynthCore.StatusAgent/WorldMapService.cs
Normal file
231
src/RynthCore.StatusAgent/WorldMapService.cs
Normal file
|
|
@ -0,0 +1,231 @@
|
|||
using System.Drawing;
|
||||
using System.Drawing.Imaging;
|
||||
using System.Runtime.InteropServices;
|
||||
using RynthCore2.TerrainData;
|
||||
|
||||
namespace RynthCore.StatusAgent;
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>True when a map can be made here at all (the cell.dat is on this box, or one is cached).</summary>
|
||||
public bool Available => _jpeg != null || File.Exists(_cellDatPath) || File.Exists(CachePath);
|
||||
|
||||
public string State => _state;
|
||||
|
||||
private string CachePath => Path.Combine(_cacheDir, CacheName);
|
||||
|
||||
/// <summary>The JPEG, or null while it is being made (the first call starts that). Any thread.</summary>
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Paint the whole map into a 24-bit RGB buffer (row 0 = north). <paramref name="readLandblock"/>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
internal static byte[] Render(Func<int, byte[]?> 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;
|
||||
}
|
||||
|
||||
/// <summary>Record layout: u32 id, u32 hasObjects, u16 terrain[81], u8 height[81] (vertex = ix*9 + iy).</summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Where a world position lands on the map, in pixels (may fall outside for bad input).</summary>
|
||||
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);
|
||||
|
||||
/// <summary>ACE's LandDefs.TerrainType, 0..20; anything else (the reserved slots) a neutral grey.</summary>
|
||||
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();
|
||||
}
|
||||
}
|
||||
39
tools/DatReaderCheck/DatReaderCheck.csproj
Normal file
39
tools/DatReaderCheck/DatReaderCheck.csproj
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<!--
|
||||
Checks a change to the dat code against the code it replaces, on the real dat files, read
|
||||
only. Covers the StatusAgent's reader and icon decoder (src\RynthCore.StatusAgent\Dat) and
|
||||
the engine's portal reader and icon decoder (src\RynthCore.Engine\UI\ScriptWindows\
|
||||
AcIconDecoder.cs), all compiled in. It uses only their API, so the same source builds
|
||||
against the old code (check out the base commit) and the new; each build writes a manifest
|
||||
and "diff" compares two:
|
||||
|
||||
manifest <AC folder> <out> every file in client_portal.dat and client_cell_1.dat through
|
||||
both readers (id, flags, offset, size, SHA-256 of the bytes),
|
||||
FindFile misses, landblock cell ids, EntriesInRange per type.
|
||||
icons <AC folder> <out> every 0x06 texture through IconDecoder.Decode and
|
||||
AcIconDecoder.Decode (icon and UI limits): size and a SHA-256
|
||||
of the RGBA pixels; 3,000 composed underlay/icon/overlay stacks.
|
||||
diff <a> <b> compares two outputs. Timing lines ("#t") and the order of the
|
||||
list calls ("#o") are reported, not compared: the lists are
|
||||
compared as sets.
|
||||
|
||||
Run: dotnet run -c Release (after the usual separator) icons "C:\Turbine\Asheron's Call" old.txt
|
||||
The RynthSuite twin, Tools\RynthCore.DatReaderCheck, covers RynthAi's reader and geometry.
|
||||
-->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0-windows</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<RootNamespace>DatReaderCheck</RootNamespace>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Include="..\..\src\RynthCore.StatusAgent\Dat\*.cs" Link="StatusAgent\%(Filename)%(Extension)" />
|
||||
<Compile Include="..\..\src\RynthCore.Engine\UI\ScriptWindows\AcIconDecoder.cs" Link="Engine\AcIconDecoder.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue