From 44074df0117fd378202061557c0d004b2c3d80f2 Mon Sep 17 00:00:00 2001 From: Tom Bohar Date: Mon, 19 Oct 2026 09:11:20 -0400 Subject: [PATCH] Snapshot for release 2026.10.19.1 (internal fa7a8f6) --- Changelog/2026-10-18-bar-declutter.md | 60 +++ Changelog/2026-10-18-display-chrome.md | 43 ++ Changelog/2026-10-18-engine-review-fixes.md | 53 ++ Changelog/2026-10-18-enl-calculator.md | 65 +++ Changelog/2026-10-18-reload-hold-optin.md | 54 ++ .../2026-10-18-vaulted-dungeons-setting.md | 38 ++ Changelog/2026-10-19-sk-chat-settings.md | 56 ++ Changelog/2026-10-19-sk-loot-combat.md | 53 ++ installer/Build-Installer.ps1 | 30 +- installer/Publish-Update.ps1 | 78 ++- native/SehTrampoline/CrashLogFilter.h | 61 ++- native/SehTrampoline/SehTrampoline.c | 41 +- .../SehTrampoline/tests/CrashLogFilterTests.c | 79 +++ src/RynthCore.App.Avalonia/MainWindow.axaml | 13 +- .../MainWindow.axaml.cs | 17 + .../RynthCore.App.Avalonia.csproj | 1 + .../ServerProfileDialog.axaml | 7 +- .../ServerProfileDialog.axaml.cs | 45 ++ src/RynthCore.App/KnownServerCatalog.cs | 160 ++++++ .../Compatibility/AppraisalHooks.cs | 14 +- .../Compatibility/AutoIdDrain.cs | 18 +- .../Compatibility/AutoIdService.cs | 8 +- .../Compatibility/HeartbeatLogger.cs | 4 + .../Compatibility/PlayerLifecycleLog.cs | 34 +- .../Compatibility/ProcessExitHooks.cs | 46 +- .../Compatibility/ReleasedObjectRetention.cs | 19 +- .../Compatibility/RynthCoreChatCommands.cs | 47 +- .../Compatibility/WorldTransitionState.cs | 61 ++- src/RynthCore.Engine/CrashDump.cs | 146 +++++ src/RynthCore.Engine/DumpBudget.cs | 62 +++ src/RynthCore.Engine/EntryPoint.cs | 91 +++- .../ImGui/EngineFrameController.cs | 5 + src/RynthCore.Engine/ImGui/ImGuiBar.cs | 16 +- src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs | 3 + src/RynthCore.Engine/ImGui/Panels/ChatFace.cs | 120 ++++- .../ImGui/Panels/ChatFiltersFace.cs | 9 + .../ImGui/Panels/DamageDetailFace.cs | 22 + src/RynthCore.Engine/ImGui/Panels/FaceKit.cs | 61 ++- .../ImGui/Panels/InventoryFace.Classic.cs | 258 ++++++--- .../ImGui/Panels/InventoryFace.cs | 255 ++++++++- .../ImGui/Panels/ItemsFace.cs | 43 +- .../ImGui/Panels/LootAddDialog.cs | 190 ++++++- .../ImGui/Panels/MiniRemoteFace.Sections.cs | 19 +- .../ImGui/Panels/MiniRemoteFace.cs | 6 + src/RynthCore.Engine/ImGui/Panels/NavFace.cs | 10 +- .../ImGui/Panels/OracleSkillsEmbed.cs | 120 +++++ .../ImGui/Panels/RynthAiFace.cs | 32 +- .../ImGui/Panels/ScriptWindowFace.cs | 16 +- .../ImGui/Panels/SettingsRows.cs | 11 +- .../ImGui/Panels/ShownLatch.cs | 62 +++ .../ImGui/Panels/SkillsFace.Progression.cs | 169 ++++++ .../ImGui/Panels/SkillsFace.cs | 88 ++- .../ImGui/Panels/SkillsRouting.cs | 84 +++ src/RynthCore.Engine/LogPaths.cs | 33 ++ .../Plugins/EngineSettings.cs | 228 +++++++- .../Plugins/EngineSettingsFile.cs | 15 +- .../Plugins/ManagedPlugins.cs | 75 ++- .../Plugins/PluginContractVersion.cs | 5 +- src/RynthCore.Engine/Plugins/PluginManager.cs | 36 +- src/RynthCore.Engine/ReloadInWorldGate.cs | 123 +++++ src/RynthCore.Engine/UI/AcWindowChrome.cs | 412 ++++++++++++++ .../UI/AcWindowChromePolicy.cs | 202 +++++++ src/RynthCore.Engine/UI/AvaloniaOverlay.cs | 5 + src/RynthCore.Engine/UI/Data/ChatCoords.cs | 40 +- src/RynthCore.Engine/UI/Data/ChatData.cs | 111 +++- .../UI/Data/ChatFilterPresets.cs | 104 ++++ .../UI/Data/ChatRetailVerdict.cs | 66 +++ .../UI/Data/ChatSettingsDto.cs | 2 + src/RynthCore.Engine/UI/Data/DamageData.cs | 18 +- .../UI/Data/EnlRowConverters.cs | 167 ++++++ src/RynthCore.Engine/UI/Data/LootEditData.cs | 50 ++ .../UI/Data/ProgressionData.cs | 110 +++- src/RynthCore.Engine/UI/Data/RynthAiData.cs | 1 + src/RynthCore.Engine/UI/Data/SettingsData.cs | 218 +++++++- .../UI/Data/SharedFileWatch.cs | 57 ++ .../UI/InventoryTitleLayout.cs | 266 +++++++++ src/RynthCore.Engine/UI/PanelStateStore.cs | 20 +- .../UI/Panels/MonstersPanel.cs | 9 + .../UI/Panels/RynthChatPresets.cs | 111 ++++ .../UI/Panels/SettingsPanel.cs | 13 +- .../UI/ScriptWindows/ScriptWindowRegistry.cs | 6 + .../build/RynthCore.PluginSdk.targets | 2 +- .../BarDeclutterTests.csproj | 29 + tools/BarDeclutterTests/Program.cs | 507 ++++++++++++++++++ tools/ChatCoordTests/ChatCoordTests.csproj | 2 +- tools/ChatCoordTests/ChatSpanShim.cs | 5 + tools/ChatCoordTests/Program.cs | 96 ++++ tools/ChatFilterTests/ChatFilterTests.csproj | 7 + tools/ChatFilterTests/EngineStubs.cs | 24 + tools/ChatFilterTests/Program.cs | 245 +++++++++ .../CombatSettingsTests.csproj | 32 ++ tools/CombatSettingsTests/Program.cs | 182 +++++++ .../EngineRobustnessTests/AutoIdDrainTests.cs | 35 ++ .../EngineRobustnessTests.csproj | 2 + tools/EngineRobustnessTests/Program.cs | 102 ++++ .../EngineRobustnessTests/RingAndGateTests.cs | 81 ++- .../EngineSettingsTests.csproj | 4 + tools/EngineSettingsTests/Program.cs | 478 ++++++++++++++++- .../EnlCalculatorTests.csproj | 28 + tools/EnlCalculatorTests/Program.cs | 269 ++++++++++ tools/EnlCalculatorTests/Stubs.cs | 13 + .../LauncherSettingsTests.csproj | 1 + tools/LauncherSettingsTests/Program.cs | 31 ++ .../LootAddWireTests/LootAddWireTests.csproj | 28 + tools/LootAddWireTests/Program.cs | 96 ++++ tools/PluginManifestTests/Program.cs | 24 +- tools/ReloadInWorldGateTests/Program.cs | 274 ++++++++++ .../ReloadInWorldGateTests.csproj | 25 + tools/VaultedSettingTests/Program.cs | 99 ++++ .../VaultedSettingTests.csproj | 31 ++ 110 files changed, 8042 insertions(+), 316 deletions(-) create mode 100644 Changelog/2026-10-18-bar-declutter.md create mode 100644 Changelog/2026-10-18-display-chrome.md create mode 100644 Changelog/2026-10-18-engine-review-fixes.md create mode 100644 Changelog/2026-10-18-enl-calculator.md create mode 100644 Changelog/2026-10-18-reload-hold-optin.md create mode 100644 Changelog/2026-10-18-vaulted-dungeons-setting.md create mode 100644 Changelog/2026-10-19-sk-chat-settings.md create mode 100644 Changelog/2026-10-19-sk-loot-combat.md create mode 100644 src/RynthCore.App/KnownServerCatalog.cs create mode 100644 src/RynthCore.Engine/DumpBudget.cs create mode 100644 src/RynthCore.Engine/ImGui/Panels/OracleSkillsEmbed.cs create mode 100644 src/RynthCore.Engine/ImGui/Panels/ShownLatch.cs create mode 100644 src/RynthCore.Engine/ImGui/Panels/SkillsRouting.cs create mode 100644 src/RynthCore.Engine/ReloadInWorldGate.cs create mode 100644 src/RynthCore.Engine/UI/AcWindowChrome.cs create mode 100644 src/RynthCore.Engine/UI/AcWindowChromePolicy.cs create mode 100644 src/RynthCore.Engine/UI/Data/ChatRetailVerdict.cs create mode 100644 src/RynthCore.Engine/UI/Data/EnlRowConverters.cs create mode 100644 src/RynthCore.Engine/UI/Data/SharedFileWatch.cs create mode 100644 src/RynthCore.Engine/UI/InventoryTitleLayout.cs create mode 100644 tools/BarDeclutterTests/BarDeclutterTests.csproj create mode 100644 tools/BarDeclutterTests/Program.cs create mode 100644 tools/ChatCoordTests/ChatSpanShim.cs create mode 100644 tools/ChatFilterTests/EngineStubs.cs create mode 100644 tools/CombatSettingsTests/CombatSettingsTests.csproj create mode 100644 tools/CombatSettingsTests/Program.cs create mode 100644 tools/EnlCalculatorTests/EnlCalculatorTests.csproj create mode 100644 tools/EnlCalculatorTests/Program.cs create mode 100644 tools/EnlCalculatorTests/Stubs.cs create mode 100644 tools/LootAddWireTests/LootAddWireTests.csproj create mode 100644 tools/LootAddWireTests/Program.cs create mode 100644 tools/ReloadInWorldGateTests/Program.cs create mode 100644 tools/ReloadInWorldGateTests/ReloadInWorldGateTests.csproj create mode 100644 tools/VaultedSettingTests/Program.cs create mode 100644 tools/VaultedSettingTests/VaultedSettingTests.csproj diff --git a/Changelog/2026-10-18-bar-declutter.md b/Changelog/2026-10-18-bar-declutter.md new file mode 100644 index 0000000..673d532 --- /dev/null +++ b/Changelog/2026-10-18-bar-declutter.md @@ -0,0 +1,60 @@ +# Bar declutter: Item Count and Skills off the bar, Inventory buttons, Skills under Oracle + +Branch `feature/bar-declutter`, from `status-export`. Not deployed, not released. The idea and the first +version are Silentkelpie's (rynth PR 6, "inventory bar declutter ... Skills under Oracle"); this takes the +parts the owner approved and changes what the owner decided differently. + +## Bar + +- Item Count no longer has a bar icon. It opens from Inventory's Count button, `/rc itemcount`, and the + Character menu. +- Mini Remote keeps its bar icon (Silentkelpie removed it; it stays). Inventory gets a Remote button too, as + an addition. +- Skills leaves the bar only while RynthOracle provides the Skills / Attributes / Progress tabs. The icon + shows whenever it does not: no Oracle window registered, or an Oracle that has never sent + `/rc oracle-skills` (an older Oracle). Nobody loses the way in. + +## Skills under Oracle + +- `/rc oracle-skills `: Oracle says which Skills body to embed in its window + (`OracleSkillsEmbed`; the contract is unchanged from the PR). Any valid form also tells the engine that + Oracle has the tabs. An Oracle that wants the Skills icon hidden before the player first opens the tab can + send `/rc oracle-skills off` once at startup. +- `/rc skills`, `/rc progression` and the Character menu's Skills line go to Oracle (`/ro skills`, + `/ro progress`, `/ro attrs`) when its tabs are there, else open the standalone Skills panel as before. + `/rc skills hide` closes Oracle only while it shows a Skills tab; `/rc skills toggle` closes it when it + already shows Skills. +- Fixed from the PR: the embed re-ran `SkillsFace.OnShown()` every two seconds and nothing ever called + `OnHidden`, so the Progression subscription stayed on after Oracle left the tab. Now the face is shown + once when the embed first draws and hidden once when it stops (`ShownLatch`): `/rc oracle-skills off`, + Oracle's window closed or removed, the Oracle plugin unloaded, engine reload / shutdown, or no draw for + a second (idle sweep). `OnShown` / `OnHidden` themselves are idempotent, so subscribing twice never + registers twice. + +## Inventory + +- Modern header and Classic title bar get Mini Remote, RynthSort (`/rsort`), Item Count and Global Inventory + (`/ginv`) buttons. The Character menu gets a Global Inventory line. +- The PR's four text buttons were about 190 px wide: at the retail width (300, scale 1) they pushed the + title to nothing and put Vault (Aelrynth) at about x=-44, off the panel. `UI/InventoryTitleLayout.cs` + now lays the bar out: the size / tools / Modern toggles stay at the right, Vault next to them is always + there, and the four buttons take the richest style that leaves the title 56 units: text (480 wide and + up), icons (360, or retail without Vault), or one "..." menu (retail with Vault). The title is cut with + an ellipsis to the room it has. The Modern header does the same with icons / menu / nothing and drops the + item count text last. +- Settings > Inventory Management > Floating HUDs tooltip says the floating pack count HUD is not the Item + Count panel. + +## Not taken from the PR + +The in-world hot-reload hold, the chat combat filters (already merged), the Enlightenment calculator UI, his +changelog files and version bumps. + +## Files + +- ImGui/Panels/ShownLatch.cs, OracleSkillsEmbed.cs, SkillsRouting.cs (new), SkillsFace.cs, + ScriptWindowFace.cs, InventoryFace.cs, InventoryFace.Classic.cs, RynthAiFace.cs +- ImGui/ImGuiBar.cs, ImGui/ImGuiPanelHost.cs (one idle-sweep line) +- UI/InventoryTitleLayout.cs (new), UI/ScriptWindows/ScriptWindowRegistry.cs, UI/Data/SettingsData.cs +- Compatibility/RynthCoreChatCommands.cs +- Tests: `tools/BarDeclutterTests` (lifecycle balance, TabsAvailable rule, title layout grid) diff --git a/Changelog/2026-10-18-display-chrome.md b/Changelog/2026-10-18-display-chrome.md new file mode 100644 index 0000000..8a7261b --- /dev/null +++ b/Changelog/2026-10-18-display-chrome.md @@ -0,0 +1,43 @@ +# Settings > Display: Borderless Windowed, remembered windows, Save Layout Now + +Branch `feature/display-chrome`, from `status-export`. Not deployed. From SilentKelpie's +RynthCore PR 6 (the Display chrome piece only), with the changes below. + +## What changed + +- `UI/AcWindowChrome.cs` (Win32) and `UI/AcWindowChromePolicy.cs` (the decisions, pure and tested). +- Settings > Display: + - **Borderless Windowed** (`BorderlessWindowed`, default off): hides the Asheron's Call title bar and + borders while staying windowed. + - **Remember Open Windows and Positions** (`RememberWindowLayout`, default on, as panels have always + been): off stops `panel_state.txt` being overwritten and stops panels reopening from the last session. + - **Remember Game Window Position** (`RememberAcWindowPosition`, default off, new): saves the game + window's position and size and puts it back after login. + - **Save Layout Now**: writes open panels, the window position (if remembered), the Vision HUD and + `imgui.ini` now. + +## How it differs from the PR + +- Chrome is only given back to a window this setting stripped. That is recorded on the window itself + (an HWND property holding the style from before), so it survives an engine hot reload and ends with + the process. With the setting off and no marker nothing is touched: exclusive fullscreen and external + borderless tools are left alone. +- The window rect is kept per client (`ac_window..txt`), written only when it + changed (checked every 10 s, written by the background writer). Until a character is known nothing is + restored or saved; after 90 s without one the shared `ac_window.txt` is used. +- Nothing changes the window inside the render callback. EndScene only reads; style changes and the + move/resize are posted to the game window's own WndProc (`Win32Backend.PostToGameThread`, as pop-out + windows are created). Settings toggles go the same way. Without the ImGui backend (no WndProc + subclass) the feature stays inactive. +- An off-screen saved rect, a rect under 160x120 or a minimised/maximised/fullscreen-looking window is + ignored. `PanelStateStore.Flush` no longer claims to be a no-op when remembering is off (it is an + explicit save). +- Not taken: Vaulted gate, chat 0x1C, hot-reload hold, bar declutter. + +## Tests + +`tools/EngineSettingsTests`: defaults and engine.json round trip for the three settings, the +borderless decisions (setting off with no marker changes nothing; our marker restores; on strips once), +off-screen / size limits, per-client file names, the rect file. + +Not yet tested in game (windowed vs fullscreen, hot reload). diff --git a/Changelog/2026-10-18-engine-review-fixes.md b/Changelog/2026-10-18-engine-review-fixes.md new file mode 100644 index 0000000..f0fb3e2 --- /dev/null +++ b/Changelog/2026-10-18-engine-review-fixes.md @@ -0,0 +1,53 @@ +# Engine review fixes (crash log size, dump safety, transition gate valve, AutoId) + +RynthCore.SehTrampoline.dll native version 8 (previous: 7). Branch `fix/engine-review`, from +`integration/pr-fixes-2026-10-18`. Not deployed. + +## native-crash.log no longer grows without bound + +- Decal's handled null-ref AV (about once a minute, one address) was written on every hit: the 30 s + "relog" applied to noise too. About 1,440 entries a day, 5-6 KB each. Now a noise address repeats only + at powers of two (about 11 entries a day for that address). The 30 s relog and the always-write for + a non-AV code stay for genuine (AC-class) addresses, capped at `CLF_MAX_RELOGS` (16) per address. + What a cap skips is still in the flush ring, so a fatal hit is recovered at exit. +- A total byte budget per process (`CLF_MAX_LOG_BYTES`, 3 MB, counted from the file's size at install): + past it ordinary entries stop after one marker line. Fatal entries (last chance, crash-exit flush) + get 256 KB more. +- `native-crash.log` is one file for every client, so `LogPaths.RotateAtStartup` (per-PID) never + covered it. `LogPaths.RotateNativeCrashLogAtStartup` moves one over 1 MB to `native-crash.log.old` + on the first engine generation, before the native side opens it. +- Tests: `native/SehTrampoline/tests/Run-CrashLogFilterTests.ps1`. + +## Full-memory OUT OF MEMORY dump: disk check and a cap across clients + +`DumpBudget` (pure, tested): the volume must keep 2 GB free after the dump, and the full dumps already +in the folder (any client) are capped at 4 files / 14 GB. The check and an empty placeholder file are +made under one machine-wide mutex, so clients that hit the box together cannot all pass first. A refusal +prunes older dumps once and asks again, else writes the small dump. The small dump (also the hang dump) +needs 200 MB free. + +## Crash dump on TerminateProcess / NtTerminateProcess is back (bounded) + +7cbf69e removed the managed dump on a crash exit and relied on CoreCLR's `createdump`. Checked offline +with a small CoreCLR host: `createdump` does run for a native AV that unwinds through a managed frame +and for one that reaches the CLR's unhandled-exception filter. It does not run when AC's own handler +catches a native AV and answers with TerminateProcess (no CLR frame, no CLR filter), and nothing else +wrote a dump there. `ProcessExitHooks.DumpCrashOnce` writes one small dump on that path: after the +native log flush, on its own thread with a 20 s wait, once per process, not when `clr__*.dmp` +exists, newest 5 kept. + +## World-transition gate: safety valve and a setting + +A gate held continuously for 120 s (`WorldTransitionState.MaxHoldMs`) opens by itself: logged once +(`[Lifecycle] world-transition gate OPENED by its safety valve`), counted in the heartbeat as +`gateov=N`, closed again when the raw transition ends. engine.json `TransitionGate` (default true; +only a hand-set false is written) turns the gate off; it is read at client start. + +## AutoId + +- `AutoIdDrain`: when the 512-per-tick evaluation budget runs out with items left, the evaluated ones + move to the back, so the next tick starts where this one stopped. +- Identify data kept since a client release is dropped on re-create when the release was + `ReleasedObjectRetention.StaleAfterMs` (2 min) or more ago (the client sends no updates for a released + object). A short absence still keeps its data. The no-re-appraisal window after a release is + therefore effectively 2 min rather than 10 for data freshness; tune the constant if that is too eager. diff --git a/Changelog/2026-10-18-enl-calculator.md b/Changelog/2026-10-18-enl-calculator.md new file mode 100644 index 0000000..f25cc7f --- /dev/null +++ b/Changelog/2026-10-18-enl-calculator.md @@ -0,0 +1,65 @@ +# Skills > Progression: Enlightenment calculator + +Branch `feature/enl-calculator`, from `integration/pr-fixes-2026-10-18`. Not deployed, not released. +The idea and the first version are Silentkelpie's (rynth PR 6, "Skills Progression: Enl calculator UI"); +this takes only the calculator UI and its data, checked against the producer, with its failure modes +tightened. + +## What it shows + +On the Enlightenment section of the Progression tab, under the plan totals, an **Enl calculator** +collapsible (open by default), drawn from what RynthILT's `AppendEnlCalculatorJson` sends: + +- **Per-level table**: Enl, Item, Qty, Lum for each step of the plan. Green while the simulated stock still + covers that step, amber after. The first 12 steps show; "Show all N steps" lists up to 100 in a table + that scrolls on its own, so a long plan never stretches the panel. +- **Still need / have**: luminance and each material. +- **Sigil craft chain (301-325)**: the eight chain rows (craft rows tagged), with RynthILT's note. +- Two lines under "Coins per token": the e-coins needed, and the luminance to buy them. + +## Not changed + +- Which luminance figure the Augmentation rows and the planners use. RynthILT's calculator simulates with + its **banked** luminance (`Bank.Luminance`), not the character's; the footnote says "banked luminance" + because that is what the numbers are (the PR's own text said "character", which the producer does not do). +- Nothing else of the PR's commit: hot reload hold, bar declutter, Oracle embed, chat filters and the + changelog / version files are handled elsewhere. The "Plan to level" label and the "Totals to plan:" + heading from the PR are left as they were. + +## Absence and bad data + +- An older RynthILT / RynthAi, or a server without ILT, sends none of the fields: the arrays are empty, the + strings empty, and the section and the two e-coin lines are not drawn. +- The row arrays are read by tolerant converters (`UI/Data/EnlRowConverters.cs`). `null`, a non-array, a row + that is not an object, a missing or mistyped field, unknown extra fields: that row (or just that field) + falls back to its default and the rest of the snapshot parses. Before, any such `JsonException` would have + turned the whole Progression snapshot into "unavailable" and hidden the Augmentation planner too. Rows + are capped at 200 per array on parse; the table draws at most 100 level rows and 16 material / chain rows. +- `ProgressionSource.ParseJson` is the one parse (the poll uses it). + +## Width + +The tables are 16 less than the panel, with the label column stretching and the number columns fixed +(scaled down below the retail width of 300). Cell text wraps inside the cell instead of running off the +panel; the notes wrap at the panel's own wrap position, like the rest of the section. + +## Lifecycle + +No new subscription: the calculator draws the Progression snapshot the Skills face already subscribes to in +`ProgressionShown` / `ProgressionHidden`, so the `ShownLatch` show / hide balance of the embedded Skills face +is unchanged. Row text (level, count, chain numbers, the "(craft)" label) is formatted once per snapshot, +and the Show all button label only when its mode changes; nothing grows per frame. + +## Files + +- `UI/Data/ProgressionData.cs` (Enl calculator fields on `EnlPlanner`, `EnlLevelRow`, `EnlMaterialRow`, + `EnlChainRow`, `EnlCalculatorView` limits, `ProgressionSource.ParseJson`) +- `UI/Data/EnlRowConverters.cs` (new) +- `ImGui/Panels/SkillsFace.Progression.cs` +- Tests: `tools/EnlCalculatorTests` (new; the sample JSON follows `AppendEnlCalculatorJson`'s shape) + +## Not verified + +No live client and no live RynthILT data: how the tables render (column widths, wrapping at 300, the +scrolling table) and the real numbers were not seen in game. The parse is tested against a sample built from +the producer's code, not captured output. diff --git a/Changelog/2026-10-18-reload-hold-optin.md b/Changelog/2026-10-18-reload-hold-optin.md new file mode 100644 index 0000000..0c8bbfa --- /dev/null +++ b/Changelog/2026-10-18-reload-hold-optin.md @@ -0,0 +1,54 @@ +# Opt-in: hold engine reloads while in the world + +Branch `feature/reload-hold-optin`, from `status-export`. Not deployed, not released. No native +(`Loader.c`) change, so no loader version bump. + +SilentKelpie's PR 6 (his 2026.10.16.3 / .5 "hold hot reloads while in-world") as a setting that is +**off by default**, so a reload behaves exactly as before unless the player turns it on. + +## Why + +On his machine, stacked automatic hot reloads (the loader's file watcher, engine deploys) while logged +in were crashing clients: the loader shut the engine down, then the CoreCLR re-init failed mid-flight. +His fix held every reload, forever, until logout, and even a reload asked for by hand waited. That is +too blunt as a default, so it is opt-in, bounded, and leaves hand reloads alone. + +## What + +- `engine.json` `HoldReloadInWorld` (default `false`; only a `true` is written; missing, or anything + that is not a boolean, reads as `false`). Settings > Misc: "Hold reloads while in the world", with a + tooltip, directly under "Background Identify". +- On: an automatic engine reload waits, with the game still running on the old engine, until the player + logs out or reaches character select (`ReloadInWorldGate`, polled every 2 s, "still in the world" + logged every 30 s, one chat line). It runs in `RynthCoreShutdown` before the plugin (combat) deferral, + so old and new loaders behave the same. +- **Never forever.** `engine.json` `HoldReloadInWorldMaxMinutes` (default 10, valid 1-240; out of range + is clamped, a non-number reads as 10; only a non-default value is written; Settings > Misc "Give up + holding after (min)", shown while the hold is on). At the bound the hold logs once + (`held N min, reloading anyway`) and the reload goes ahead. +- **Hand reloads are never held.** ERl, the bar RL button, `/rc rl` and the hotkey set the existing + hand-reload mark; the gate now honours it (`ShouldHold(byHand, ...)`; his version ignored `byHand`). + A hand reload that arrives while an automatic one is being held ends the hold at the next poll and also + skips the plugin deferral, like any hand reload. Switching the setting off mid-wait also releases it. +- Fails open: a throwing query, setting read or gate counts as "do not hold". +- Off: none of this runs; no wait and no new log line. + +## Left out of the PR + +- `Loader.c` ReloadWatcher poll and `RynthCoreMayHotReload` export (loader 2.2): the wait is done in the + managed `Shutdown`, which the loader already calls on its reload thread (the same place the plugin + deferral waits), so the native poll is redundant. It would also have needed its own bound in C, which + could not be built or tested here. +- `RequestManualReload` and the reroute of ERl / bar RL / `/rc rl` / hotkey: hand reloads are not held now. +- The rest of that commit (inventory bar declutter, Oracle Skills embed, ...). + +## Files + +- `src/RynthCore.Engine/ReloadInWorldGate.cs` (new), `EntryPoint.cs` +- `Plugins/EngineSettings.cs` (keys, owned-keys list), `UI/Data/SettingsData.cs` (Settings > Misc rows) +- `tools/ReloadInWorldGateTests` (new, 44 checks), `tools/EngineSettingsTests` (round trip, clamp, defaults) + +## Not verified + +No live client: the actual deferral in a running world, the chat line, and the Settings rows were not +exercised in game. diff --git a/Changelog/2026-10-18-vaulted-dungeons-setting.md b/Changelog/2026-10-18-vaulted-dungeons-setting.md new file mode 100644 index 0000000..e104fb5 --- /dev/null +++ b/Changelog/2026-10-18-vaulted-dungeons-setting.md @@ -0,0 +1,38 @@ +# Settings > Navigation: Vaulted Dungeons master switch + +Branch `feature/vaulted-setting`, from `integration/pr-fixes-2026-10-18`. Not deployed, not released. +Pairs with RynthSuite `feature/vaulted-dungeons` (the keeper itself). + +From SilentKelpie's RynthCore PR 6 (commit 3), the Vaulted Dungeons row only. The Display chrome and +the chat 0x1C part of that commit are already merged. + +## What + +- Settings > Navigation, section "Infinite Leaftide": **Vaulted Dungeons**, off by default. It is the + master switch of RynthILT's Vaulted Dungeons keeper (Infinite Leaftide / ACECustom only): off, the + keeper does nothing (no recalls, no `/rc quit`, no Mini Remote tab, a saved On or Auto Start ignored); + turning it off while it runs stops it at once. +- The setting is **RynthAi's** (`EnableVaultedDungeons` in the RynthAi profile, per character). The + engine keeps no copy: `RynthAiSettings.EnableVaultedDungeons` in `UI/Data/SettingsData.cs` is only + the mirror of RynthAi's settings payload, like every other row. RynthILT reads the switch from RynthAi + (`RynthAi.Hub` `VaultedDungeonsEnabled`), so there is exactly one source of truth. +- The mirror is nullable, as the Nav panel's switches are: a RynthAi that predates the setting omits it, + the row stays hidden, and a save sends `null`, which RynthAi leaves alone (his version used a plain + `bool`, which would have written `false` over the switch). + +## Left out of the PR + +- The rest of that commit (already merged, or separate decisions): Variable Power and Hitting the + Environment rows, the changelog notes, the installer version files. + +## Files + +- `src/RynthCore.Engine/UI/Data/SettingsData.cs` +- `tools/VaultedSettingTests` (new, 22 checks): the mirror's JSON (absent, false, true, case), the + Navigation row (one, a checkbox, hidden until RynthAi sends the value, reads Off by default, edits + only that property, tooltip). It loads the built engine assembly and reaches the internal types by + reflection (`SettingsData.cs` has no standalone compile seam). + +## Not verified + +No live client: the row in the Settings window, and the keeper's reaction to the switch (RynthSuite side). diff --git a/Changelog/2026-10-19-sk-chat-settings.md b/Changelog/2026-10-19-sk-chat-settings.md new file mode 100644 index 0000000..879f30d --- /dev/null +++ b/Changelog/2026-10-19-sk-chat-settings.md @@ -0,0 +1,56 @@ +# Silentkelpie PR 6, commit 7: engine settings, chat, Modern vault, launcher picker + +Branch `feature/sk2-chat`, from `integration/pr-fixes-2026-10-18`. Not deployed, not released. + +From SilentKelpie's RynthCore PR 6 (commit 7, "port SK test branch (2026.10.18.24) onto sk"). That commit +is a squash against his base, so it was taken piece by piece and adapted; none of its hunks that roll back +our newer code were taken (plugin API comments, display chrome, DatFileShareHooks, InventoryTitleLayout, +bar restructure, Skills embed, updater floor, installer / launcher DXVK). + +## What + +- **engine.json saves only the keys this client changed.** Every client kept the whole settings in memory + and wrote them all back, so a client that never touched a setting put its stale value over another + client's change (a Display option set in one client came back in all of them). `Save(key)` records the + key and `EngineSettingsFile.Merge` takes only those from the engine; every other key keeps what the file + holds. A changed key back at its default is still left out (removed); a missing file still gets the whole + settings. Redone against our key set (TransitionGate, HoldReloadInWorld(+MaxMinutes), + RememberAcWindowPosition, AutoIdMode, ...); his BorderlessFillMonitor key is not here. +- **Map coordinates in chat are underlined links** (hover: hand and tooltip). Click points RynthNav's arrow + there, Ctrl+click walks there; a drag still selects and copies, right-click keeps the line menu. +- **Lines a chat filter hides stay out of AC's own chat window too.** The engine runs RynthChat's Hide rules + and ticked standard filters on a held line before its verdict (`ChatModel.ShouldHideInRetail`, + `ChatRetailVerdict`); a moved or copied line still prints in AC. Option under Standard filters, on by + default (`hideInRetail`). The plugin pump's incoming chat queue holds 4096 lines (was 256) and logs drops. +- **RynthChat re-reads `rynthchat_settings.json` when another client saved it** (`SharedFileWatch`, every + 2 s): rules, standard filters, tabs and display options follow, this client's own saves are skipped, its + selected tab is kept. +- **Modern Inventory has the Aelrynth Vault**: a chest button beside the Classic button, the vault in place + of the grid, caption, Refresh, right-click Withdraw. The header positions are now `InventoryHeaderLayout`; + the Vault takes its room first and is never dropped. +- **Launcher**: a Known server picker in the Server Profile dialog (17 servers) and the Launcher tab scroll + fix (the profile cards no longer push Updates and Launch Targets out of reach). + +## Left out + +- The low-memory safeguard (turn Adaptive degrade on after an early address-space shortage): it is a part + of his graphics profile code (AcGraphics, AcGraphicsPrefs, graphics.json, the launcher writing the + profile into UserPreferences.ini), which is not taken. +- In his chat/PluginManager hunks: the EngineStatusMetrics call, the MemoryUse.Mark removal, "v85" -> + "v81" comment edits and the ServerPlugins wording (rollbacks). +- His Classic title-bar "more" menu, and the DXVK toggle in the launcher. + +## Files + +- `src/RynthCore.Engine/Plugins/EngineSettings.cs`, `EngineSettingsFile.cs` +- `src/RynthCore.Engine/ImGui/Panels/ChatFace.cs`, `ChatFiltersFace.cs`, `InventoryFace.cs`, `InventoryFace.Classic.cs` +- `src/RynthCore.Engine/UI/Data/ChatCoords.cs`, `ChatData.cs`, `ChatSettingsDto.cs`, `ChatRetailVerdict.cs` (new), `SharedFileWatch.cs` (new) +- `src/RynthCore.Engine/UI/InventoryTitleLayout.cs`, `Plugins/PluginManager.cs` +- `src/RynthCore.App/KnownServerCatalog.cs` (new), `src/RynthCore.App.Avalonia/` (ServerProfileDialog, MainWindow, csproj) +- Tests: `tools/EngineSettingsTests`, `ChatCoordTests`, `ChatFilterTests`, `BarDeclutterTests`, `LauncherSettingsTests` + +## Not verified + +No live client: the underlined links and clicks, the retail-chat hide and the 4096 queue under a real burst, +the settings re-read between two running clients, the Modern vault button and grid (needs an Aelrynth +character), the launcher dialog and scroll. diff --git a/Changelog/2026-10-19-sk-loot-combat.md b/Changelog/2026-10-19-sk-loot-combat.md new file mode 100644 index 0000000..861d458 --- /dev/null +++ b/Changelog/2026-10-19-sk-loot-combat.md @@ -0,0 +1,53 @@ +# Add-to-loot attribute checklist, Variable Power, Hitting the Environment and Kite rows + +Branch `feature/sk2-loot-combat`, from `integration/pr-fixes-2026-10-18`. Not deployed, not released. +Pairs with RynthSuite `feature/sk2-loot-combat` (RynthAi's side of all of it). + +From SilentKelpie's RynthCore PR 6 (commit 7, and the Settings rows of commit 6), adapted. + +## What + +- **Add to loot profile, attribute checklist** (`ImGui/Panels/LootAddDialog.cs`, `UI/Data/LootEditData.cs`). + The popup lists every attribute the item has, grouped (Item, Weapon / Armor, Ratings, Spells, Pet + essence, T11, Requirements). Tick a row to require it, pick `>=`, `=`, `<=` (spells: or better / + exact / any tier) and type a value. The popup is wider with the list. "Items like this" pre-ticks what + it always required. + - Wire: the ask carries `Choices` (one per row the player changed, null until then) and the draft + carries `AttributesSupported` and `Attributes`. These are the DTO mirrors of RynthSuite's + `LootEditWire`. + - **Fallback:** a RynthAi without the checklist never sets `AttributesSupported`, so the popup keeps + its single "Include T11 attributes" box and nothing else changes. An older engine against the new + RynthAi never sends `Choices`, and RynthAi then builds exactly what it built before. +- **Settings > Melee Combat:** "Variable Power (monster rules)" (Variable Min % / Max %), "Hitting the + Environment" (Missile Response, Hits to trip, Window, Move closer by, Closest, Skip target) and + "Pull Away (Kite)" (Pull Distance, Tag Before Fleeing). **Settings > Spell Combat:** "Hitting the + Environment" (Magic Response). +- **Damage panel, a monster's detail:** a "Power" combo (Default, High, Reckless, Variable, + Reckless + Variable) and a "Kite" combo (Default, Off, PullAway). A new rule copied from the DEFAULT line + follows it; one copied from a name rule keeps that rule's choices. + +## Defaults + +Nothing changes until a player turns it on: every response is Off, every rule's Power and Kite are +Default (Default Power is the global Power settings, Default Kite on the DEFAULT line is Off). + +## Compatibility + +- The new RynthAi settings are **nullable mirrors** in `RynthAiSettings`, like the Vaulted Dungeons + switch: a RynthAi that predates them omits them, the rows (and their section headers) stay hidden, + and a save sends `null`, which RynthAi leaves alone. His version used plain ints and a bool, which + would have written the engine's defaults over a RynthAi that did not have them. +- `Combo` rows gained an optional `when:` like the other kinds (needed to hide Missile / Magic Response). +- An older RynthAi ignores the Rule's new `AttackPower` and `Kite` fields. + +## Not taken + +The rest of that commit: the ring run-away and its engine side are decided separately; the chat, display +and EngineSettings pieces are on other branches. + +## Tests + +- `tools/CombatSettingsTests` (new): the mirrors, the rows' visibility and ranges, the schema defaults, + the Power / Kite spellings and the rule's change detection. +- `tools/LootAddWireTests` (new): the popup's DTOs against what RynthAi's `LootEditWire` writes and + reads, and the older-RynthAi fallback. diff --git a/installer/Build-Installer.ps1 b/installer/Build-Installer.ps1 index da412fe..cbd1010 100644 --- a/installer/Build-Installer.ps1 +++ b/installer/Build-Installer.ps1 @@ -50,7 +50,13 @@ param( # Old opt-in switch, kept so existing command lines still work; the bridge is the default now. [switch]$IncludeDecalBridge, # Decal's install folder, when not the default C:\Program Files (x86)\Decal 3.0. - [string]$DecalDir = "" + [string]$DecalDir = "", + # Managed (collectible) plugins, built by Publish-Update.ps1 (engine API 88): the folder of the + # plugins' common dependencies, staged into Runtime\PluginShared, and the managed RynthAi DLL, + # used instead of the NativeAOT RynthAi build. NativeAOT plugins can never be unloaded, so each + # reload kept a copy of every one (220-450 MB of address space per reload, 2026-10-19). + [string]$PluginSharedDir = "", + [string]$RynthAiDll = "" ) $ErrorActionPreference = "Stop" @@ -126,11 +132,13 @@ if (-not $SkipBuild) { } # (Default: the CoreCLR engine and native loader are built straight into staging below.) - # ── 4. Plugin (NativeAOT) ───────────────────────────────────────────────── - Write-Host "" - Write-Host "[4/5] Publishing Plugin (NativeAOT)..." -ForegroundColor Cyan - dotnet publish $PluginProject -c $Configuration @VersionArgs - if ($LASTEXITCODE -ne 0) { throw "Plugin publish failed (exit $LASTEXITCODE)" } + # ── 4. Plugin (NativeAOT; a managed RynthAi from Publish-Update replaces it) ── + if (-not $RynthAiDll) { + Write-Host "" + Write-Host "[4/5] Publishing Plugin (NativeAOT)..." -ForegroundColor Cyan + dotnet publish $PluginProject -c $Configuration @VersionArgs + if ($LASTEXITCODE -ne 0) { throw "Plugin publish failed (exit $LASTEXITCODE)" } + } # ── 5. Loot Editor (self-contained Avalonia tool) ───────────────────────── Write-Host "" @@ -213,10 +221,18 @@ if ($NativeAot -and (Test-Path "$EnginePublish\Native")) { # Plugin DLL only — staged separately so the .iss file can install it to an # absolute path outside {app}. The engine no longer auto-scans Runtime\Plugins\; # the user explicitly adds the plugin path via the launcher's Plugins tab. -$pluginDll = "$PluginPublish\RynthCore.Plugin.RynthAi.dll" +$pluginDll = if ($RynthAiDll) { $RynthAiDll } else { "$PluginPublish\RynthCore.Plugin.RynthAi.dll" } if (-not (Test-Path $pluginDll)) { throw "Plugin DLL not found at: $pluginDll" } Copy-Item $pluginDll "$pluginStagingDir\RynthAi\" -Force +# The managed plugins' common dependencies (engine API 88: ManagedPlugins looks in Runtime\PluginShared). +if ($PluginSharedDir) { + if (-not (Test-Path $PluginSharedDir)) { throw "PluginShared folder not found at: $PluginSharedDir" } + New-Item -ItemType Directory -Path "$StagingDir\Runtime\PluginShared" -Force | Out-Null + Copy-Item "$PluginSharedDir\*" "$StagingDir\Runtime\PluginShared\" -Force + Write-Host " Runtime\PluginShared: $((Get-ChildItem "$StagingDir\Runtime\PluginShared" -File).Count) file(s)" +} + # Loot Editor (self-contained — copy everything from publish, drop pdbs) if (-not (Test-Path $LootEditorPublish)) { throw "Loot Editor publish not found at: $LootEditorPublish" } foreach ($file in (Get-ChildItem "$LootEditorPublish" -File)) { diff --git a/installer/Publish-Update.ps1 b/installer/Publish-Update.ps1 index 4c37329..c992e78 100644 --- a/installer/Publish-Update.ps1 +++ b/installer/Publish-Update.ps1 @@ -44,6 +44,7 @@ param( # (its id is a hash of every file); otherwise the live feed's entry is carried over. [string]$NavDataDir = "C:\Games\RynthCore\NavData", [switch]$SkipNavData, # leave navdata out of this feed (launchers then keep what they have) + [switch]$NativeAotPlugins, # the old NativeAOT plugin builds (each reload keeps a copy of every one) # The World Map's optional sizes (RynthNav.Baker --map-world): worldmap-hd.rmap, worldmap-ultra.rmap and worldmap-p32.rmap from this # folder are offered by the launcher as separate downloads ("mappacks" in the feed). Each is uploaded once under # mappacks// and kept by later releases. Without this folder the live feed's packs are @@ -127,8 +128,61 @@ $rel = Join-Path $ScriptDir "Releases\$release" if (Test-Path $rel) { Remove-Item $rel -Recurse -Force } New-Item -ItemType Directory -Force "$rel\plugins", "$rel\build" | Out-Null +# Plugins: built MANAGED by default (collectible: a reload frees them; NativeAOT plugins can never be +# unloaded, so every reload kept a copy of each one - 220-450 MB of address space per reload, +# 2026-10-19). Each managed plugin still ships as one DLL in the feed: their common dependencies +# (RynthCore.PluginSdk, PluginCore, ImGui.NET, MoonSharp, ...) go into the installer's +# Runtime\PluginShared, where the engine (API 88) finds them. The plugins declare minEngineApi 88, +# so an older engine refuses them instead of failing to load them. -NativeAotPlugins: the old builds. +$suitePlugins = "RynthChat", "RynthTracker", "RynthNav", "RynthVision", "RynthLua", "RynthOracle", "RynthInventory", "RynthSort", "RynthILT", "RynthThreads", "RynthNet" +# Server plugins (Plugins\Shared\ServerPack; SilentKelpie's): one per game server, each loaded by the +# engine only for its own server. They go in the feed only, so the launcher offers each one under +# Available plugins for the player to install; not in RynthSuite-Plugins.zip or the installer. +$serverPlugins = "RynthAChard", "RynthAelrynth", "RynthColdeve", "RynthConquest", "RynthDerptide", "RynthDreamWeave", "RynthEversong", + "RynthFrostACE", "RynthFrostcull", "RynthLeafDawn", "RynthLeafdawning", "RynthPortalStorm", "RynthReefcull", "RynthSundering", "RynthThistlecrown" +$managedArgs = if ($NativeAotPlugins) { @() } else { + @("-p:PublishAot=false", "-p:NativeLib=", "-p:SelfContained=false", "-p:RuntimeIdentifier=win-x86", + "-p:GenerateRuntimeConfigurationFiles=false", "-p:RynthPluginMinEngineApi=88") +} +function Build-Plugin([string]$name, [string]$label) { + Step "Building $name$label" + $proj = Join-Path $RynthSuiteRoot "Plugins\RynthCore.Plugin.$name\RynthCore.Plugin.$name.csproj" + # PublishDir overrides the projects' own (RynthNav/RynthVision publish into the live C:\Games folders). + dotnet publish $proj -c Release "-p:Version=$Version" "-p:PublishDir=$rel\build\$name\" @managedArgs -v q -nologo + if ($LASTEXITCODE -ne 0) { throw "dotnet publish failed for $name" } +} +foreach ($name in @("RynthAi") + $suitePlugins) { Build-Plugin $name "" } +foreach ($name in $serverPlugins) { Build-Plugin $name " (server plugin, feed only)" } + +$sharedDir = "" +if (-not $NativeAotPlugins) { + # Every plugin's dependencies, once each; the same name must be the same file in every plugin + # (they all build from this commit), else the release stops. + $sharedDir = "$rel\build\PluginShared" + New-Item -ItemType Directory -Force $sharedDir | Out-Null + $seen = @{} + foreach ($name in @("RynthAi") + $suitePlugins + $serverPlugins) { + foreach ($f in Get-ChildItem "$rel\build\$name\*.dll") { + if ($f.Name -like "RynthCore.Plugin.*.dll") { continue } + $hash = (Get-FileHash $f.FullName -Algorithm SHA256).Hash + if ($seen.ContainsKey($f.Name)) { + if ($seen[$f.Name] -ne $hash) { throw "PluginShared: $($f.Name) differs between plugins ($name) - not publishing." } + continue + } + $seen[$f.Name] = $hash + Copy-Item $f.FullName "$sharedDir\" + } + } + Write-Host " PluginShared: $($seen.Count) file(s): $(($seen.Keys | Sort-Object) -join ', ')" +} + Step "Building the installer ($Version)" -& (Join-Path $ScriptDir "Build-Installer.ps1") -Version $Version -RynthSuiteRoot $RynthSuiteRoot +$installerArgs = @{ Version = $Version; RynthSuiteRoot = $RynthSuiteRoot } +if (-not $NativeAotPlugins) { + $installerArgs.PluginSharedDir = $sharedDir + $installerArgs.RynthAiDll = "$rel\build\RynthAi\RynthCore.Plugin.RynthAi.dll" +} +& (Join-Path $ScriptDir "Build-Installer.ps1") @installerArgs if (-not $?) { throw "Build-Installer.ps1 failed" } # The Decal bridge ships in every release (experimental, opt-in per account): the installer # carries it, so a launcher that updates through this feed gets it as a fresh install does. @@ -138,27 +192,7 @@ if (-not (Test-Path $bridgeStaged)) { throw "The installer was built without the Write-Host " Decal bridge in the installer: $((Get-Item $bridgeStaged).VersionInfo.FileVersion)" Copy-Item (Join-Path $ScriptDir "Output\RynthCore-Setup.exe") "$rel\RynthCore-Setup.exe" Copy-Item (Join-Path $ScriptDir "staging\plugins\RynthAi\RynthCore.Plugin.RynthAi.dll") "$rel\plugins\" - -$suitePlugins = "RynthChat", "RynthTracker", "RynthNav", "RynthVision", "RynthLua", "RynthOracle", "RynthInventory", "RynthSort", "RynthILT", "RynthThreads", "RynthNet" -foreach ($name in $suitePlugins) { - Step "Building $name" - $proj = Join-Path $RynthSuiteRoot "Plugins\RynthCore.Plugin.$name\RynthCore.Plugin.$name.csproj" - # PublishDir overrides the projects' own (RynthNav/RynthVision publish into the live C:\Games folders). - dotnet publish $proj -c Release "-p:Version=$Version" "-p:PublishDir=$rel\build\$name\" -v q -nologo - if ($LASTEXITCODE -ne 0) { throw "dotnet publish failed for $name" } - Copy-Item "$rel\build\$name\RynthCore.Plugin.$name.dll" "$rel\plugins\" -} - -# Server plugins (Plugins\Shared\ServerPack; SilentKelpie's): one per game server, each loaded by the -# engine only for its own server. They go in the feed only, so the launcher offers each one under -# Available plugins for the player to install; not in RynthSuite-Plugins.zip or the installer. -$serverPlugins = "RynthAChard", "RynthAelrynth", "RynthColdeve", "RynthConquest", "RynthDerptide", "RynthDreamWeave", "RynthEversong", - "RynthFrostACE", "RynthFrostcull", "RynthLeafDawn", "RynthLeafdawning", "RynthPortalStorm", "RynthReefcull", "RynthSundering", "RynthThistlecrown" -foreach ($name in $serverPlugins) { - Step "Building $name (server plugin, feed only)" - $proj = Join-Path $RynthSuiteRoot "Plugins\RynthCore.Plugin.$name\RynthCore.Plugin.$name.csproj" - dotnet publish $proj -c Release "-p:Version=$Version" "-p:PublishDir=$rel\build\$name\" -v q -nologo - if ($LASTEXITCODE -ne 0) { throw "dotnet publish failed for $name" } +foreach ($name in $suitePlugins + $serverPlugins) { Copy-Item "$rel\build\$name\RynthCore.Plugin.$name.dll" "$rel\plugins\" } diff --git a/native/SehTrampoline/CrashLogFilter.h b/native/SehTrampoline/CrashLogFilter.h index 03014f0..2a4cfff 100644 --- a/native/SehTrampoline/CrashLogFilter.h +++ b/native/SehTrampoline/CrashLogFilter.h @@ -17,10 +17,20 @@ * heap corruption. * - Each faulting address has a slot with its hit count and the time it was last * written. The first sighting is written. A repeat is written again (with its count) - * when the count is a power of two, when 30 s have passed since that address was - * last written, or when the code is not an AV. So a contained AV that later recurs - * as the fatal one is not swallowed as "seen before": a fatal fault is usually a - * terminate from some handler, and then no last-chance filter ever runs. + * when the count is a power of two (any class), or, for an AC-class address only, + * when 30 s have passed since it was last written, or when the code is not an AV. + * So a contained AV that later recurs as the fatal one is not swallowed as "seen + * before": a fatal fault is usually a terminate from some handler, and then no + * last-chance filter ever runs. + * Review fix (2026-10-18): the 30 s relog used to apply to noise too, so Decal's + * handled null-ref AV (about once a minute, one address) was written on EVERY hit: + * ~1,440 entries (~5-6 KB each with the stack sweep) per day per client. Noise now + * repeats only at powers of two (about 11 entries a day for that address), and the + * 30 s / non-AV relogs are capped per address (CLF_MAX_RELOGS); what a cap or the + * dedupe skips is still in the flush ring, so a fatal hit is recovered at exit. + * - A total byte budget (CLF_MAX_LOG_BYTES, counted from the file's size at install plus + * what this process writes): past it ordinary entries are dropped after ONE marker + * line; fatal entries (last-chance, crash-exit flush) get CLF_LOG_RESERVE_BYTES more. * - Noise is classified, written once per address like the rest, and never charged to * the AC limit: * .NET Framework (Decal plugins): faulting module clr.dll, mscorwks.dll, mscorlib; @@ -50,6 +60,9 @@ #define CLF_MAX_LAST_CHANCE 8 #define CLF_ADDR_SLOTS 128 #define CLF_RELOG_MS 30000u +#define CLF_MAX_RELOGS 16 /* non-power-of-two rewrites per address */ +#define CLF_MAX_LOG_BYTES (3u * 1024u * 1024u) /* ordinary entries stop here */ +#define CLF_LOG_RESERVE_BYTES (256u * 1024u) /* extra room for fatal entries */ #define CLF_CODE_ACCESS_VIOLATION 0xC0000005u #define CLF_CODE_FAIL_FAST 0xC0000602u @@ -80,6 +93,7 @@ typedef struct { unsigned int lastWriteMs; unsigned char cls; /* clf_class */ unsigned char used; + unsigned char relogs; /* writes that were not first / power-of-two (time, non-AV) */ } clf_slot; typedef struct { @@ -90,6 +104,10 @@ typedef struct { unsigned int otherRepeats; /* other repeats not written */ unsigned int overCap; /* not written: limit reached */ unsigned int untracked; /* AC addresses written but not tracked (table full of AC) */ + unsigned int relogCapped; /* relogs skipped: the address used its CLF_MAX_RELOGS */ + unsigned int logBytes; /* bytes in the log file: size at install + written since */ + unsigned int byteDenied; /* entries dropped by the byte budget */ + unsigned char capMarked; /* the budget marker line has been written */ } clf_state; static int clf_is_logged_code(unsigned int code) @@ -152,10 +170,22 @@ static clf_decision clf_repeat(clf_state* s, clf_slot* slot, unsigned int code, { slot->hits++; if (hits) *hits = slot->hits; - if (clf_is_pow2(slot->hits) || nowMs - slot->lastWriteMs >= CLF_RELOG_MS || code != CLF_CODE_ACCESS_VIOLATION) { + if (clf_is_pow2(slot->hits)) { slot->lastWriteMs = nowMs; return CLF_LOG_REPEAT; } + /* The 30 s relog is for genuine (AC-class) faults only: noise at one address (Decal's + * handled null-ref, about once a minute) would otherwise be written on every hit. A + * non-AV code is always written, within the per-address cap. */ + if ((slot->cls == CLF_CLASS_AC && nowMs - slot->lastWriteMs >= CLF_RELOG_MS) + || code != CLF_CODE_ACCESS_VIOLATION) { + if (slot->relogs < CLF_MAX_RELOGS) { + slot->relogs++; + slot->lastWriteMs = nowMs; + return CLF_LOG_REPEAT; + } + s->relogCapped++; + } if (slot->cls != CLF_CLASS_AC) s->noiseRepeats++; else s->otherRepeats++; return CLF_SKIP_REPEAT; } @@ -189,6 +219,7 @@ static clf_decision clf_new(clf_state* s, unsigned int code, unsigned int addr, slot->hits = 1; slot->lastWriteMs = nowMs; slot->cls = (unsigned char)cls; + slot->relogs = 0; slot->used = 1; } else { s->untracked++; @@ -266,6 +297,26 @@ static int clf_ring_take(clf_ring* g, clf_rec* out, unsigned int* older) return n; } +typedef enum { + CLF_BYTES_OK = 0, /* write the entry */ + CLF_BYTES_MARK, /* over the budget: write the one marker line, then no entry */ + CLF_BYTES_DENY, /* over the budget: write nothing */ +} clf_bytes; + +/* + * The byte budget, asked before each entry. fatal: a last-chance / crash-exit entry, + * which may use CLF_LOG_RESERVE_BYTES beyond CLF_MAX_LOG_BYTES. The caller adds what it + * writes to s->logBytes (the marker included). + */ +static clf_bytes clf_bytes_gate(clf_state* s, int fatal) +{ + unsigned int limit = CLF_MAX_LOG_BYTES + (fatal ? CLF_LOG_RESERVE_BYTES : 0u); + if (s->logBytes < limit) return CLF_BYTES_OK; + s->byteDenied++; + if (!fatal && !s->capMarked) { s->capMarked = 1; return CLF_BYTES_MARK; } + return CLF_BYTES_DENY; +} + /* The last-chance (unhandled) filter. Any code: whatever reaches it is fatal. */ static clf_decision clf_last_chance(clf_state* s) { diff --git a/native/SehTrampoline/SehTrampoline.c b/native/SehTrampoline/SehTrampoline.c index 03656a9..f31a04e 100644 --- a/native/SehTrampoline/SehTrampoline.c +++ b/native/SehTrampoline/SehTrampoline.c @@ -27,7 +27,9 @@ #include /* File version of this native module (bump with every behavioural change). */ -#define RC_SEH_TRAMPOLINE_VERSION 7 /* v7: stack sweeps bounded by this thread's stack (TEB), never +#define RC_SEH_TRAMPOLINE_VERSION 8 /* v8: noise repeats only at powers of two, capped relogs per address, + a total byte budget for native-crash.log (CrashLogFilter.h); + v7: stack sweeps bounded by this thread's stack (TEB), never reading at or past StackBase; v6: AwfulWaffle's crash logger (per-address dedupe, pid/date, flush ring, RC_FlushCrashLog, module cache) merged with v3-v5; @@ -546,7 +548,21 @@ static clf_class cl_first_frame_class(unsigned int esp) static void cl_write(const char* p, DWORD n) { DWORD wr; - if (g_logHandle != INVALID_HANDLE_VALUE) WriteFile(g_logHandle, p, n, &wr, NULL); + if (g_logHandle != INVALID_HANDLE_VALUE && WriteFile(g_logHandle, p, n, &wr, NULL)) + g_filter.logBytes += wr; /* under g_logOwner, like every writer */ +} + +/* The byte budget (CrashLogFilter.h). Under the lock, before an entry. Returns 1 when the + * entry may be written. The first refusal of an ordinary entry writes one marker line. */ +static int cl_budget(int fatal) +{ + clf_bytes b = clf_bytes_gate(&g_filter, fatal); + if (b == CLF_BYTES_MARK) { + const char* m = "\r\n==== NATIVE CRASH LOGGER: log size budget reached, further ordinary entries are dropped " + "(fatal entries still get a reserve; restart the client or trim the file to resume) ====\r\n"; + cl_write(m, (DWORD)lstrlenA(m)); + } + return b == CLF_BYTES_OK; } /* Append " pid=N tid=N date=YYYY-MM-DD time=HH:MM:SS" (local time). */ @@ -569,7 +585,7 @@ static char* cl_stamp(char* p) return p; } -static void cl_write_entry(PEXCEPTION_POINTERS ep, const char* kind, unsigned int hits) +static void cl_write_entry(PEXCEPTION_POINTERS ep, const char* kind, unsigned int hits, int fatal) { char* p = g_buf; CONTEXT* c = ep->ContextRecord; @@ -577,6 +593,7 @@ static void cl_write_entry(PEXCEPTION_POINTERS ep, const char* kind, unsigned in unsigned int exAddr = (unsigned int)(UINT_PTR)ep->ExceptionRecord->ExceptionAddress; unsigned int words; if (g_logHandle == INVALID_HANDLE_VALUE) return; + if (!cl_budget(fatal)) return; p = cl_str(p, "\r\n==== NATIVE CRASH LOGGER ("); p = cl_str(p, kind); @@ -604,6 +621,10 @@ static void cl_write_entry(PEXCEPTION_POINTERS ep, const char* kind, unsigned in p = cl_u(p, g_filter.otherRepeats); p = cl_str(p, " overCap="); p = cl_u(p, g_filter.overCap); + p = cl_str(p, " relogCapped="); + p = cl_u(p, g_filter.relogCapped); + p = cl_str(p, " logBytes="); + p = cl_u(p, g_filter.logBytes); p = cl_str(p, "\r\n eip="); p = cl_sym(p, c->Eip, 1); p = cl_str(p, " esp="); p = cl_hex(p, c->Esp); p = cl_str(p, " ebp="); p = cl_hex(p, c->Ebp); @@ -670,6 +691,7 @@ static void cl_flush_locked(const char* reason, unsigned int code, unsigned int n = k; } if (n == 0 || g_logHandle == INVALID_HANDLE_VALUE) return; + if (!cl_budget(maxAgeMs == 0)) return; /* last chance / crash exit are fatal: they get the reserve */ p = g_buf; p = cl_str(p, "\r\n==== NATIVE CRASH LOGGER (flush: "); p = cl_str(p, reason); @@ -731,7 +753,7 @@ static LONG CALLBACK CrashVeh(PEXCEPTION_POINTERS ep) if (slot) { /* A repeat: decided without touching any module. */ if (clf_repeat(&g_filter, slot, code, now, &hits) == CLF_LOG_REPEAT) { - cl_write_entry(ep, slot->cls != CLF_CLASS_AC ? "first-chance, repeat, noise" : "first-chance, repeat", hits); + cl_write_entry(ep, slot->cls != CLF_CLASS_AC ? "first-chance, repeat, noise" : "first-chance, repeat", hits, 0); written = 1; } } else { @@ -742,11 +764,11 @@ static LONG CALLBACK CrashVeh(PEXCEPTION_POINTERS ep) leaf == NULL && code == CLF_CODE_ACCESS_VIOLATION ? cl_first_frame_class(ep->ContextRecord->Esp) : CLF_CLASS_AC); clf_decision d = clf_new(&g_filter, code, exAddr, cls, now); if (d == CLF_LOG_COUNTED) - cl_write_entry(ep, "first-chance", 1); + cl_write_entry(ep, "first-chance", 1, 0); else if (d == CLF_LOG_NOISE) cl_write_entry(ep, cls == CLF_CLASS_NETFX ? "first-chance, .NET Framework noise, not counted" - : "first-chance, managed (CoreCLR) noise, not counted", 1); + : "first-chance, managed (CoreCLR) noise, not counted", 1, 0); written = d == CLF_LOG_COUNTED || d == CLF_LOG_NOISE; } /* Kept for a flush (memory only): the fatal hit is often one not written here. */ @@ -766,7 +788,7 @@ static LONG WINAPI CrashLastChance(PEXCEPTION_POINTERS ep) if (cl_lock()) { cl_flush_locked("last chance", ep->ExceptionRecord->ExceptionCode, 0); if (clf_last_chance(&g_filter) == CLF_LOG_LAST_CHANCE) - cl_write_entry(ep, "LAST-CHANCE, unhandled", 1); + cl_write_entry(ep, "LAST-CHANCE, unhandled", 1, 1); cl_unlock(); } if (g_prevFilter && g_prevFilter != CrashLastChance) { @@ -830,6 +852,9 @@ RC_InstallCrashLogger(const wchar_t* logPath) FILE_ATTRIBUTE_NORMAL, NULL); if (h != INVALID_HANDLE_VALUE) { HANDLE old = g_logHandle; + DWORD size = GetFileSize(h, NULL); /* the budget counts what is already there */ + g_filter.logBytes = size == INVALID_FILE_SIZE ? 0u : (unsigned int)size; + g_filter.capMarked = 0; g_logHandle = h; if (old != INVALID_HANDLE_VALUE) { CloseHandle(old); } } @@ -949,7 +974,7 @@ static int gt_filter(PEXCEPTION_POINTERS ep, GT_FAULT* f) f->module[k] = 0; } if (InterlockedIncrement(&g_gameTickRecords) <= CL_MAX_GAMETICK) { - cl_write_entry(ep, "AV CAUGHT IN GAME TICK (Client::UseTime guard; tick dropped, client kept running)", 1); + cl_write_entry(ep, "AV CAUGHT IN GAME TICK (Client::UseTime guard; tick dropped, client kept running)", 1, 0); } cl_unlock(); if (leaf && f->module && f->module[0]) { diff --git a/native/SehTrampoline/tests/CrashLogFilterTests.c b/native/SehTrampoline/tests/CrashLogFilterTests.c index 5c1469c..45675a8 100644 --- a/native/SehTrampoline/tests/CrashLogFilterTests.c +++ b/native/SehTrampoline/tests/CrashLogFilterTests.c @@ -222,8 +222,87 @@ static void ring_order_overflow_and_written(void) check(got == 1 && out[0].addr == 0x9999 && older == 0, "after a flush, only what came since"); } +/* Review fix: Decal's handled null-ref AV at one JIT-code address about once a minute was + * written on EVERY hit (the 30 s relog applied to noise). A day of it: 1,440 hits. */ +static void noise_once_a_minute_is_not_written_every_hit(void) +{ + static clf_state s; + unsigned int hits, i, written = 0, now = 100000u; + for (i = 0; i < 1440; i++, now += 60000u) + if (is_write(FC(&s, AV, 0x433620C8u, CLF_CLASS_NETFX, now))) written++; + /* first + powers of two 2..1024 = 1 + 10 */ + check(written == 11, "1,440 once-a-minute hits of one noise address: 11 entries, not 1,440"); + check(s.counted == 0, "and none charged to the limit"); + check(s.noiseRepeats == 1440 - 11, "skipped noise repeats are counted"); + { + static clf_state m; + written = 0; + for (i = 0; i < 1440; i++) if (is_write(FC(&m, AV, 0x70001000u, CLF_CLASS_MANAGED, 5000u + i * 60000u))) written++; + check(written == 11, "managed noise is the same"); + } +} + +/* A genuine (AC) address keeps its 30 s relog, but only CLF_MAX_RELOGS times. */ +static void ac_relog_is_capped_per_address(void) +{ + static clf_state s; + unsigned int hits, i, written = 0, now = 1000u; + check(FC(&s, AV, 0x00416C86u, CLF_CLASS_AC, now) == CLF_LOG_COUNTED, "first sighting written"); + for (i = 2; i <= 1500; i++) { + now += 31000u; + if (is_write(FC(&s, AV, 0x00416C86u, CLF_CLASS_AC, now))) written++; + } + { + unsigned int pow2 = 0, v; + for (v = 2; v <= 1500; v <<= 1) pow2++; /* 2..1024 = 10 */ + check(written == pow2 + CLF_MAX_RELOGS, "1,500 hits 31 s apart: the power-of-two ones + CLF_MAX_RELOGS time relogs"); + } + check(s.relogCapped > 0, "the skipped relogs are counted"); + check(clf_find(&s, 0x00416C86u)->relogs == CLF_MAX_RELOGS, "the slot used its relog budget"); +} + +/* A non-AV code at a known address is written, within the same per-address cap. */ +static void non_av_relog_is_capped(void) +{ + static clf_state s; + unsigned int hits, i, written = 0; + FC(&s, AV, 0x00500000u, CLF_CLASS_AC, 100); + for (i = 0; i < 200; i++) + if (is_write(FC(&s, CLF_CODE_HEAP_CORRUPTION, 0x00500000u, CLF_CLASS_AC, 200 + i))) written++; + /* hits 2..201: powers of two 2,4,..,128 = 7, plus the capped relogs */ + check(written == 7 + CLF_MAX_RELOGS, "non-AV repeats: powers of two + CLF_MAX_RELOGS, not every hit"); +} + +/* The byte budget: ordinary entries stop after one marker; fatal ones get a reserve. */ +static void byte_budget(void) +{ + static clf_state s; + int i; + check(clf_bytes_gate(&s, 0) == CLF_BYTES_OK, "an empty log accepts an entry"); + s.logBytes = CLF_MAX_LOG_BYTES - 1; + check(clf_bytes_gate(&s, 0) == CLF_BYTES_OK, "one byte under the budget still accepts"); + s.logBytes = CLF_MAX_LOG_BYTES; + check(clf_bytes_gate(&s, 0) == CLF_BYTES_MARK, "at the budget: the marker, once"); + for (i = 0; i < 5; i++) + check(clf_bytes_gate(&s, 0) == CLF_BYTES_DENY, "then ordinary entries are dropped"); + check(s.byteDenied == 6, "and counted"); + check(clf_bytes_gate(&s, 1) == CLF_BYTES_OK, "a fatal entry still fits in the reserve"); + s.logBytes = CLF_MAX_LOG_BYTES + CLF_LOG_RESERVE_BYTES; + check(clf_bytes_gate(&s, 1) == CLF_BYTES_DENY, "and not past the reserve"); + { + static clf_state t; /* a log that starts over the budget (shared file already big) */ + t.logBytes = CLF_MAX_LOG_BYTES + 10; + check(clf_bytes_gate(&t, 1) == CLF_BYTES_OK, "a fatal entry fits in the reserve of a log that opened over budget"); + check(clf_bytes_gate(&t, 0) == CLF_BYTES_MARK, "its first ordinary entry gets the marker"); + } +} + int main(void) { + noise_once_a_minute_is_not_written_every_hit(); + ac_relog_is_capped_per_address(); + non_av_relog_is_capped(); + byte_budget(); fatal_repeat_recovered_by_flush(5); fatal_repeat_recovered_by_flush(100); fatal_repeat_recovered_by_flush(1000); diff --git a/src/RynthCore.App.Avalonia/MainWindow.axaml b/src/RynthCore.App.Avalonia/MainWindow.axaml index 199cc65..957e376 100644 --- a/src/RynthCore.App.Avalonia/MainWindow.axaml +++ b/src/RynthCore.App.Avalonia/MainWindow.axaml @@ -110,7 +110,11 @@ - + + + - + - + await CheckForUpdatesAsync(); _updateTimer.Start(); _ = CheckForUpdatesAsync(); + // Keep Updates + Launch Targets reachable: a bad * row under this scroll used to + // leave Offset stuck with those cards clipped above the viewport. + MainTabs.SelectionChanged += (_, _) => + { + if (MainTabs.SelectedIndex == 0) + ResetLauncherScrollToTop(); + }; Opened += async (_, _) => { + ResetLauncherScrollToTop(); await AskAboutUsageStatsOnceAsync(); await CleanUpDecalBridgeIfUnusedAsync(atStartup: true); await CheckFolderAccessAtStartupAsync(); // MainWindow.FolderAccess.cs: can the game client save? }; } + /// + /// Scroll the Launcher tab back to the top so Updates and Launch Targets stay reachable. + /// + private void ResetLauncherScrollToTop() + { + try { LauncherScroll.Offset = new global::Avalonia.Vector(0, 0); } + catch { /* designer / pre-init */ } + } + private void WireEvents() { AddServerButton.Click += async (_, _) => await AddServerAsync(); diff --git a/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj b/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj index bdbee8b..b39cf67 100644 --- a/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj +++ b/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj @@ -43,6 +43,7 @@ + diff --git a/src/RynthCore.App.Avalonia/ServerProfileDialog.axaml b/src/RynthCore.App.Avalonia/ServerProfileDialog.axaml index 32b2b1a..2eb9d24 100644 --- a/src/RynthCore.App.Avalonia/ServerProfileDialog.axaml +++ b/src/RynthCore.App.Avalonia/ServerProfileDialog.axaml @@ -1,14 +1,17 @@ + + + diff --git a/src/RynthCore.App.Avalonia/ServerProfileDialog.axaml.cs b/src/RynthCore.App.Avalonia/ServerProfileDialog.axaml.cs index 4ba6f24..e873a72 100644 --- a/src/RynthCore.App.Avalonia/ServerProfileDialog.axaml.cs +++ b/src/RynthCore.App.Avalonia/ServerProfileDialog.axaml.cs @@ -1,12 +1,20 @@ using System; +using System.Collections.Generic; using Avalonia.Controls; +using RynthCore.App; namespace RynthCore.App.Avalonia; internal partial class ServerProfileDialog : Window { + /// The picker's first entry: keep whatever is typed in the fields. + private const string CustomServerLabel = "Custom server (fill in the fields below)"; + private readonly RynthCore.App.LaunchServerProfile _profile; + /// True while the constructor selects the profile's known server, so it isn't re-applied. + private bool _loading; + public ServerProfileDialog(RynthCore.App.LaunchServerProfile profile) { _profile = profile; @@ -20,10 +28,47 @@ internal partial class ServerProfileDialog : Window EmulatorBox.SelectedItem = profile.Emulator.ToString(); RodatCheck.IsChecked = profile.RodatEnabled; + var choices = new List { CustomServerLabel }; + choices.AddRange(KnownServerCatalog.All); + KnownServerBox.ItemsSource = choices; + KnownServerBox.SelectionChanged += (_, _) => OnKnownServerChanged(); + + _loading = true; + KnownServer? current = KnownServerCatalog.FindByHost(profile.Host); + KnownServerBox.SelectedItem = current != null ? current : CustomServerLabel; + _loading = false; + ShowKnownServerNote(current); + SaveButton.Click += (_, _) => SaveAndClose(); CancelButton.Click += (_, _) => Close(false); } + /// + /// Picking a known server fills Name, Host, Port and Emulator from the catalog; Alias and + /// Rodat stay as typed. Picking "Custom server" leaves the fields alone. + /// + private void OnKnownServerChanged() + { + KnownServer? server = KnownServerBox.SelectedItem as KnownServer; + ShowKnownServerNote(server); + if (_loading || server == null) + return; + + NameBox.Text = server.Name; + HostBox.Text = server.Host; + PortBox.Text = server.Port.ToString(); + EmulatorBox.SelectedItem = server.Emulator.ToString(); + ValidationText.Text = string.Empty; + } + + /// The picked server's description and the RynthSuite plugin RynthCore loads for it. + private void ShowKnownServerNote(KnownServer? server) + { + KnownServerNote.Text = server == null + ? "Any server works. Known servers fill in the connection details; each has a RynthSuite server plugin name." + : $"{server.Note} Server plugin: {server.PluginName} (RynthCore loads it when you connect to {server.Host}, if it is installed)."; + } + private void SaveAndClose() { if (string.IsNullOrWhiteSpace(NameBox.Text)) diff --git a/src/RynthCore.App/KnownServerCatalog.cs b/src/RynthCore.App/KnownServerCatalog.cs new file mode 100644 index 0000000..271268f --- /dev/null +++ b/src/RynthCore.App/KnownServerCatalog.cs @@ -0,0 +1,160 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace RynthCore.App; + +/// +/// One server RynthSuite ships a server plugin for: where to connect, and which plugin +/// (C:\Games\RynthSuite\<PluginName>\) RynthCore loads for it. +/// +/// The plugin's manifest server id (lower-case, "a-z0-9-"). +/// The server's name, used as the profile's Server Name. +/// The host the launcher connects to (the client's -h). +/// The login port. +/// The server software. +/// "PvE" or "PvP", as the server lists itself. +/// The RynthSuite server plugin for this server. +/// One line about the server, shown under the picker. +internal sealed record KnownServer( + string Id, + string Name, + string Host, + int Port, + AcEmulatorKind Emulator, + string Ruleset, + string PluginName, + string Note) +{ + /// "host:port", as the server list shows it. + public string Address => $"{Host}:{Port}"; + + /// The picker's line for this server. + public override string ToString() => $"{Name} - {Address} ({Ruleset})"; +} + +/// +/// The servers RynthSuite has a server plugin for, so an account can be set up on one by picking +/// it. Hosts, ports and emulators come from the public server list +/// (github.com/acresources/serverslist, Servers.xml, checked 2026-10-13); Aelrynth is not on +/// that list and uses aelrynth.com:9020. A PluginName is the server plugin's folder under +/// C:\Games\RynthSuite when one is installed; the picker works the same without it. A Host +/// should stay inside that plugin's manifest "server" hosts, or RynthCore's server gate won't +/// pick the plugin for it. +/// +internal static class KnownServerCatalog +{ + /// Every known server, in the order the picker lists them (by name). + public static IReadOnlyList All { get; } = new[] + { + new KnownServer("achard", "AChard", "a-chard.ddns.net", 9000, AcEmulatorKind.Ace, "PvP", "RynthAChard", + "End-of-retail PvP server with custom PK content and kill rankings."), + new KnownServer("aelrynth", "Aelrynth", "aelrynth.com", 9020, AcEmulatorKind.Ace, "PvE", "RynthAelrynth", + "Aelrynth (aelrynth.com), an ACE server with its own mods."), + new KnownServer("coldeve", "Coldeve", "play.coldeve.ac", 9000, AcEmulatorKind.Ace, "PvE", "RynthColdeve", + "PvE server evolving toward an end-of-retail experience."), + new KnownServer("conquest", "Conquest", "acconquest.ddns.net", 9000, AcEmulatorKind.Ace, "PvE", "RynthConquest", + "Custom PvE server with live events, deep crafting and a PK system."), + new KnownServer("derptide", "Derptide", "ac.derptide.net", 9000, AcEmulatorKind.Ace, "PvE", "RynthDerptide", + "End-of-retail server with custom content, upgraded quest weapons and live events."), + new KnownServer("dreamweave", "DreamWeave", "play.acdreamweave.com", 9000, AcEmulatorKind.Ace, "PvE", "RynthDreamWeave", + "Lore-driven PvE server: new class abilities, new crafting, an up-to-date wiki."), + new KnownServer("eversong", "Eversong", "eversong.abrdns.com", 9000, AcEmulatorKind.Ace, "PvE", "RynthEversong", + "Five difficulty worlds, enlightenment, banking and lockboxes, invasions."), + new KnownServer("frostace", "FrostACE", "172.111.230.127", 9000, AcEmulatorKind.Ace, "PvE", "RynthFrostACE", + "New accounts include level 275 starter characters; retail restoration supported."), + new KnownServer("frostcull", "Frostcull", "frostcull.ddns.net", 9000, AcEmulatorKind.Ace, "PvE", "RynthFrostcull", + "No level or attribute cap, 10x XP and luminance, 25x drop rate."), + new KnownServer("ilt", "Infinite Leaftide", "game.infiniteleaftide.online", 9000, AcEmulatorKind.Ace, "PvE", "RynthILT", + "Infinite levels and enlightenment, custom content, constant development."), + new KnownServer("leafdawn", "LeafDawn", "leafdawn.hopto.org", 9000, AcEmulatorKind.Ace, "PvE", "RynthLeafDawn", + "End-of-retail PvE server with some custom content."), + new KnownServer("leafdawning", "Leafdawning", "leafdawning.duckdns.org", 9000, AcEmulatorKind.Ace, "PvE", "RynthLeafdawning", + "No-frills end-of-retail PvE server. Enforced 3 account limit."), + new KnownServer("levistras", "Levistras", "levistras.acportalstorm.com", 9000, AcEmulatorKind.Ace, "PvE", "RynthLevistras", + "Botting-free PvE server (automation is not allowed). 2 account limit."), + new KnownServer("portalstorm", "PortalStorm", "ac.portalstorm.us.com", 9020, AcEmulatorKind.Ace, "PvE", "RynthPortalStorm", + "15 tiers, 10 enlightenments, infinite luminance augmentations, custom skills."), + new KnownServer("reefcull", "Reefcull", "reefcull.gdleac.com", 9000, AcEmulatorKind.Gdle, "PvE", "RynthReefcull", + "GDLE PvE server that mimics end-of-game retail."), + new KnownServer("sundering", "Sundering", "ace.sunderingac.com", 9000, AcEmulatorKind.Ace, "PvE", "RynthSundering", + "End-of-retail feel with convenience changes. 3 active character limit."), + new KnownServer("thistlecrown", "Thistlecrown", "thistlecrown.ddns.net", 9000, AcEmulatorKind.Ace, "PvE", "RynthThistlecrown", + "Recreation of Thistledown. 3 account limit."), + }; + + /// The known server with this id (case-insensitive), or null. + public static KnownServer? FindById(string? id) + { + if (string.IsNullOrWhiteSpace(id)) + return null; + string wanted = id.Trim(); + return All.FirstOrDefault(s => string.Equals(s.Id, wanted, StringComparison.OrdinalIgnoreCase)); + } + + /// + /// The known server a saved profile points at, by host: the same host, or one under the known + /// host's parent domain ("infiniteleaftide.online" also finds ILT). An IP matches only itself. + /// Null when the host is empty or not a known server. + /// + public static KnownServer? FindByHost(string? host) + { + if (string.IsNullOrWhiteSpace(host)) + return null; + string h = host.Trim().TrimEnd('.'); + foreach (KnownServer s in All) + { + if (string.Equals(h, s.Host, StringComparison.OrdinalIgnoreCase)) + return s; + } + foreach (KnownServer s in All) + { + string domain = ParentDomain(s.Host); + if (domain.Length == 0) + continue; + if (string.Equals(h, domain, StringComparison.OrdinalIgnoreCase) || + h.EndsWith("." + domain, StringComparison.OrdinalIgnoreCase)) + return s; + } + return null; + } + + /// + /// Fills a profile's connection fields from a known server: Name, Host, Port and Emulator. + /// Id, Alias and RodatEnabled are the user's and are left alone. + /// + public static void ApplyTo(KnownServer server, LaunchServerProfile profile) + { + ArgumentNullException.ThrowIfNull(server); + ArgumentNullException.ThrowIfNull(profile); + profile.Name = server.Name; + profile.Host = server.Host; + profile.Port = server.Port; + profile.Emulator = server.Emulator; + } + + /// + /// The domain a host sits under, for matching a typed host to a known one: + /// "game.infiniteleaftide.online" gives "infiniteleaftide.online". Hosts on shared dynamic-DNS + /// domains (ddns.net, duckdns.org, ...) and IPs give "" so they match only themselves. + /// + private static string ParentDomain(string host) + { + if (System.Net.IPAddress.TryParse(host, out _)) + return ""; + string[] labels = host.Split('.'); + if (labels.Length < 3) + return host; + string parent = string.Join('.', labels.Skip(1)); + return SharedDomains.Contains(parent) ? "" : parent; + } + + /// + /// Dynamic-DNS domains several servers share; a host under one is not that server's domain. + /// + private static readonly HashSet SharedDomains = new(StringComparer.OrdinalIgnoreCase) + { + "ddns.net", "duckdns.org", "hopto.org", "abrdns.com", "zapto.org", "redirectme.net", + "dynamic-dns.net", "gdleac.com", "acportalstorm.com", + }; +} diff --git a/src/RynthCore.Engine/Compatibility/AppraisalHooks.cs b/src/RynthCore.Engine/Compatibility/AppraisalHooks.cs index 2bf83c5..78e9511 100644 --- a/src/RynthCore.Engine/Compatibility/AppraisalHooks.cs +++ b/src/RynthCore.Engine/Compatibility/AppraisalHooks.cs @@ -157,11 +157,19 @@ internal static class AppraisalHooks } } - /// The object was created again: its data is current, not merely kept. - public static void MarkLive(uint guid) + /// + /// The object was created again: its data is current, not merely kept. Except data kept since + /// a release longer ago than ReleasedObjectRetention.StaleAfterMs: the client sent no updates + /// meanwhile, so it is dropped here (the next appraisal refreshes it). Returns true when it was. + /// + public static bool MarkLive(uint guid, long nowMs) { lock (_cacheLock) - _released.Forget(guid); + { + if (!_released.TakeLive(guid, nowMs)) return false; + EvictLocked(guid); + return true; + } } /// Drops the data of objects released longer ago than the retention time. Timer thread. diff --git a/src/RynthCore.Engine/Compatibility/AutoIdDrain.cs b/src/RynthCore.Engine/Compatibility/AutoIdDrain.cs index 9ca8b8d..94662a8 100644 --- a/src/RynthCore.Engine/Compatibility/AutoIdDrain.cs +++ b/src/RynthCore.Engine/Compatibility/AutoIdDrain.cs @@ -7,7 +7,10 @@ // // Per tick: take the new candidates, the one-shot login sweep, then look at the pending // list in order (at most MaxEvaluatedPerTick, at most MaxPerTick sends) and decide each -// one with AutoIdPolicy. Waits stay; skips leave; a send leaves only when the main-thread +// one with AutoIdPolicy. When the evaluation budget runs out with items still unlooked-at, +// the ones just evaluated (and kept) move to the back, so the next tick starts where this +// one stopped: with more than MaxEvaluatedPerTick items waiting, a newer item at the end +// is reached in a few ticks instead of never (review fix 2026-10-18). Waits stay; skips leave; a send leaves only when the main-thread // queue took it (a refusal, in a transition or with the ring full, keeps the entry and // ends this tick's sending). // @@ -93,6 +96,7 @@ internal sealed class AutoIdDrain private int _incomingCount; private readonly List _pending = new(256); private readonly HashSet _pendingIds = new(); + private readonly List _rotateScratch = new(MaxEvaluatedPerTick); private int _pendingCount; private long _lastInventorySendMs; private long _sweptLoginAt; @@ -225,11 +229,14 @@ internal sealed class AutoIdDrain bool sending = true; int keep = 0, evaluated = 0; + int keptBeforeBudgetEnd = -1; // evaluated-and-kept items at the front when the budget ran out for (int i = 0; i < _pending.Count; i++) { Pending p = _pending[i]; if (!sending || sent >= MaxPerTick || evaluated >= MaxEvaluatedPerTick) { + if (keptBeforeBudgetEnd < 0 && sending && sent < MaxPerTick) + keptBeforeBudgetEnd = keep; // only the evaluation budget ended it (not a send limit or a refusal) _pending[keep++] = p; continue; } @@ -293,6 +300,15 @@ internal sealed class AutoIdDrain } } _pending.RemoveRange(keep, _pending.Count - keep); + // Round-robin: [evaluated and kept | not looked at] becomes [not looked at | evaluated and kept]. + if (keptBeforeBudgetEnd > 0 && keptBeforeBudgetEnd < _pending.Count) + { + _rotateScratch.Clear(); + for (int i = 0; i < keptBeforeBudgetEnd; i++) _rotateScratch.Add(_pending[i]); + _pending.RemoveRange(0, keptBeforeBudgetEnd); + _pending.AddRange(_rotateScratch); + _rotateScratch.Clear(); + } Volatile.Write(ref _pendingCount, _pending.Count); return sent; } diff --git a/src/RynthCore.Engine/Compatibility/AutoIdService.cs b/src/RynthCore.Engine/Compatibility/AutoIdService.cs index 37b1492..2aa0284 100644 --- a/src/RynthCore.Engine/Compatibility/AutoIdService.cs +++ b/src/RynthCore.Engine/Compatibility/AutoIdService.cs @@ -164,10 +164,12 @@ internal static class AutoIdService return; // Created again: data kept since a client release is current again (and still cached - // if the release was inside ReleasedObjectRetention's time). - AppraisalHooks.MarkLive(objectId); - bool cached = AppraisalHooks.HasAppraisalData(objectId); + // if the release was inside ReleasedObjectRetention's time), unless it was kept so long + // that it may be out of date (StaleAfterMs): then it is dropped and the object, uncached, + // is a candidate again. long now = Environment.TickCount64; + AppraisalHooks.MarkLive(objectId, now); + bool cached = AppraisalHooks.HasAppraisalData(objectId); AutoIdEligibility.CreateDecision decision; lock (_gate) decision = _eligibility.OnCreate(objectId, now, cached); diff --git a/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs b/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs index da233c4..c48c9dd 100644 --- a/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs +++ b/src/RynthCore.Engine/Compatibility/HeartbeatLogger.cs @@ -179,6 +179,10 @@ internal static class HeartbeatLogger } // Safety net for the main-thread message box count (MainThreadFreeze). MessageBoxHooks.ReconcileStaleMainThreadCount(); + // gateov=N = the world-transition gate's safety valve has opened N times (a death/portal + // that outlasted WorldTransitionState.MaxHoldMs); omitted while 0. + try { int gov = PlayerLifecycleLog.GateOverrides; if (gov > 0) vaField += $" gateov={gov}"; } + catch { } // pump=paused = plugin ticks paused because AC's main thread is frozen // (MainThreadFreeze); omitted while running. try { if (MainThreadFreeze.Paused) vaField += $" pump=paused stall={MainThreadFreeze.MainThreadStallMs}ms"; } diff --git a/src/RynthCore.Engine/Compatibility/PlayerLifecycleLog.cs b/src/RynthCore.Engine/Compatibility/PlayerLifecycleLog.cs index 0c3d843..0933cd0 100644 --- a/src/RynthCore.Engine/Compatibility/PlayerLifecycleLog.cs +++ b/src/RynthCore.Engine/Compatibility/PlayerLifecycleLog.cs @@ -31,6 +31,8 @@ internal static class PlayerLifecycleLog private static readonly WorldTransitionState _state = new(); private static long _settleUntil; // published copy for other threads private static volatile bool _portaling, _dead; + private static volatile bool _gateOpen; // the valve opened, or engine.json TransitionGate is off + private static int _gateOverrides; private static long _portalEnteredAt, _diedAt; /// @@ -39,7 +41,13 @@ internal static class PlayerLifecycleLog /// (BusyCountHooks' force-clear). As of the last game tick; any thread. /// public static bool InWorldTransition => - _dead || _portaling || Environment.TickCount64 < Interlocked.Read(ref _settleUntil); + !_gateOpen && (_dead || _portaling || Environment.TickCount64 < Interlocked.Read(ref _settleUntil)); + + /// + /// Times the transition gate's safety valve opened (a transition held more than + /// WorldTransitionState.MaxHoldMs without a break), for the heartbeat (gateov=N). + /// + public static int GateOverrides => Volatile.Read(ref _gateOverrides); /// /// When the last settle window ends (TickCount64; 0 = no transition yet), as of the last @@ -92,13 +100,25 @@ internal static class PlayerLifecycleLog uint landblock = cell >> 16; long now = Environment.TickCount64; + bool gateSetting = true; + try { gateSetting = Plugins.EngineSettings.TransitionGate; } catch { } + _state.Enabled = gateSetting; WorldTransitionState.Edge edges = _state.Sample(now, dead, portaling, landblock); _dead = _state.Dead; _portaling = _state.Portaling; - Interlocked.Exchange(ref _settleUntil, _state.SettleUntilMs); + PublishGate(); if (edges == WorldTransitionState.Edge.None) return; + if ((edges & WorldTransitionState.Edge.GateOverride) != 0) + { + Interlocked.Exchange(ref _gateOverrides, _state.Overrides); + RynthLog.Warn($"[Lifecycle] world-transition gate OPENED by its safety valve after {_state.HeldForMs(now) / 1000} s held without a break " + + $"(dead={_state.Dead}, portaling={_state.Portaling}, health {health}/{maxHealth}, landblock 0x{landblock:X4}); queued game actions run again. " + + "A character that reads dead after a revive, or a stuck portal flag, would otherwise freeze every bot. " + + $"Open #{_state.Overrides} this session; engine.json TransitionGate=false turns the gate off."); + } + if ((edges & WorldTransitionState.Edge.Died) != 0) { _diedAt = now; @@ -126,11 +146,19 @@ internal static class PlayerLifecycleLog { long now = Environment.TickCount64; bool started = _state.OnTeleportMessage(now); - Interlocked.Exchange(ref _settleUntil, _state.SettleUntilMs); + PublishGate(); if (started) RynthLog.Info($"[Lifecycle] PlayerTeleport (0xF751) received in landblock 0x{_state.Landblock:X4}; queued game actions held off for {WorldTransitionState.SettleMs / 1000} s."); } + // Published for other threads: with the gate open (valve or setting off) the settle window reads as + // none, so InWorldTransition and AutoId's post-transition defer let go too. + private static void PublishGate() + { + _gateOpen = !_state.Enabled || _state.Overridden; + Interlocked.Exchange(ref _settleUntil, _gateOpen ? 0 : _state.SettleUntilMs); + } + private static string Ago(long since, long now) => since == 0 ? "?" : $"{(now - since) / 1000.0:0.0}s"; } diff --git a/src/RynthCore.Engine/Compatibility/ProcessExitHooks.cs b/src/RynthCore.Engine/Compatibility/ProcessExitHooks.cs index a8f95b1..ffa4ea3 100644 --- a/src/RynthCore.Engine/Compatibility/ProcessExitHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ProcessExitHooks.cs @@ -208,6 +208,40 @@ internal static class ProcessExitHooks // never reaches the last-chance filter). Which codes count: CrashExitRule. private static bool IsCrashExit(uint code) => CrashExitRule.IsCrashExit(code); + // Review fix (2026-10-18): the managed dump this file used to write on TerminateProcess / + // NtTerminateProcess (f9c62ed, for Lucy's Town) was removed above on the grounds that + // createdump covers it. It covers only the paths the CLR itself ends: an AV that unwinds + // through one of our managed detours, or reaches the CLR's unhandled-exception filter (both + // checked offline with a small CoreCLR host: createdump runs). It does NOT cover a native AV + // that AC's own handler catches and answers with TerminateProcess: no CLR frame, no CLR + // filter, and nothing else here writes a dump. So the dump is back on that path, with what + // made the old one risky taken out: + // - after the native log flush, so the crash log is on disk whatever happens next; + // - on its own thread with a bounded wait (CrashDumpWaitMs): if the dying process is stuck + // on a lock, the exit goes ahead after that, never hangs; a 0-byte file is deleted by + // the next client's log housekeeping; + // - once per process, and not at all when createdump already wrote clr__*.dmp; + // - small type only (CrashDump.WriteSelfDump), which also needs free space + // (DumpBudget.SmallDumpMinFree), and only the newest few are kept. + private static int _crashDumped; + private const int CrashDumpWaitMs = 20_000; + + private static void DumpCrashOnce(string via, uint code) + { + if (Interlocked.Exchange(ref _crashDumped, 1) != 0) return; + try + { + var worker = new Thread(() => + { + try { CrashDump.WriteCrashDumpOnce(via, code); } + catch { } + }) { IsBackground = true, Name = "RynthCore.CrashDump" }; + worker.Start(); + worker.Join(CrashDumpWaitMs); + } + catch { /* never block or break the exit */ } + } + private static bool TerminateProcessDetour(IntPtr hProcess, uint exitCode) { // Only log when terminating ourselves: TerminateProcess on other process handles is a @@ -215,7 +249,11 @@ internal static class ProcessExitHooks bool selfKill = hProcess == new IntPtr(-1) || hProcess == GetCurrentProcessHandle(); if (selfKill) { - if (IsCrashExit(exitCode)) SehTrampoline.FlushCrashLog(exitCode); + if (IsCrashExit(exitCode)) + { + SehTrampoline.FlushCrashLog(exitCode); + DumpCrashOnce("TerminateProcess", exitCode); + } else LogTermination("TerminateProcess", hProcess, exitCode); } try { return _terminateOriginal!(hProcess, exitCode); } @@ -246,7 +284,11 @@ internal static class ProcessExitHooks if (selfKill) { // A second flush (TerminateProcess calls this) writes nothing: records are written once. - if (IsCrashExit(exitStatus)) SehTrampoline.FlushCrashLog(exitStatus); + if (IsCrashExit(exitStatus)) + { + SehTrampoline.FlushCrashLog(exitStatus); + DumpCrashOnce("NtTerminateProcess", exitStatus); + } else LogTermination("NtTerminateProcess", processHandle, exitStatus); } try { return _ntTermOriginal!(processHandle, exitStatus); } diff --git a/src/RynthCore.Engine/Compatibility/ReleasedObjectRetention.cs b/src/RynthCore.Engine/Compatibility/ReleasedObjectRetention.cs index 1ffb902..40d9493 100644 --- a/src/RynthCore.Engine/Compatibility/ReleasedObjectRetention.cs +++ b/src/RynthCore.Engine/Compatibility/ReleasedObjectRetention.cs @@ -11,7 +11,10 @@ // - when RetainMs has passed (Expire, from AutoIdService's timer); // - when the SERVER deleted the object (0xF747; AppraisalHooks.EvictObject); // - at a session clear (logout), and under AppraisalHooks' object cap. -// A re-create (OnLive) makes the object current again. +// A re-create (TakeLive) makes the object current again, but data kept for StaleAfterMs or +// longer is dropped then (review fix 2026-10-18): the client sent no updates for an object it +// had released, so a stack count or a structure kept that long may be minutes old. A re-create +// after a short absence (walking out of and back into view) still finds its data. // // Pure bookkeeping (released ids and when); no locking (AppraisalHooks holds its lock). // Compiled into tools\EngineRobustnessTests. @@ -26,6 +29,9 @@ internal sealed class ReleasedObjectRetention public const long DefaultRetainMs = 10L * 60 * 1000; public const int DefaultMaxReleased = 4096; + /// A re-create this long after the release no longer trusts the kept data. + public const long StaleAfterMs = 2L * 60 * 1000; + private readonly Dictionary _releasedAt; private readonly long _retainMs; private readonly int _max; @@ -56,6 +62,17 @@ internal sealed class ReleasedObjectRetention /// The object is current again (re-created), or its data was dropped for another reason. public void Forget(uint id) => _releasedAt.Remove(id); + /// + /// The object was created again. Returns true when it had been released for + /// or longer (its kept data may be out of date: drop it); + /// false when it was not released, or only briefly. Either way it is current again. + /// + public bool TakeLive(uint id, long nowMs, long staleAfterMs = StaleAfterMs) + { + if (!_releasedAt.Remove(id, out long at)) return false; + return nowMs - at >= staleAfterMs; + } + public bool IsReleased(uint id) => _releasedAt.ContainsKey(id); /// Released ids whose data has outlived RetainMs: removed here and added to . diff --git a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs index 456d94a..6dcbfeb 100644 --- a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs +++ b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs @@ -398,24 +398,47 @@ internal static class RynthCoreChatCommands return true; } - // /rc skills [show|hide|toggle] : the ImGui Skills panel; /rc progression opens it on its - // Progression tab (ILT worlds; the tab shows once RynthILT reports ILT features). - if (IsVerb(sub, "skills", out string skillsArgs)) + // /rc oracle-skills : RynthOracle says which SkillsFace body to embed + // in its window (engine bridge; Silentkelpie's design). Any valid form also tells the engine that + // Oracle has the tabs, which hides the standalone Skills bar icon and routes /rc skills there. + if (IsVerb(sub, "oracle-skills", out string oracleSkillsArgs)) { - if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.SkillsFace.Title)) - Reply("The Skills panel isn't available (the ImGui layer is off?)."); - else if (!TryPanelMode(skillsArgs, out bool? show)) - Reply("Usage: /rc skills [show|hide|toggle]"); + string a = oracleSkillsArgs.Trim().ToLowerInvariant(); + int tab = a switch + { + "off" or "clear" or "none" or "-1" => -1, + "0" or "skills" or "skill" => 0, + "1" or "attrs" or "attributes" or "vitals" => 1, + "2" or "progress" or "progression" => 2, + _ => -2, + }; + if (tab == -2) + Reply("Usage: /rc oracle-skills "); else - SetPanelOpen(ImGuiBackend.Panels.SkillsFace.Title, show); + { + ImGuiBackend.Panels.OracleSkillsEmbed.Announce(); + if (tab < 0) ImGuiBackend.Panels.OracleSkillsEmbed.Clear(); + else ImGuiBackend.Panels.OracleSkillsEmbed.SetActiveTab(tab); + } return true; } - if (sub.Equals("progression", StringComparison.OrdinalIgnoreCase)) + + // /rc skills [show|hide|toggle] : RynthOracle's Skills tab when Oracle provides it (see + // SkillsRouting), else the standalone ImGui Skills panel. /rc progression (or progress) opens the + // Progress tab / the panel's Progression tab (ILT worlds; it shows once RynthILT reports ILT features). + if (IsVerb(sub, "skills", out string skillsArgs)) { - if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.SkillsFace.Title)) + if (!TryPanelMode(skillsArgs, out bool? show)) + Reply("Usage: /rc skills [show|hide|toggle]"); + else if (!ImGuiBackend.Panels.SkillsRouting.SetOpen(show)) + Reply("The Skills panel isn't available (the ImGui layer is off?)."); + return true; + } + if (sub.Equals("progression", StringComparison.OrdinalIgnoreCase) + || sub.Equals("progress", StringComparison.OrdinalIgnoreCase)) + { + if (!ImGuiBackend.Panels.SkillsRouting.Open(2)) Reply("The Skills panel isn't available (the ImGui layer is off?)."); - else - ImGuiBackend.Panels.SkillsFace.ShowProgression(); return true; } diff --git a/src/RynthCore.Engine/Compatibility/WorldTransitionState.cs b/src/RynthCore.Engine/Compatibility/WorldTransitionState.cs index 058ac8b..a893424 100644 --- a/src/RynthCore.Engine/Compatibility/WorldTransitionState.cs +++ b/src/RynthCore.Engine/Compatibility/WorldTransitionState.cs @@ -25,6 +25,14 @@ // fight, AC streams the neighbour in without tearing the player's world down, and a 5 s // hold there would stall every border fight. // +// Safety valve (2026-10-18 review): the gate holds everything, with no way out but the +// transition ending. Dead is "MaxHealth > 0 && Health == 0" and the portal flag is AC's own; +// if a revived character kept reading Health 0, or the flag stuck, every bot would freeze +// silently. So a transition that has held CONTINUOUSLY for MaxHoldMs opens the gate by +// itself (Overridden: counted in Overrides, announced once through Edge.GateOverride) and +// stays open until the raw transition ends. Enabled = false (engine.json TransitionGate) +// turns the gate off altogether. +// // Pure: AC main thread only (single writer and reader: the UseTime sample and both // main-thread drains). Compiled into tools\EngineRobustnessTests. // ============================================================================ @@ -37,6 +45,12 @@ internal sealed class WorldTransitionState { public const long SettleMs = 5_000; + /// + /// A transition held this long without a break opens the gate. A real death + portal + + /// settle is well under 30 s (a slow portal load or a very long death screen included). + /// + public const long MaxHoldMs = 120_000; + [Flags] public enum Edge { @@ -46,6 +60,8 @@ internal sealed class WorldTransitionState PortalEntered = 4, PortalExited = 8, LandblockJump = 16, + /// The valve opened: the transition outlasted . + GateOverride = 32, } private bool _init; @@ -58,8 +74,46 @@ internal sealed class WorldTransitionState /// Last time a gate check saw the transition (0 = never). public long LastBlockedMs { get; private set; } + /// False = the gate is off (engine.json TransitionGate): nothing is ever held. + public bool Enabled { get; set; } = true; + + /// The valve is open: the current transition outlasted . + public bool Overridden { get; private set; } + + /// Times the valve has opened, over the life of this state. + public int Overrides { get; private set; } + + /// How long the current transition has been held, as of the last sample (0 = none). + public long HeldForMs(long nowMs) => _heldSinceMs == 0 ? 0 : nowMs - _heldSinceMs; + + private long _heldSinceMs; + + /// Dead, portaling, or inside the settle window, whatever the valve and the setting say. + public bool RawInTransition(long nowMs) => Dead || Portaling || nowMs < SettleUntilMs; + /// One game-tick sample. Returns the edges crossed (for the lifecycle log). public Edge Sample(long nowMs, bool dead, bool portaling, uint landblock) + { + Edge edges = SampleCore(nowMs, dead, portaling, landblock); + if (!RawInTransition(nowMs)) + { + _heldSinceMs = 0; + Overridden = false; + } + else if (_heldSinceMs == 0) + { + _heldSinceMs = nowMs; + } + else if (!Overridden && nowMs - _heldSinceMs >= MaxHoldMs) + { + Overridden = true; + Overrides++; + edges |= Edge.GateOverride; + } + return edges; + } + + private Edge SampleCore(long nowMs, bool dead, bool portaling, uint landblock) { if (!_init) { @@ -115,8 +169,11 @@ internal sealed class WorldTransitionState return Math.Abs(dx) > 1 || Math.Abs(dy) > 1; } - /// Dead, portaling, or inside the settle window. - public bool InTransition(long nowMs) => Dead || Portaling || nowMs < SettleUntilMs; + /// + /// Dead, portaling, or inside the settle window, and the gate is on and its valve has not + /// opened: the answer every drain and every "is it safe to poke AC" check wants. + /// + public bool InTransition(long nowMs) => Enabled && !Overridden && RawInTransition(nowMs); public enum Verdict { Run, Hold, Drop } diff --git a/src/RynthCore.Engine/CrashDump.cs b/src/RynthCore.Engine/CrashDump.cs index 0507e2a..497568b 100644 --- a/src/RynthCore.Engine/CrashDump.cs +++ b/src/RynthCore.Engine/CrashDump.cs @@ -36,6 +36,9 @@ internal static class CrashDump IntPtr userStreamParam, IntPtr callbackParam); + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern bool GetDiskFreeSpaceExW(string directory, out ulong freeAvailable, out ulong total, out ulong totalFree); + [DllImport("kernel32.dll")] private static extern IntPtr GetCurrentProcess(); @@ -73,6 +76,14 @@ internal static class CrashDump string dir = Path.Combine(LogPaths.LogDirectory, "dumps"); Directory.CreateDirectory(dir); + // The small dump is tens of MB; with the volume nearly full it would only fail halfway. + long free = FreeBytes(dir); + if (!DumpBudget.SmallDumpAllowed(free)) + { + RynthLog.Error($"CrashDump: not writing the {prefix} dump - {(free < 0 ? "free space unknown" : (free / (1024 * 1024)) + " MB free")} on the dump volume, reason={reason}"); + return false; + } + string stamp = DateTime.Now.ToString("yyyyMMdd_HHmmss"); dumpPath = Path.Combine(dir, $"{prefix}_{Environment.ProcessId}_{stamp}.dmp"); return WriteDumpFile(dumpPath, DumpTypePreferred, DumpTypeFallback, reason); @@ -84,6 +95,45 @@ internal static class CrashDump } } + /// Free bytes available to this user on the volume holding ; -1 when unknown. + internal static long FreeBytes(string dir) + { + try + { + if (GetDiskFreeSpaceExW(dir, out ulong avail, out _, out _)) + return avail > long.MaxValue ? long.MaxValue : (long)avail; + } + catch { } + return -1; + } + + /// Crash dumps (crash_<pid>_*.dmp) kept in Logs\dumps. + internal const int CrashDumpsKept = 5; + + /// + /// On a crash exit (ProcessExitHooks): one small dump of this process unless CoreCLR's + /// createdump already wrote clr_<pid>_*.dmp for it. Never throws. + /// + internal static void WriteCrashDumpOnce(string via, uint code) + { + try + { + string dir = Path.Combine(LogPaths.LogDirectory, "dumps"); + try + { + if (Directory.Exists(dir) && Directory.GetFiles(dir, $"clr_{Environment.ProcessId}_*.dmp").Length > 0) + return; // the CLR's own crash dump is there: a second one adds nothing + } + catch { } + if (WriteSelfDump($"{via} 0x{code:X8}", out string path, "crash")) + { + RynthLog.Info($"ProcessExit: crash dump written {path} ({via} 0x{code:X8})"); + PruneDumps(dir, "crash_", CrashDumpsKept); + } + } + catch { } + } + // Writes one dump to . On ERROR_INVALID_PARAMETER (87: AC's ancient // dbghelp 6.1 rejected a flag) retries with . Never leaves a // 0-byte or partial .dmp behind (it reads as a crash marker during triage; observed: @@ -216,6 +266,12 @@ internal static class CrashDump Directory.CreateDirectory(dir); string path = Path.Combine(dir, $"{OutOfMemoryDumpPrefix}{Environment.ProcessId}_{DateTime.Now:yyyyMMdd_HHmmss}.dmp"); + if (!ReserveFullDump(dir, path, out string refusal)) + { + RynthLog.Error($"CrashDump: OUT OF MEMORY full-memory dump skipped ({refusal}); writing the small dump instead."); + WriteSelfDump(reason, out _, "oom-small"); + return; + } if (WriteDumpFile(path, DumpTypeFull, DumpTypeFullFallback, reason)) { _fullDumpWrittenPath = path; @@ -235,6 +291,96 @@ internal static class CrashDump } } + // Every client runs this check-then-create under one machine-wide (per logon session) mutex, + // and the empty placeholder it creates counts against the next client's check, so clients that + // hit OUT OF MEMORY together cannot all pass the check before any of them has started writing. + private const string FullDumpGateName = @"Local\RynthCore.FullDumpGate"; + private const int FullDumpGateWaitMs = 10_000; + + /// + /// Whether a full dump may be written to now (: + /// free space on the volume, and the number and bytes of full dumps already in the folder from + /// ALL clients). On a refusal it first prunes the folder down to + /// OutOfMemoryDumpsKept - 1 (dumps of dead clients and our own older ones) and asks again. + /// On success an empty placeholder exists at . + /// + private static bool ReserveFullDump(string dir, string path, out string refusal) + { + refusal = string.Empty; + Mutex? gate = null; + bool held = false; + try + { + try + { + gate = new Mutex(false, FullDumpGateName); + held = gate.WaitOne(FullDumpGateWaitMs); + } + catch (AbandonedMutexException) { held = true; } // a client died holding it: ours now + catch { /* no mutex available: decide without it */ } + + long estimate = DumpBudget.EstimateFullDumpBytes(PrivateBytes()); + DumpVerdict verdict = EvaluateFolder(dir, estimate, out long free, out int count, out long bytes); + if (verdict != DumpVerdict.Full) + { + // Older dumps are the thing most likely to be in the way: make room for this one. + PruneDumps(dir, OutOfMemoryDumpPrefix, Math.Max(0, OutOfMemoryDumpsKept - 1)); + verdict = EvaluateFolder(dir, estimate, out free, out count, out bytes); + } + if (verdict != DumpVerdict.Full) + { + refusal = $"{verdict}: {(free < 0 ? "free space unknown" : (free / (1024 * 1024)) + " MB free")}, dump needs ~{estimate / (1024 * 1024)} MB, " + + $"{count} full dump(s) / {bytes / (1024 * 1024)} MB already in {dir}"; + return false; + } + try + { + using (new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.ReadWrite)) { } + } + catch (Exception ex) + { + refusal = $"cannot create {path}: {ex.GetType().Name}"; + return false; + } + return true; + } + finally + { + if (gate != null) + { + if (held) { try { gate.ReleaseMutex(); } catch { } } + gate.Dispose(); + } + } + } + + private static DumpVerdict EvaluateFolder(string dir, long estimate, out long free, out int count, out long bytes) + { + free = FreeBytes(dir); + count = 0; + bytes = 0; + try + { + foreach (FileInfo f in new DirectoryInfo(dir).GetFiles(OutOfMemoryDumpPrefix + "*.dmp")) + { + count++; + try { bytes += f.Length; } catch { } + } + } + catch { } + return DumpBudget.Evaluate(free, estimate, count, bytes); + } + + private static long PrivateBytes() + { + try + { + using var p = System.Diagnostics.Process.GetCurrentProcess(); + return p.PrivateMemorySize64; + } + catch { return 0; } + } + /// /// Deletes all but the newest *.dmp files in /// . The folder is shared by every client: a dump whose name carries diff --git a/src/RynthCore.Engine/DumpBudget.cs b/src/RynthCore.Engine/DumpBudget.cs new file mode 100644 index 0000000..01c346d --- /dev/null +++ b/src/RynthCore.Engine/DumpBudget.cs @@ -0,0 +1,62 @@ +using System; + +namespace RynthCore.Engine; + +/// +/// Whether a full-memory dump may be written now. Pure arithmetic (the disk and folder are read +/// by ), so tools\EngineRobustnessTests runs it directly. +/// +/// A full dump is about the size of the process (a 32-bit client: up to ~4 GB), the client is +/// frozen while it is written, and every client that hits the OUT OF MEMORY box at once writes +/// one. So: the volume must keep a margin free afterwards, and the dumps already in the folder +/// (all clients, live or not) are capped in number and in bytes. When the verdict is not +/// the caller writes the small dump instead. +/// +internal enum DumpVerdict +{ + Full = 0, + /// Free space unknown, or less than the dump plus . + LowDisk, + /// or more full dumps are already in the folder. + TooManyDumps, + /// The full dumps in the folder plus this one would pass . + TooManyBytes, +} + +internal static class DumpBudget +{ + /// Free space that must remain on the volume after a full dump. + internal const long MinFreeAfterFullDump = 2L * 1024 * 1024 * 1024; + + /// Full dumps in the folder, all clients together, before another is refused. + internal const int MaxFullDumpsAllPids = 4; + + /// Bytes of full dumps in the folder, all clients together, including the one about to be written. + internal const long MaxFullDumpBytesAllPids = 14L * 1024 * 1024 * 1024; + + /// A full dump holds the private memory plus the mapped images and the dump's own tables. + internal const long FullDumpOverheadBytes = 512L * 1024 * 1024; + + /// The small (Normal + handle data) dump is tens of MB; it still needs some room. + internal const long SmallDumpMinFree = 200L * 1024 * 1024; + + /// Largest a 32-bit client can be; the estimate when the process size cannot be read. + internal const long FallbackProcessBytes = 4L * 1024 * 1024 * 1024; + + internal static long EstimateFullDumpBytes(long privateBytes) + => (privateBytes > 0 ? privateBytes : FallbackProcessBytes) + FullDumpOverheadBytes; + + /// Free bytes available to this user on the dump volume; negative = unknown. + /// The size this dump is expected to have. + /// Full dumps already in the folder (any client, any state). + /// Their combined size. + internal static DumpVerdict Evaluate(long freeBytes, long estimateBytes, int existingCount, long existingBytes) + { + if (freeBytes < 0 || freeBytes - estimateBytes < MinFreeAfterFullDump) return DumpVerdict.LowDisk; + if (existingCount >= MaxFullDumpsAllPids) return DumpVerdict.TooManyDumps; + if (existingBytes + estimateBytes > MaxFullDumpBytesAllPids) return DumpVerdict.TooManyBytes; + return DumpVerdict.Full; + } + + internal static bool SmallDumpAllowed(long freeBytes) => freeBytes >= SmallDumpMinFree; +} diff --git a/src/RynthCore.Engine/EntryPoint.cs b/src/RynthCore.Engine/EntryPoint.cs index d50a398..6ba2339 100644 --- a/src/RynthCore.Engine/EntryPoint.cs +++ b/src/RynthCore.Engine/EntryPoint.cs @@ -165,16 +165,98 @@ public static class EntryPoint private const long ManualReloadWindowMs = 10_000; internal static void NoteManualReload() => Interlocked.Exchange(ref _manualReloadAtMs, Environment.TickCount64); + /// True when ERl / the bar RL / /rc rl / the hotkey marked a hand reload within the window + /// (does not clear the mark). + private static bool IsRecentManualReload() + { + long manualAt = Volatile.Read(ref _manualReloadAtMs); + return manualAt != 0 && Environment.TickCount64 - manualAt < ManualReloadWindowMs; + } + + /// + /// In the world after a successful login, and not yet logged out: with + /// engine.json HoldReloadInWorld on, an automatic reload waits. Character select / + /// disconnected / never logged in are safe to reload. (From SilentKelpie's PR 6.) + /// + private static bool IsInWorldForAutoReloadDeferral() + { + try + { + if (!Compatibility.LoginLifecycleHooks.HasObservedLoginComplete) return false; + if (Compatibility.LogoutLifecycleHooks.HasObservedLogout) return false; + int mode = Compatibility.UiFlowHooks.CurrentMode; + // Explicit non-world screens: safe for an automatic reload. + if (mode == Compatibility.UiFlowHooks.ModeCharacterManagement + || mode == Compatibility.UiFlowHooks.ModeDisconnected + || mode == Compatibility.UiFlowHooks.ModeIntro + || mode == Compatibility.UiFlowHooks.ModeCharGen + || mode == Compatibility.UiFlowHooks.ModeCredits + || mode == Compatibility.UiFlowHooks.ModeDataPatch + || mode == Compatibility.UiFlowHooks.ModeEpilogue) + return false; + // ModeGamePlay, or ModeNone before the first mode sample after login: hold. + return true; + } + catch { return false; } + } + + /// + /// The opt-in in-world hold (engine.json HoldReloadInWorld, default off; ReloadInWorldGate). Only + /// called with the setting on. Waits, with the game running on this engine, while the player is in + /// the world and the reload is an automatic one, for at most HoldReloadInWorldMaxMinutes; a hand + /// reload that arrives meanwhile (ERl, RL, /rc rl, hotkey) or switching the setting off ends the + /// wait. Returns true when a hand reload ended it, so the caller skips the plugin deferral too. + /// Never throws; any failure fails open to "reload now". + /// + private static bool HoldReloadWhileInWorld() + { + try + { + var maxWait = TimeSpan.FromMinutes(ReloadInWorldGate.ClampMaxMinutes(EngineSettings.HoldReloadInWorldMaxMinutes)); + ReloadInWorldGate.Outcome outcome = ReloadInWorldGate.Run( + // Re-read each poll: a hand reload or the setting turned off in the meantime ends the hold. + stillHold: () => ReloadInWorldGate.ShouldHold(IsRecentManualReload(), EngineSettings.HoldReloadInWorld, IsInWorldForAutoReloadDeferral()), + log: msg => RynthLog.Info(msg), + notify: why => Compatibility.AcMainThreadQueue.EnqueueWriteToChat( + $"[RynthCore] A new RynthCore build is ready. It loads when you leave the world ({why}; at most {maxWait.TotalMinutes:0.#} minutes).", 1), + maxWait: maxWait, + waited: out TimeSpan waited); + if (outcome != ReloadInWorldGate.Outcome.Clear) + RynthLog.Info($"engine reload: in-world hold {outcome} after {waited.TotalSeconds:0.0} s."); + } + catch (Exception ex) + { + RynthLog.Warn($"engine reload: in-world hold failed ({ex.GetType().Name}: {ex.Message}); reloading now."); + } + // A hand reload that came in during the wait set the mark again: it counts as by hand. + return IsRecentManualReload(); + } + /// /// 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". + /// With engine.json HoldReloadInWorld on (default off), an automatic reload first waits until + /// the player leaves the world (HoldReloadWhileInWorld); a hand reload is never held. /// private static void DeferReloadWhilePluginsObject() { long manualAt = Interlocked.Exchange(ref _manualReloadAtMs, 0); - if (manualAt != 0 && Environment.TickCount64 - manualAt < ManualReloadWindowMs) + bool byHand = manualAt != 0 && Environment.TickCount64 - manualAt < ManualReloadWindowMs; + + bool hold = false; + try { hold = EngineSettings.HoldReloadInWorld; } catch { } // opt-in, default off: any failure = no hold + if (hold && ReloadInWorldGate.ShouldHold(byHand, hold, IsInWorldForAutoReloadDeferral())) + { + if (HoldReloadWhileInWorld()) + { + Interlocked.Exchange(ref _manualReloadAtMs, 0); + byHand = true; + } + } + + if (byHand) { RynthLog.Info("engine reload: asked for by hand (ERl), so it isn't deferred for the plugins."); return; @@ -702,7 +784,12 @@ public static class EntryPoint // a module-resolved stack sweep for the AV (0xC0000005) / fail-fast // (0xC0000602) classes that bypass managed handlers, into a dedicated // native-crash.log so the next crash self-reports instead of going dark. - SehTrampoline.InstallCrashLogger(System.IO.Path.Combine(LogPaths.LogDirectory, "native-crash.log")); + // The shared file has one fixed name, so no per-PID rotation covers it: move a big one + // aside on the first generation, before the native side opens it. (Later generations + // keep the handle the first one opened, so rotating then would only be ignored.) + if (_initCount <= 1 && LogPaths.RotateNativeCrashLogAtStartup()) + RynthLog.Compat("native-crash.log was over 1 MB at startup: moved to native-crash.log.old"); + SehTrampoline.InstallCrashLogger(System.IO.Path.Combine(LogPaths.LogDirectory, LogPaths.NativeCrashLogName)); } if (!ConfigureImGuiNativeLibrary(engineDir)) diff --git a/src/RynthCore.Engine/ImGui/EngineFrameController.cs b/src/RynthCore.Engine/ImGui/EngineFrameController.cs index 945e34c..21de28a 100644 --- a/src/RynthCore.Engine/ImGui/EngineFrameController.cs +++ b/src/RynthCore.Engine/ImGui/EngineFrameController.cs @@ -278,6 +278,11 @@ internal static class EngineFrameController // in ImGui-off mode so Avalonia owner-window binding works. EnsureCore(pDevice); + // Settings > Display: borderless windowed + AC window placement. Throttled; reads only + // here - the window itself is changed from the game WndProc (AcWindowChrome). + try { UI.AcWindowChrome.Tick(_gameHwnd); } + catch (Exception ex) { RynthLog.UI($"AcWindowChrome.Tick threw {ex.GetType().Name}: {ex.Message}"); } + // Cache the D3D9 device function pointers used by Nav3DRenderInjector, // RenderNav3D, and the always-on render path. This is a strict subset // of what InitImGui needs and is safe to run without ImGui state. diff --git a/src/RynthCore.Engine/ImGui/ImGuiBar.cs b/src/RynthCore.Engine/ImGui/ImGuiBar.cs index 4acd3c7..73beb50 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiBar.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiBar.cs @@ -67,10 +67,18 @@ internal static class ImGuiBar ScriptWindow? Window = null); // Engine panels with an ImGui face only (no OverlayHost entry) that get a bar button. + // Item Count has no icon of its own since 2026-10-18: Inventory's Count button, /rc itemcount, the Character menu. + // Skills moves under RynthOracle (Skills / Attributes / Progress tabs): its icon shows only while Oracle's + // tabs can't be reached (SkillsRouting.ShowSkillsBarIcon), so nobody loses the way in. Mini Remote stays. private static readonly string[] ImGuiOnlyBarPanels = - { Panels.InventoryFace.Title, Panels.SkillsFace.Title, Panels.SenseFace.Title, Panels.ItemCountFace.Title, Panels.MiniRemoteFace.Title, + { Panels.InventoryFace.Title, Panels.SkillsFace.Title, Panels.SenseFace.Title, Panels.MiniRemoteFace.Title, Panels.CharactersFace.Title }; + /// An ImGui-only panel's bar button is wanted: it has a face, and Skills only while Oracle can't host it. + private static bool ImGuiOnlyWanted(string title) => + ImGuiPanelHost.HasFace(title) + && (title != Panels.SkillsFace.Title || Panels.SkillsRouting.ShowSkillsBarIcon); + // The ILT section: ImGui-only Infinite Leaftide panels (Bounties and Guardian, both RynthILT's). // They never get buttons of their own; one ILT button stands for them, shown only on Infinite // Leaftide (IltInfo.IsIlt) with RynthILT loaded (IltInfo.PluginLoaded), and only for the ones @@ -726,12 +734,12 @@ internal static class ImGuiBar ImGuiNET.ImGui.PopStyleVar(3); } - /// Bit i set: ImGuiOnlyBarPanels[i] has a face now. + /// Bit i set: ImGuiOnlyBarPanels[i] gets a button now (a face, and for Skills no Oracle tabs). private static int ImGuiOnlyMask() { int mask = 0; for (int i = 0; i < ImGuiOnlyBarPanels.Length; i++) - if (ImGuiPanelHost.HasFace(ImGuiOnlyBarPanels[i])) mask |= 1 << i; + if (ImGuiOnlyWanted(ImGuiOnlyBarPanels[i])) mask |= 1 << i; return mask; } @@ -755,7 +763,7 @@ internal static class ImGuiBar list.Add(new ButtonInfo(title, "##bar_" + title, icon, letter, title)); } foreach (string title in ImGuiOnlyBarPanels) - if (ImGuiPanelHost.HasFace(title) && !LauncherOnly.Contains(title)) + if (ImGuiOnlyWanted(title) && !LauncherOnly.Contains(title)) { string icon = IconFor(title, out bool letter); list.Add(new ButtonInfo(title, "##bar_" + title, icon, letter, title)); diff --git a/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs b/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs index 676b110..04eed1c 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs @@ -459,6 +459,7 @@ internal static class ImGuiPanelHost Apply(req.Title, req.Kind, placeScale); RemoveUnregistered(); SweepEmbedded(); + Panels.OracleSkillsEmbed.Sweep(Environment.TickCount64); // Oracle's Skills embed that stopped drawing List order; lock (Sync) order = DrawOrder; @@ -512,6 +513,8 @@ internal static class ImGuiPanelHost { if (_restored) return; _restored = true; + // Settings > Display "Remember Open Windows and Positions" (default on). + if (!Plugins.EngineSettings.RememberWindowLayout) return; List titles = new(); // Script windows (dynamic) open when their owner says so, not from the saved state. lock (Sync) diff --git a/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs b/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs index d2e24a0..531f604 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs @@ -16,7 +16,9 @@ // so copy is mouse-driven). Right-click a line to copy it or to make a rule // from it: move / copy lines like it to a tab, hide them, colour them. A line // with map coordinates in it ("42.1N, 33.6E") also offers "Arrow to" and "Go -// to" them, sent to RynthNav (UI/Data/ChatCoords.cs finds them). +// to" them, sent to RynthNav (UI/Data/ChatCoords.cs finds them). The +// coordinates are also drawn as underlined links: click points RynthNav's +// arrow there (its overlay opens), Ctrl+click walks there. // Follows the newest line until you scroll up; the scroll for new lines is set // in the same frame they're drawn (DrawLines; until 2026-10-11 it landed a frame // late and the text bounced). Scrolled up, the view holds still. The history is @@ -584,10 +586,18 @@ internal sealed class ChatFace : IImGuiPanel dl.AddText(font, font.FontSize, tp, col, line.Text, textW); else foreach (Seg seg in lay.Segs) + { dl.AddText(font, font.FontSize, tp + seg.Offset, seg.Argb == 0 ? col : RynthTheme.Argb(seg.Argb), seg.Text); + if (seg.Link >= 0) // a map coordinate: underlined, it's clickable + { + Vector2 u = tp + seg.Offset + new Vector2(0, font.FontSize - 1); + dl.AddLine(u, u + new Vector2(seg.W, 0), RynthTheme.Argb(LinkCol), 1f); + } + } } ImGuiNET.ImGui.Dummy(new Vector2(wrapW, Math.Max(1, total))); - HandleSelection(basePos, wrapW, scrollY, viewH, n); + HoverLink(basePos, tsW, n, out ChatCoord? hoveredLink); + HandleSelection(basePos, wrapW, scrollY, viewH, n, hoveredLink); HandleLineMenu(basePos, wrapW, n); _lastScrollY = scrollY; @@ -675,7 +685,17 @@ internal sealed class ChatFace : IImGuiPanel { ChatLine line = _vis[i]; ChatSpan[]? spans = line.Route.Spans; - if (spans != null) + // Map coordinates ("82.3N, 34.2E") become links. Found here, when the line is measured, + // never per frame; a line without any keeps the plain (or highlighted) path. + List coords = ChatCoords.MayHaveCoords(line.Text) ? ChatCoords.Find(line.Text) : NoCoords; + if (coords.Count > 0) + { + ChatSpan[] withLinks = ChatCoords.LinkSpans(spans, coords, LinkCol); + SpanLayout lay = LayoutSpans(font, line.Text, withLinks, textW, coords); + _lay[i] = lay; + _h[i] = lay.Height; + } + else if (spans != null) { SpanLayout lay = LayoutSpans(font, line.Text, spans, textW); _lay[i] = lay; @@ -705,21 +725,40 @@ internal sealed class ChatFace : IImGuiPanel // ── Highlighted lines: hand layout ─────────────────────────────────── - private readonly record struct Seg(string Text, Vector2 Offset, uint Argb); // Argb 0 = the line's colour + // Argb 0 = the line's colour. W: the run's width. Link: index into SpanLayout.Links (a map + // coordinate drawn as a link: click = RynthNav arrow, Ctrl+click = go), -1 for plain text. + private readonly record struct Seg(string Text, Vector2 Offset, uint Argb, float W = 0f, int Link = -1); private sealed class SpanLayout { public required float Height; public required Seg[] Segs; + /// The line's map coordinates (ChatCoords), when any are drawn as links. + public ChatCoord[]? Links; } + /// Coordinate links in chat lines: soft teal, underlined (0xAARRGGBB, like ChatSpan.Argb). + private const uint LinkCol = 0xFF5ECFE0; + + private static readonly List NoCoords = new(); + /// /// Word-wraps to and cuts each /// row where a highlight starts or ends, so every run is drawn in its own /// colour. Called when a line is measured, never per frame. + /// : the line's map coordinates, whose runs get a link index. /// - private static SpanLayout LayoutSpans(ImFontPtr font, string text, ChatSpan[] spans, float wrapW) + private static SpanLayout LayoutSpans(ImFontPtr font, string text, ChatSpan[] spans, float wrapW, List? links = null) { + // Which coordinate link a run [s0, s1) belongs to (-1 none). + int LinkOf(int s0, int s1) + { + if (links == null) return -1; + for (int k = 0; k < links.Count; k++) + if (s0 >= links[k].Start && s1 <= links[k].Start + links[k].Length) return k; + return -1; + } + float size = font.FontSize; float Width(int start, int end) => end <= start ? 0 : font.CalcTextSizeA(size, float.MaxValue, 0f, text[start..end]).X; @@ -776,13 +815,14 @@ internal sealed class ChatFace : IImGuiPanel int s0 = Math.Max(span.Start, a), s1 = Math.Min(span.Start + span.Length, b); if (s1 <= s0) continue; if (s0 > c) { segs.Add(new Seg(text[c..s0], new Vector2(sx, y), 0)); sx += Width(c, s0); } - segs.Add(new Seg(text[s0..s1], new Vector2(sx, y), span.Argb)); - sx += Width(s0, s1); + float spanW = Width(s0, s1); + segs.Add(new Seg(text[s0..s1], new Vector2(sx, y), span.Argb, spanW, LinkOf(s0, s1))); + sx += spanW; c = s1; } if (c < b) segs.Add(new Seg(text[c..b], new Vector2(sx, y), 0)); } - return new SpanLayout { Height = Math.Max(1, rows.Count) * size, Segs = segs.ToArray() }; + return new SpanLayout { Height = Math.Max(1, rows.Count) * size, Segs = segs.ToArray(), Links = links?.ToArray() }; } /// Index of the line containing content y (clamped to the list). @@ -797,7 +837,53 @@ internal sealed class ChatFace : IImGuiPanel return Math.Min(lo, Math.Max(0, n - 1)); } - private void HandleSelection(Vector2 basePos, float wrapW, float scrollY, float viewH, int n) + /// + /// The map coordinate link under the mouse, if any (hand cursor and a tooltip). Only the + /// hovered line's runs are looked at. + /// + private void HoverLink(Vector2 basePos, float tsW, int n, out ChatCoord? link) + { + link = null; + if (n == 0 || _selDragging || !ImGuiNET.ImGui.IsWindowHovered()) return; + Vector2 mouse = ImGuiNET.ImGui.GetMousePos(); + float contentY = mouse.Y - basePos.Y; + if (contentY < 0 || contentY >= _tops[n]) return; + int i = FirstAtOrBelow(contentY, n); + if (_lay[i] is not { Links: { Length: > 0 } links } lay) return; + Vector2 tp = basePos + new Vector2(3 + tsW, _tops[i]); + float h = ImGuiNET.ImGui.GetFontSize(); + foreach (Seg seg in lay.Segs) + { + if (seg.Link < 0 || seg.Link >= links.Length) continue; + Vector2 a = tp + seg.Offset, b = a + new Vector2(seg.W, h); + if (mouse.X < a.X || mouse.X >= b.X || mouse.Y < a.Y || mouse.Y >= b.Y) continue; + link = links[seg.Link]; + ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand); + bool nav = ImGuiPanelHost.HasFace(RynthNavFace.Title); + SafeImGui.SetTooltip(nav + ? $"Click: point the arrow at {link.Value.Text}\nCtrl+click: RynthNav walks there\nRight-click: more" + : $"{link.Value.Text}\n(RynthNav isn't loaded: no arrow)"); + return; + } + } + + /// A click on a coordinate link: RynthNav's arrow there, or (Ctrl) walk there. + private void ClickLink(ChatCoord c) + { + if (!ImGuiPanelHost.HasFace(RynthNavFace.Title)) { Flash("RynthNav isn't loaded", 1.5); return; } + if (ImGuiNET.ImGui.GetIO().KeyCtrl) + { + RynthNavCommands.Go(c.Text, c.Ns, c.Ew); + Flash("Going to " + c.Text, 1.5); + } + else + { + RynthNavCommands.Arrow(c.Text, c.Ns, c.Ew); + Flash("Arrow: " + c.Text, 1.5); + } + } + + private void HandleSelection(Vector2 basePos, float wrapW, float scrollY, float viewH, int n, ChatCoord? hoveredLink = null) { if (n == 0) { ClearSelection(); return; } Vector2 mouse = ImGuiNET.ImGui.GetMousePos(); @@ -814,6 +900,7 @@ internal sealed class ChatFace : IImGuiPanel _selDragging = true; _selMoved = false; _selDown = mouse; + _downLink = hoveredLink; // a click (no drag) on it acts on release return; } @@ -827,8 +914,15 @@ internal sealed class ChatFace : IImGuiPanel if (ImGuiNET.ImGui.IsMouseDown(ImGuiMouseButton.Left)) return; _selDragging = false; - // A drag (even within one line) copies; a plain click just clears. - if (!_selMoved && _selEnd == _selAnchor) { ClearSelection(); return; } + // A drag (even within one line) copies; a plain click just clears, or follows a + // coordinate link it was pressed on. + if (!_selMoved && _selEnd == _selAnchor) + { + ChatCoord? link = _downLink; + ClearSelection(); + if (link is { } c) ClickLink(c); + return; + } int lo = Math.Min(_selAnchor, _selEnd), hi = Math.Max(_selAnchor, _selEnd); var parts = new List(hi - lo + 1); for (int i = lo; i <= hi && i < _vis.Count; i++) parts.Add(CopyText(_vis[i])); @@ -855,8 +949,12 @@ internal sealed class ChatFace : IImGuiPanel { _selAnchor = _selEnd = -1; _selDragging = _selMoved = false; + _downLink = null; } + /// The coordinate link the left button went down on (acted on if it comes up without a drag). + private ChatCoord? _downLink; + // ── Input ──────────────────────────────────────────────────────────── private void DrawInput(Vector2 p, float w, float h) diff --git a/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs b/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs index 68b6ebb..3235253 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs @@ -196,6 +196,15 @@ internal sealed class ChatFiltersFace : IImGuiPanel Label("Checked after the rules above, only for lines no rule moved or hid.", Mute); Label("Tick to hide the lines; pick a tab to move them there instead.", Mute); ImGuiNET.ImGui.PopFont(); + bool retail = ChatModel.HideInRetailChat; + if (ImGuiNET.ImGui.Checkbox("Hidden lines are hidden in the retail chat too##hideretail", ref retail)) + { + ChatModel.HideInRetailChat = retail; + ChatModel.SaveSettings(); + } + SafeImGui.SetItemTooltip("On: a line a rule or standard filter hides doesn't print in AC's own chat window either.\n" + + "Off: hiding only applies to RynthChat; the retail chat shows everything.\n" + + "Moved / copied lines still show in the retail chat either way."); foreach (string group in UI.Panels.RynthChatPresets.Groups) { int on = 0, total = 0; diff --git a/src/RynthCore.Engine/ImGui/Panels/DamageDetailFace.cs b/src/RynthCore.Engine/ImGui/Panels/DamageDetailFace.cs index ffd80ef..24b1643 100644 --- a/src/RynthCore.Engine/ImGui/Panels/DamageDetailFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/DamageDetailFace.cs @@ -409,6 +409,28 @@ internal sealed class DamageDetailFace : IImGuiPanel pick => DamageCommands.EditRule(name, r => r.ExVuln = pick), "A vulnerability of another element, on top of Vuln (which follows the attack's element)."); + // Melee/missile attack power against it + string power = string.IsNullOrEmpty(view.AttackPower) ? "Default" : view.AttackPower; + Combo("Power", "##power", DamageCommands.AttackPowerModes, power, + pick => DamageCommands.EditRule(name, r => r.AttackPower = pick), + (isDefault + ? "Melee/missile attack power for every monster without its own. Default = the Power settings (Melee Combat).\n" + : "Melee/missile attack power against the monsters it covers. Default = the DEFAULT line's.\n") + + "High = 100%. Reckless = 80% (needs Recklessness trained, else 100%).\n" + + "Variable = a new random power each attack, between Variable Min and Max (Settings).\n" + + "Reckless + Variable = random, kept inside the Recklessness band (20-80%)."); + + // Pull-away kite: tag then run until the mob is clear of its spawn pack + ImGuiNET.ImGui.SameLine(0, 14); + string kite = string.IsNullOrEmpty(view.Kite) ? "Default" : view.Kite; + Combo("Kite", "##kite", DamageCommands.KiteModes, kite, + pick => DamageCommands.EditRule(name, r => r.Kite = pick), + (isDefault + ? "Pull-away for every monster without its own. Default = Off (fight in place).\n" + : "Pull-away for the monsters it covers. Default = the DEFAULT line's.\n") + + "Off = kill where it stands. PullAway = tag, run until it has been dragged\n" + + "Kite Pull Distance metres from its lock spot (Settings > Melee Combat), then kill."); + // The DEFAULT line's own choice is the Prefer chip in the Damage panel's top bar. if (!isDefault) Combo("Prefer", "##prefer", DamageCommands.PreferredDamages, string.IsNullOrEmpty(view.PreferredDamage) ? "Auto" : view.PreferredDamage, diff --git a/src/RynthCore.Engine/ImGui/Panels/FaceKit.cs b/src/RynthCore.Engine/ImGui/Panels/FaceKit.cs index 4ca8656..1421f87 100644 --- a/src/RynthCore.Engine/ImGui/Panels/FaceKit.cs +++ b/src/RynthCore.Engine/ImGui/Panels/FaceKit.cs @@ -222,17 +222,26 @@ internal static class FaceKit /// /// One popup list per face, opened from any button: call Open from the /// button's click and Draw once per frame at the end of the face's Draw - /// (outside any child window, so the popup id always matches). + /// (outside any child window, so the popup id always matches). Long lists + /// (Slayer Type's creature names, materials, long keys) get a type-to-filter + /// box so players can pick by name instead of scrolling. /// internal sealed class Picker { + /// Show the filter box when the list is at least this long. + private const int FilterAt = 12; + private const float FilterH = 22f; + private const float RowH = 20f; + private readonly string _popupId; + private readonly byte[] _filter = new byte[64]; private string[] _items = Array.Empty(); private int _selected = -1; private Action? _onPick; private Vector2 _pos; private float _width = 220; private bool _openRequested; + private bool _focusFilter; public Picker(string popupId) => _popupId = popupId; @@ -244,6 +253,8 @@ internal static class FaceKit _pos = below; _width = width; _openRequested = items.Length > 0; + _filter[0] = 0; // clear the previous open's filter + _focusFilter = items.Length >= FilterAt; } public void Draw() @@ -255,38 +266,74 @@ internal static class FaceKit ImGuiNET.ImGui.SetNextWindowPos(new Vector2(Math.Clamp(_pos.X, 0, Math.Max(0, display.X - _width)), _pos.Y)); ImGuiNET.ImGui.OpenPopup(_popupId); } + bool filterOn = _items.Length >= FilterAt; + string filterText = filterOn ? Utf8(_filter) : string.Empty; + // Count matches so the popup height tracks a short filtered list. + int shown = 0; + if (!filterOn) shown = _items.Length; + else + { + for (int i = 0; i < _items.Length; i++) + if (FilterMatch(_items[i], filterText)) shown++; + } + float listH = Math.Min(Math.Max(shown, 1) * RowH + 4, 340); + float totalH = listH + (filterOn ? FilterH + 4 : 0); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg); ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Border, Teal); ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.PopupRounding, 4f); ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(2, 2)); ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 1)); - ImGuiNET.ImGui.SetNextWindowSize(new Vector2(_width, Math.Min(_items.Length * 21 + 4, 340))); + ImGuiNET.ImGui.SetNextWindowSize(new Vector2(_width, totalH)); bool open = ImGuiNET.ImGui.BeginPopup(_popupId); ImGuiNET.ImGui.PopStyleVar(3); ImGuiNET.ImGui.PopStyleColor(2); if (!open) return; + + if (filterOn) + { + Vector2 fp = ImGuiNET.ImGui.GetCursorScreenPos(); + if (_focusFilter) + { + _focusFilter = false; + ImGuiNET.ImGui.SetKeyboardFocusHere(0); // next widget = the filter box + } + TextBox("##pick_filter", _filter, fp, ImGuiNET.ImGui.GetContentRegionAvail().X, "Type to filter...", out _, + ImGuiInputTextFlags.None, FilterH); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(fp.X, fp.Y + FilterH + 2)); + filterText = Utf8(_filter); + } + var dl = ImGuiNET.ImGui.GetWindowDrawList(); float iw = ImGuiNET.ImGui.GetContentRegionAvail().X; for (int i = 0; i < _items.Length; i++) { + if (filterOn && !FilterMatch(_items[i], filterText)) continue; ImGuiNET.ImGui.PushID(i); Vector2 ip = ImGuiNET.ImGui.GetCursorScreenPos(); - bool click = ImGuiNET.ImGui.InvisibleButton("##it", new Vector2(iw, 20)); + bool click = ImGuiNET.ImGui.InvisibleButton("##it", new Vector2(iw, RowH)); bool hot = ImGuiNET.ImGui.IsItemHovered(); ImGuiNET.ImGui.PopID(); bool sel = i == _selected; - dl.AddRectFilled(ip, ip + new Vector2(iw, 20), sel ? Selected : hot ? Lighten(BtnFill) : BtnFill); - dl.AddRect(ip, ip + new Vector2(iw, 20), BtnBord); - dl.AddText(ip + new Vector2(6, (20 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), sel ? Teal : Text, _items[i]); + dl.AddRectFilled(ip, ip + new Vector2(iw, RowH), sel ? Selected : hot ? Lighten(BtnFill) : BtnFill); + dl.AddRect(ip, ip + new Vector2(iw, RowH), BtnBord); + dl.AddText(ip + new Vector2(6, (RowH - ImGuiNET.ImGui.GetFontSize()) * 0.5f), sel ? Teal : Text, _items[i]); if (click) { Action? act = _onPick; ImGuiNET.ImGui.CloseCurrentPopup(); - act?.Invoke(i); + act?.Invoke(i); // still the original index for the caller } } ImGuiNET.ImGui.EndPopup(); } + + /// Case-insensitive substring match; empty filter shows everything. + private static bool FilterMatch(string item, string filter) + { + if (filter.Length == 0) return true; + return item.IndexOf(filter, StringComparison.OrdinalIgnoreCase) >= 0; + } } // ── Text buffers ───────────────────────────────────────────────────── diff --git a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs index 8b60e2d..229a097 100644 --- a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs +++ b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs @@ -16,7 +16,9 @@ // 25 px title band isn't stretched) follow AcClientReborn's InventoryGeometry. // Credit: OpenAC (Tom's project) for the layout and sprite research. // -// title retail title bar "Inventory of ", tool toggles, close +// title retail title bar "Inventory of ", Vault, Remote / Sort / Count / +// GInv (text, icons or one menu: InventoryTitleLayout), size / tools / +// Modern toggles, close // tools search, sort, category chips (toggle, the funnel in the title) // paperdoll the 24 equip slots at their retail places (the 3D figure isn't // drawn, so the retail "Slots" view is always on) @@ -134,6 +136,10 @@ internal sealed partial class InventoryFace private string? _hoverLabel, _hoverLabel2; private string _titleText = "Inventory"; private string? _titleFor; + // The title cut to its room (InventoryTitleLayout.Elide), kept while the text and the room stay the same. + private string _titleCut = string.Empty; + private string? _titleCutFor; + private float _titleCutRoom, _titleCutW; // ===================================================================== // Body @@ -230,71 +236,128 @@ internal sealed partial class InventoryFace dl.AddRect(o, o + new Vector2(barW, h - 1), Gold, 4); } - // Two toggles at the bar's right end: the tools row and the Modern look. - float btn = MathF.Round(18 * s); - var b2 = new Vector2(o.X + barW - 8 * s - btn, o.Y + (h - btn) * 0.5f); - var b1 = new Vector2(b2.X - btn - 2 * s, b2.Y); - var bPlus = new Vector2(b1.X - btn - 6 * s, b2.Y); - var bMinus = new Vector2(bPlus.X - btn - 2 * s, b2.Y); - if (TitleToggle("##inv_smaller", PhosphorIcons.Minus, bMinus, btn, false)) - InventorySettingsStore.StepSize(-1); - SafeImGui.SetItemTooltip($"Smaller ({InventorySettingsStore.SizePct}%)"); - if (TitleToggle("##inv_bigger", PhosphorIcons.Plus, bPlus, btn, false)) - InventorySettingsStore.StepSize(+1); - SafeImGui.SetItemTooltip($"Bigger ({InventorySettingsStore.SizePct}%)"); - if (TitleToggle("##inv_tools", PhosphorIcons.Funnel, b1, btn, InventorySettingsStore.ShowTools)) - { - // Closing the search / filter row shows every item again. - if (InventorySettingsStore.ShowTools) ClearFilters(); - InventorySettingsStore.SetShowTools(!InventorySettingsStore.ShowTools); - } - ImGuiNET.ImGui.SetItemTooltip("Search, sort and filter"); - if (TitleToggle("##inv_modern", PhosphorIcons.SquaresFour, b2, btn, false)) - InventorySettingsStore.SetClassic(false); - ImGuiNET.ImGui.SetItemTooltip("Modern look"); - - // Vault (Aelrynth only): the contents area shows the account vault instead of the open pack. - float leftmost = bMinus.X; - if (VaultFeed.Available) - { - var vsz = new Vector2(MathF.Round(38 * s), btn); - var bV = new Vector2(bMinus.X - vsz.X - 8 * s, b2.Y); - if (TitleTextToggle("##inv_vault", "Vault", bV, vsz, _vaultOpen)) - { - _vaultOpen = !_vaultOpen; - if (_vaultOpen) VaultFeed.ViewOpened(); - } - ImGuiNET.ImGui.SetItemTooltip("Your Aelrynth account vault"); - leftmost = bV.X; - } - else - { - _vaultOpen = false; - } - - // Drag surface: the bar left of the toggles (moves the panel, like the header). - float dragW = Math.Max(1, leftmost - o.X - 2); - ImGuiNET.ImGui.SetCursorScreenPos(o); - ImGuiNET.ImGui.InvisibleButton("##inv_titledrag", new Vector2(dragW, h)); - ImGuiPanelHost.DragWindowWithLastItem(); - - // "Inventory of ", centred on the bar (left of the toggles when it's narrow). + // "Inventory of ": its width decides how much room the layout owes the title. if (!ReferenceEquals(_titleFor, view.PlayerName)) { _titleFor = view.PlayerName; _titleText = view.PlayerName.Length > 0 ? "Inventory of " + view.PlayerName : "Inventory"; } ImFontPtr f = ImGuiFonts.Get(UiFont.UiBold11); - ImGuiNET.ImGui.PushFont(f); - Vector2 ts = ImGuiNET.ImGui.CalcTextSize(_titleText); - ImGuiNET.ImGui.PopFont(); float titlePx = 12 * s; - ts *= titlePx / f.FontSize; - float tx = o.X + (barW - ts.X) * 0.5f; - if (tx + ts.X > leftmost - 4) tx = Math.Max(o.X + 10 * s, leftmost - 4 - ts.X); - dl.PushClipRect(o + new Vector2(6 * s, 0), new Vector2(leftmost - 2, o.Y + h), true); - dl.AddText(f, titlePx, new Vector2(tx, o.Y + (h - ts.Y) * 0.5f), White, _titleText); - dl.PopClipRect(); + float titleK = titlePx / f.FontSize; + ImGuiNET.ImGui.PushFont(f); + Vector2 ts = ImGuiNET.ImGui.CalcTextSize(_titleText) * titleK; + ImGuiNET.ImGui.PopFont(); + + // Where everything goes (UI/InventoryTitleLayout, tested): the four toggles at the right end, Vault + // next to them (always there on a vault server), then the related-panel buttons as text, as icons or + // as one "more" menu, whichever leaves the title its room. Nothing lands off the panel. + InventoryTitleLayout lay = InventoryTitleLayout.Compute(barW, s, VaultFeed.Available, ts.X); + float btn = lay.Btn; + float by = o.Y + (h - btn) * 0.5f; + Vector2 At(TitleSlot sl) => new(o.X + sl.X, by); + + if (TitleToggle("##inv_smaller", PhosphorIcons.Minus, At(lay.Smaller), btn, false)) + InventorySettingsStore.StepSize(-1); + SafeImGui.SetItemTooltip($"Smaller ({InventorySettingsStore.SizePct}%)"); + if (TitleToggle("##inv_bigger", PhosphorIcons.Plus, At(lay.Bigger), btn, false)) + InventorySettingsStore.StepSize(+1); + SafeImGui.SetItemTooltip($"Bigger ({InventorySettingsStore.SizePct}%)"); + if (TitleToggle("##inv_tools", PhosphorIcons.Funnel, At(lay.Tools), btn, InventorySettingsStore.ShowTools)) + { + // Closing the search / filter row shows every item again. + if (InventorySettingsStore.ShowTools) ClearFilters(); + InventorySettingsStore.SetShowTools(!InventorySettingsStore.ShowTools); + } + ImGuiNET.ImGui.SetItemTooltip("Search, sort and filter"); + if (TitleToggle("##inv_modern", PhosphorIcons.SquaresFour, At(lay.Modern), btn, false)) + InventorySettingsStore.SetClassic(false); + ImGuiNET.ImGui.SetItemTooltip("Modern look"); + + // Vault (Aelrynth only): the contents area shows the account vault instead of the open pack. + if (lay.Vault.Present) + { + if (TitleTextToggle("##inv_vault", "Vault", At(lay.Vault), new Vector2(lay.Vault.W, btn), _vaultOpen)) + { + _vaultOpen = !_vaultOpen; + if (_vaultOpen) VaultFeed.ViewOpened(); + } + ImGuiNET.ImGui.SetItemTooltip("Your Aelrynth account vault"); + } + else if (!VaultFeed.Available) + { + _vaultOpen = false; + } + + // Related panels: Mini Remote, RynthSort, Item Count, Global Inventory. + switch (lay.Mode) + { + case TitleExtrasMode.Text: + if (TitleTextToggle("##inv_miniremote", "Remote", At(lay.Remote), new Vector2(lay.Remote.W, btn), MiniRemoteOpen)) + ToggleMiniRemote(); + SafeImGui.SetItemTooltip(MiniRemoteTip); + if (TitleTextToggle("##inv_rsort", "Sort", At(lay.Sort), new Vector2(lay.Sort.W, btn), RynthSortOpen)) + ToggleRynthSort(); + SafeImGui.SetItemTooltip(RynthSortTip()); + if (TitleTextToggle("##inv_itemcount", "Count", At(lay.Count), new Vector2(lay.Count.W, btn), ItemCountOpen)) + ToggleItemCount(); + SafeImGui.SetItemTooltip(ItemCountTip); + if (TitleTextToggle("##inv_ginv", "GInv", At(lay.GInv), new Vector2(lay.GInv.W, btn), GlobalInventoryOpen)) + ToggleGlobalInventory(); + SafeImGui.SetItemTooltip(GlobalInventoryTip()); + break; + case TitleExtrasMode.Icons: + if (TitleToggle("##inv_miniremote", PhosphorIcons.SlidersHorizontal, At(lay.Remote), btn, MiniRemoteOpen)) + ToggleMiniRemote(); + SafeImGui.SetItemTooltip(MiniRemoteTip); + if (TitleToggle("##inv_rsort", PhosphorIcons.SortAscending, At(lay.Sort), btn, RynthSortOpen)) + ToggleRynthSort(); + SafeImGui.SetItemTooltip(RynthSortTip()); + if (TitleToggle("##inv_itemcount", PhosphorIcons.Bag, At(lay.Count), btn, ItemCountOpen)) + ToggleItemCount(); + SafeImGui.SetItemTooltip(ItemCountTip); + if (TitleToggle("##inv_ginv", PhosphorIcons.GlobeHemisphereWest, At(lay.GInv), btn, GlobalInventoryOpen)) + ToggleGlobalInventory(); + SafeImGui.SetItemTooltip(GlobalInventoryTip()); + break; + case TitleExtrasMode.Menu: + if (TitleToggle("##inv_more", PhosphorIcons.DotsThree, At(lay.More), btn, + MiniRemoteOpen || RynthSortOpen || ItemCountOpen || GlobalInventoryOpen)) + _openMore = true; + ImGuiNET.ImGui.SetItemTooltip("Mini Remote, RynthSort, Item Count, Global Inventory"); + break; + } + RelatedMenu(); + + // Drag surface: the bar left of the buttons (moves the panel, like the header). + float dragW = Math.Max(1, lay.LeftmostX - 2); + ImGuiNET.ImGui.SetCursorScreenPos(o); + ImGuiNET.ImGui.InvisibleButton("##inv_titledrag", new Vector2(dragW, h)); + ImGuiPanelHost.DragWindowWithLastItem(); + + // The title: centred on the bar when it fits, else against the left edge and cut with "...". + float room = lay.TitleWidth - 4 * s; + if (room >= 1) + { + string shown = _titleText; + if (ts.X > room) + { + if (!ReferenceEquals(_titleCutFor, _titleText) || _titleCutRoom != room) + { + CutTitle(f, titleK, room); + } + shown = _titleCut; + ts.X = _titleCutW; + } + if (shown.Length > 0) + { + float left = o.X + lay.TitleLeft + 4 * s; + float tx = Math.Clamp(o.X + (barW - ts.X) * 0.5f, left, Math.Max(left, o.X + lay.TitleRight - ts.X)); + dl.PushClipRect(o + new Vector2(lay.TitleLeft, 0), new Vector2(o.X + lay.TitleRight, o.Y + h), true); + dl.AddText(f, titlePx, new Vector2(tx, o.Y + (h - ts.Y) * 0.5f), White, shown); + dl.PopClipRect(); + } + } // The retail close button. var cp = new Vector2(o.X + barW, o.Y); @@ -310,6 +373,17 @@ internal sealed partial class InventoryFace } } + /// Cuts the title text to px (only when it changed): _titleCut and its width. + private void CutTitle(ImFontPtr font, float k, float room) + { + ImGuiNET.ImGui.PushFont(font); + _titleCut = InventoryTitleLayout.Elide(_titleText, room, t => ImGuiNET.ImGui.CalcTextSize(t).X * k); + _titleCutW = _titleCut.Length == 0 ? 0 : ImGuiNET.ImGui.CalcTextSize(_titleCut).X * k; + ImGuiNET.ImGui.PopFont(); + _titleCutFor = _titleText; + _titleCutRoom = room; + } + private static bool TitleToggle(string id, string glyph, Vector2 pos, float size, bool on) { ImGuiNET.ImGui.SetCursorScreenPos(pos); @@ -640,6 +714,45 @@ internal sealed partial class InventoryFace private VaultItem? _vaultCtx; private bool _openVaultCtx; + /// The vault view's caption: how full it is, or the read's status before the first read. + private static string VaultCaption(VaultSnapshot? snap) + { + if (snap == null) return VaultFeed.Status; + int n = snap.Items.Length; + return snap.Max > 0 ? $"Aelrynth Vault: {n:N0} of {snap.Max:N0}" : $"Aelrynth Vault: {n:N0}"; + } + + /// What the vault view says before it has been read. + private static string VaultEmptyText => VaultFeed.Unsupported ? "The vault is not open on this server yet." : "Click Refresh to read the vault."; + + /// + /// The vault's right-click menu (both looks): Withdraw the item. Call it in the panel's own window + /// (not inside a child), so the popup opened and drawn here share one ID. + /// + private void VaultContextMenu() + { + if (_openVaultCtx) + { + _openVaultCtx = false; + ImGuiNET.ImGui.OpenPopup("##vault_ctx"); + } + PushMenuStyle(); + if (ImGuiNET.ImGui.BeginPopup("##vault_ctx")) + { + VaultItem? it = _vaultCtx; + if (it == null) ImGuiNET.ImGui.CloseCurrentPopup(); + else + { + SafeImGui.TextDisabled(it.Name); + ImGuiNET.ImGui.Separator(); + if (ImGuiNET.ImGui.MenuItem("Withdraw", "", false, VaultFeed.Available)) + VaultFeed.Withdraw(it); + } + ImGuiNET.ImGui.EndPopup(); + } + PopMenuStyle(); + } + /// A small labelled button in the title bar. private static bool TitleTextToggle(string id, string label, Vector2 pos, Vector2 size, bool on) { @@ -671,9 +784,7 @@ internal sealed partial class InventoryFace VaultSnapshot? snap = VaultFeed.Snapshot; VaultItem[] items = snap?.Items ?? Array.Empty(); int cells = snap == null ? 0 : Math.Max(snap.Max, items.Length); - string caption = snap == null ? VaultFeed.Status - : snap.Max > 0 ? $"Aelrynth Vault: {items.Length:N0} of {snap.Max:N0}" : $"Aelrynth Vault: {items.Length:N0}"; - CenterText(dl, ImGuiFonts.Get(UiFont.Ui14), caption, new Vector2(gridPos.X, field.Y), new Vector2(gridW, 15 * s), White, 12 * s); + CenterText(dl, ImGuiFonts.Get(UiFont.Ui14), VaultCaption(snap), new Vector2(gridPos.X, field.Y), new Vector2(gridW, 15 * s), White, 12 * s); // Read again (the vault changes when anything is deposited or withdrawn). var rb = new Vector2(gridPos.X + gridW - 44 * s, field.Y + 1 * s); @@ -738,29 +849,10 @@ internal sealed partial class InventoryFace } else if (snap == null && !VaultFeed.Awaiting) { - dl.AddText(gridPos + new Vector2(4, 22 * s), Mute, VaultFeed.Unsupported ? "The vault is not open on this server yet." : "Click Refresh to read the vault."); + dl.AddText(gridPos + new Vector2(4, 22 * s), Mute, VaultEmptyText); } - if (_openVaultCtx) - { - _openVaultCtx = false; - ImGuiNET.ImGui.OpenPopup("##vault_ctx"); - } - PushMenuStyle(); - if (ImGuiNET.ImGui.BeginPopup("##vault_ctx")) - { - VaultItem? it = _vaultCtx; - if (it == null) ImGuiNET.ImGui.CloseCurrentPopup(); - else - { - SafeImGui.TextDisabled(it.Name); - ImGuiNET.ImGui.Separator(); - if (ImGuiNET.ImGui.MenuItem("Withdraw", "", false, VaultFeed.Available)) - VaultFeed.Withdraw(it); - } - ImGuiNET.ImGui.EndPopup(); - } - PopMenuStyle(); + VaultContextMenu(); if (snap != null) // nothing to scroll before the vault has been read Scrollbar("##inv_vaultsb", new Vector2(gridPos.X + gridW, gridPos.Y), rows * cell, s, ref _vaultFirstRow, totalRows, rows); diff --git a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs index 6e0ebec..feb1f9c 100644 --- a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs @@ -6,7 +6,11 @@ // pictures (InventoryFace.Classic.cs; Phase 2) // Modern the Phase 1 layout, below // -// header burden (percent of capacity) and pyreals; item count +// header burden (percent of capacity) and pyreals; item count; buttons for +// Mini Remote, RynthSort (/rsort), Item Count (/rc itemcount) and +// Global Inventory (/ginv), folded into one menu when the header is short; +// on Aelrynth also the Vault (always there; the grid shows the account +// vault, picking a pack goes back) // tools search box, attribute filter (InventoryFace.AttrFilter.cs), sort // picker; category chips // packs All, Main pack, each side pack (its icon and fill), Worn @@ -36,6 +40,8 @@ using System.Globalization; using System.Numerics; using ImGuiNET; using RynthCore.Engine.Compatibility; +using RynthCore.Engine.Net; +using RynthCore.Engine.UI; using RynthCore.Engine.UI.ScriptWindows; using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; @@ -201,12 +207,99 @@ internal sealed partial class InventoryFace : IImGuiPanel float bodyH = Math.Max(60, origin.Y + size.Y - 6 - bottomH - bodyPos.Y); float colW = w >= 380 ? 128 : 46; PackColumn(view, bodyPos, colW, bodyH); - Grid(new Vector2(bodyPos.X + colW + 4, bodyPos.Y), new Vector2(w - colW - 4, bodyH)); + // The Vault (Aelrynth) takes the grid's place; picking a pack in the column goes back to it. + if (_vaultOpen && (!VaultFeed.Available || _pack != _vaultOpenedOnPack)) _vaultOpen = false; + if (_vaultOpen) ModernVault(new Vector2(bodyPos.X + colW + 4, bodyPos.Y), new Vector2(w - colW - 4, bodyH)); + else Grid(new Vector2(bodyPos.X + colW + 4, bodyPos.Y), new Vector2(w - colW - 4, bodyH)); ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(bodyPos.X, bodyPos.Y + bodyH + 4)); Zones(view, w); StatusRow(w); } + /// RynthInventory's Global Inventory script window key (UiWindow "RynthInventory/Main"). + private const string GlobalInventoryKey = "RynthInventory/Main"; + /// RynthSort's script window key (UiWindow "RynthSort/Main"). + private const string RynthSortKey = "RynthSort/Main"; + + private static bool MiniRemoteOpen => ImGuiPanelHost.IsOpen(MiniRemoteFace.Title); + private static bool ItemCountOpen => ImGuiPanelHost.IsOpen(ItemCountFace.Title); + private static bool RynthSortOpen => ScriptWindowRegistry.IsOpen(RynthSortKey); + private static bool GlobalInventoryOpen => ScriptWindowRegistry.IsOpen(GlobalInventoryKey); + + private const string MiniRemoteTip = "Mini Remote (/rc miniremote): remote, sections and HUDs"; + private const string ItemCountTip = "Item Count (/rc itemcount): how many of each named item you carry"; + private static string RynthSortTip() => ScriptWindowRegistry.Has(RynthSortKey) + ? "RynthSort (/rsort): pack sort rules and auto-sort" + : "RynthSort (/rsort) - needs the RynthSort plugin"; + private static string GlobalInventoryTip() => ScriptWindowRegistry.Has(GlobalInventoryKey) + ? "Global Inventory (/ginv): every character's saved packs and storage" + : "Global Inventory (/ginv) - needs the RynthInventory plugin"; + + /// Opens or closes the Item Count panel (same as /rc itemcount). + private static void ToggleItemCount() + { + if (!ImGuiPanelHost.HasFace(ItemCountFace.Title)) return; + PanelRouter.Toggle(ItemCountFace.Title); + } + + /// Opens or closes the Mini Remote (same as /rc miniremote). + private static void ToggleMiniRemote() + { + if (!ImGuiPanelHost.HasFace(MiniRemoteFace.Title)) return; + PanelRouter.Toggle(MiniRemoteFace.Title); + } + + /// + /// Opens or closes a plugin script window by key, or runs + /// when the plugin hasn't submitted it yet. + /// + private static void ToggleScriptWindow(string key, string fallbackCmd) + { + if (ScriptWindowRegistry.Has(key)) + { + ScriptWindowRegistry.PlayerSetVisible(key, !ScriptWindowRegistry.IsOpen(key)); + return; + } + ServerMenus.Run(fallbackCmd); + } + + /// Opens or closes RynthInventory's Global Inventory (same as /ginv). + private static void ToggleGlobalInventory() => ToggleScriptWindow(GlobalInventoryKey, "/ginv"); + + /// Opens or closes RynthSort (same as /rsort). + private static void ToggleRynthSort() => ToggleScriptWindow(RynthSortKey, "/rsort"); + + // The "more" menu both looks use when their bar is too short for the four buttons. + private bool _openMore; + + /// The "more" popup: the four related panels as menu lines (checked while open). Draw where its button was. + private void RelatedMenu() + { + if (_openMore) + { + _openMore = false; + ImGuiNET.ImGui.OpenPopup("##inv_more_menu"); + } + PushMenuStyle(); + if (ImGuiNET.ImGui.BeginPopup("##inv_more_menu")) + { + if (ImGuiNET.ImGui.MenuItem("Mini Remote", "/rc miniremote", MiniRemoteOpen, ImGuiPanelHost.HasFace(MiniRemoteFace.Title))) + ToggleMiniRemote(); + SafeImGui.SetItemTooltip(MiniRemoteTip); + if (ImGuiNET.ImGui.MenuItem("RynthSort", "/rsort", RynthSortOpen)) + ToggleRynthSort(); + SafeImGui.SetItemTooltip(RynthSortTip()); + if (ImGuiNET.ImGui.MenuItem("Item Count", "/rc itemcount", ItemCountOpen, ImGuiPanelHost.HasFace(ItemCountFace.Title))) + ToggleItemCount(); + SafeImGui.SetItemTooltip(ItemCountTip); + if (ImGuiNET.ImGui.MenuItem("Global Inventory", "/ginv", GlobalInventoryOpen)) + ToggleGlobalInventory(); + SafeImGui.SetItemTooltip(GlobalInventoryTip()); + ImGuiNET.ImGui.EndPopup(); + } + PopMenuStyle(); + } + // ── Header: burden, pyreals, count ────────────────────────────────── private void Header(InventoryView view, float w) @@ -239,11 +332,62 @@ internal sealed partial class InventoryFace : IImGuiPanel InventorySettingsStore.SetClassic(true); ImGuiNET.ImGui.SetItemTooltip("Classic look (the retail inventory window)"); + // Related panels (Mini Remote, RynthSort, Item Count, Global Inventory): four icons when the room + // left of the Classic / Close buttons holds them, else one "more" menu, else none (the Character + // menu has them all). The item count text gives way last. On Aelrynth the Vault button sits next + // to the Classic button and takes its room first: it is never dropped + // (UI/InventoryTitleLayout.InventoryHeaderLayout, tested in tools/BarDeclutterTests). float cw = ImGuiNET.ImGui.CalcTextSize(_countText).X; - dl.AddText(new Vector2(tb.X - cw - 6, ty), Mute, _countText); + float leftEnd = x + 20 + ImGuiNET.ImGui.CalcTextSize(view.PyrealText).X + 6; + InventoryHeaderLayout hl = InventoryHeaderLayout.Compute(w, leftEnd - p.X, cw, VaultFeed.Available); + Vector2 At(TitleSlot s) => new(p.X + s.X, p.Y + 1); + var btn22 = new Vector2(InventoryHeaderLayout.Btn, InventoryHeaderLayout.Btn); + if (hl.Plan.Extras == TitleExtrasMode.Icons) + { + if (IconButton("##inv_ginv", PhosphorIcons.GlobeHemisphereWest, At(hl.GInv), btn22, + GlobalInventoryOpen ? Teal : Amber, BtnFill, font: UiFont.Ui11)) + ToggleGlobalInventory(); + SafeImGui.SetItemTooltip(GlobalInventoryTip()); + if (IconButton("##inv_itemcount", PhosphorIcons.Bag, At(hl.Count), btn22, + ItemCountOpen ? Teal : Amber, BtnFill, font: UiFont.Ui11)) + ToggleItemCount(); + SafeImGui.SetItemTooltip(ItemCountTip); + if (IconButton("##inv_rsort", PhosphorIcons.SortAscending, At(hl.Sort), btn22, + RynthSortOpen ? Teal : Amber, BtnFill, font: UiFont.Ui11)) + ToggleRynthSort(); + SafeImGui.SetItemTooltip(RynthSortTip()); + if (IconButton("##inv_miniremote", PhosphorIcons.SquaresFour, At(hl.Remote), btn22, + MiniRemoteOpen ? Teal : Amber, BtnFill, font: UiFont.Ui11)) + ToggleMiniRemote(); + SafeImGui.SetItemTooltip(MiniRemoteTip); + } + else if (hl.Plan.Extras == TitleExtrasMode.Menu) + { + if (IconButton("##inv_more", PhosphorIcons.DotsThree, At(hl.More), btn22, + MiniRemoteOpen || RynthSortOpen || ItemCountOpen || GlobalInventoryOpen ? Teal : Amber, BtnFill, font: UiFont.Ui11)) + _openMore = true; + ImGuiNET.ImGui.SetItemTooltip("Mini Remote, RynthSort, Item Count, Global Inventory"); + } + RelatedMenu(); + + // Vault (Aelrynth only): the grid shows the account vault instead of the packs. + if (hl.Plan.Vault) + { + if (IconButton("##inv_vault_m", PhosphorIcons.TreasureChest, At(hl.Vault), btn22, + _vaultOpen ? Teal : Amber, BtnFill, font: UiFont.Ui11)) + { + _vaultOpen = !_vaultOpen; + _vaultOpenedOnPack = _pack; + if (_vaultOpen) VaultFeed.ViewOpened(); + } + ImGuiNET.ImGui.SetItemTooltip("Your Aelrynth account vault"); + } + + if (hl.Plan.ShowCount) dl.AddText(new Vector2(p.X + hl.CountX, ty), Mute, _countText); + float countLeft = hl.Plan.ShowCount ? p.X + hl.CountX : p.X + hl.RightEdge; // Drag surface: the empty part of the header, between the pyreals and the count. - float dragFrom = x + 20 + ImGuiNET.ImGui.CalcTextSize(view.PyrealText).X + 6, dragTo = tb.X - cw - 10; + float dragFrom = leftEnd, dragTo = countLeft - 4; if (dragTo > dragFrom) { ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(dragFrom, p.Y)); @@ -612,6 +756,109 @@ internal sealed partial class InventoryFace : IImGuiPanel ImGuiNET.ImGui.PopStyleColor(); } + // The pack showing when the Modern Vault opened (picking another pack closes the Vault). + private uint _vaultOpenedOnPack; + + /// + /// The Modern look's Vault: the account vault's items in the grid's style, a caption with how full + /// it is and Refresh. Read-only apart from right-click > Withdraw (VaultContextMenu). + /// + private void ModernVault(Vector2 pos, Vector2 size) + { + VaultSnapshot? snap = VaultFeed.Snapshot; + VaultItem[] items = snap?.Items ?? Array.Empty(); + var pdl = ImGuiNET.ImGui.GetWindowDrawList(); + const float CapH = 22; + float ty = pos.Y + (CapH - ImGuiNET.ImGui.GetFontSize()) * 0.5f; + pdl.AddText(new Vector2(pos.X + 4, ty), Text, VaultCaption(snap)); + if (IconButton("##vault_refresh_m", PhosphorIcons.ArrowsClockwise, new Vector2(pos.X + size.X - 22, pos.Y), new Vector2(22, 20), + VaultFeed.Awaiting ? Teal : Amber, BtnFill, font: UiFont.Ui11)) + VaultFeed.RequestRefresh(); + ImGuiNET.ImGui.SetItemTooltip("Read the vault again"); + + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(pos.X, pos.Y + CapH)); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(3, 3)); + ImGuiNET.ImGui.BeginChild("##inv_vault_grid", new Vector2(size.X, Math.Max(30, size.Y - CapH)), ImGuiChildFlags.AlwaysUseWindowPadding); + ImGuiNET.ImGui.PopStyleVar(); + + float avail = ImGuiNET.ImGui.GetContentRegionAvail().X; + int cols = Math.Max(1, (int)(avail / Cell)); + int rows = (items.Length + cols - 1) / cols; + Vector2 o = ImGuiNET.ImGui.GetCursorScreenPos(); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + if (items.Length == 0) + { + string empty = snap == null ? (VaultFeed.Awaiting ? "Reading the vault..." : VaultEmptyText) : "The vault is empty."; + dl.AddText(o + new Vector2(4, 4), Mute, empty); + ImGuiNET.ImGui.Dummy(new Vector2(avail, 20)); + } + else + { + var content = new Vector2(cols * Cell, Math.Max(rows * Cell, 1)); + ImGuiNET.ImGui.InvisibleButton("##vault_cells_m", content, ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonRight); + bool hovered = ImGuiNET.ImGui.IsItemHovered(); + Vector2 mouse = ImGuiNET.ImGui.GetMousePos(); + int hoverIdx = -1; + if (hovered) + { + int c = (int)((mouse.X - o.X) / Cell), r = (int)((mouse.Y - o.Y) / Cell); + if (c >= 0 && c < cols && r >= 0 && r < rows && r * cols + c < items.Length) hoverIdx = r * cols + c; + } + + // Visible rows only. + Vector2 clipMin = ImGuiNET.ImGui.GetWindowPos(), clipMax = clipMin + ImGuiNET.ImGui.GetWindowSize(); + int firstRow = Math.Max(0, (int)((clipMin.Y - o.Y) / Cell)); + int lastRow = Math.Min(rows - 1, (int)((clipMax.Y - o.Y) / Cell)); + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); // stack counts + for (int r = firstRow; r <= lastRow; r++) + { + for (int c = 0; c < cols; c++) + { + int i = r * cols + c; + if (i >= items.Length) break; + VaultItem it = items[i]; + var cmin = new Vector2(o.X + c * Cell, o.Y + r * Cell); + var cmax = cmin + new Vector2(Cell - 2, Cell - 2); + dl.AddRectFilled(cmin, cmax, i == hoverIdx ? CellHot : CellBg, 3); + Vector2 imin = cmin + new Vector2(2, 2); + if (ScriptIcons.TryGetItem(it.Icon, it.Underlay, it.Overlay, it.Effects, it.ItemType, out IntPtr tex)) + { + IconSampling.Begin(dl); + dl.AddImage(tex, imin, imin + new Vector2(Icon, Icon)); + IconSampling.End(dl); + } + else + dl.AddRectFilled(imin, imin + new Vector2(Icon, Icon), Placeholder, 2); + if (it.Stack > 1) + { + string st = it.Stack.ToString(CultureInfo.InvariantCulture); + Vector2 ts = ImGuiNET.ImGui.CalcTextSize(st); + var tp = new Vector2(cmax.X - ts.X - 2, cmax.Y - ts.Y - 1); + dl.AddText(tp + Vector2.One, StackShadow, st); + dl.AddText(tp, StackCol, st); + } + } + } + ImGuiNET.ImGui.PopFont(); + + if (hoverIdx >= 0) + { + VaultItem hot = items[hoverIdx]; + SafeImGui.SetTooltip(hot.Stack > 1 ? $"{hot.Name} ({hot.Stack:N0})" : hot.Name); + if (ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Right)) + { + _vaultCtx = hot; + _openVaultCtx = true; + } + } + } + + ImGuiNET.ImGui.EndChild(); + ImGuiNET.ImGui.PopStyleColor(); + VaultContextMenu(); // in the panel's window, outside the child + } + /// An item's icon (with underlay and overlay) from the shared icon cache, or a placeholder. private static void DrawItemIcon(ImDrawListPtr dl, uint objectId, Vector2 min, float size, uint tint = 0xFFFFFFFF) { diff --git a/src/RynthCore.Engine/ImGui/Panels/ItemsFace.cs b/src/RynthCore.Engine/ImGui/Panels/ItemsFace.cs index 680043c..256953f 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ItemsFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ItemsFace.cs @@ -82,12 +82,23 @@ internal sealed class ItemsFace : IImGuiPanel foreach (var (groupName, idx) in groups) { if (groups.Count > 1) KindHeading(groupName, idx.Count, bw); - foreach (int i in idx) + for (int k = 0; k < idx.Count; k++) { + int i = idx[k]; ItemsPanel.WeaponEntry wpn = _data.Weapons[i]; ImGuiNET.ImGui.PushID("w" + i); - int r = Row(wpn.Name, wpn.Element, shown++, bw, _data.MissingIds.Contains(wpn.Id)); + int r = Row(wpn.Name, wpn.Element, shown++, bw, _data.MissingIds.Contains(wpn.Id), k > 0, k < idx.Count - 1); ImGuiNET.ImGui.PopID(); + // Up / down inside its group: the order is RynthAi's preference (the buff wand, the + // first weapon of a kind), and it couldn't be changed but by removing and re-adding. + if (r == 3 || r == 4) + { + int j = idx[r == 3 ? k - 1 : k + 1]; + (_data.Weapons[i], _data.Weapons[j]) = (_data.Weapons[j], _data.Weapons[i]); + Save(); + removed = true; // the indexes moved: draw the rest next frame + break; + } if (r == 1) { Vector2 at = ImGuiNET.ImGui.GetIO().MousePos; @@ -121,8 +132,15 @@ internal sealed class ItemsFace : IImGuiPanel { ItemsPanel.ConsumableEntry c = _data.Consumables[i]; ImGuiNET.ImGui.PushID("c" + i); - int r = Row(c.Name, c.Type, i, bw, missing: false); + int r = Row(c.Name, c.Type, i, bw, missing: false, canUp: i > 0, canDown: i < _data.Consumables.Count - 1); ImGuiNET.ImGui.PopID(); + if (r == 3 || r == 4) + { + int j = r == 3 ? i - 1 : i + 1; + (_data.Consumables[i], _data.Consumables[j]) = (_data.Consumables[j], _data.Consumables[i]); + Save(); + break; + } if (r == 1) { Vector2 at = ImGuiNET.ImGui.GetIO().MousePos; @@ -248,18 +266,21 @@ internal sealed class ItemsFace : IImGuiPanel } private const string MissingSuffix = " (missing)"; + // The up / down buttons' width in a row (two 20 px buttons and their gaps). + private const float MoveW = 46; /// - /// Name | [value picker] | Del. Returns 1 when the picker was clicked, 2 for Del, else 0. + /// Name | up | down | [value picker] | Del. Returns 1 when the picker was clicked, 2 for Del, + /// 3 for up, 4 for down, else 0. Up / down are drawn dim and do nothing at the ends. /// : the item isn't carried any more (amber, a warning icon, /// "(missing)" and a tooltip saying what to do). /// - private static int Row(string name, string value, int index, float w, bool missing) + private static int Row(string name, string value, int index, float w, bool missing, bool canUp = false, bool canDown = false) { Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); var dl = ImGuiNET.ImGui.GetWindowDrawList(); dl.AddRectFilled(p, p + new Vector2(w, 24), index % 2 == 0 ? RowAlt : PanelBg); - float nameW = w - 146; + float nameW = w - 146 - MoveW; float ty = p.Y + (24 - ImGuiNET.ImGui.GetFontSize()) * 0.5f; dl.PushClipRect(p, p + new Vector2(nameW, 24), true); if (missing) @@ -280,8 +301,14 @@ internal sealed class ItemsFace : IImGuiPanel ImGuiNET.ImGui.SetTooltip("Not in your pack any more - select the item in your inventory and click\n" + "Add Selected Weapon again, or remove this entry."); int result = 0; - if (Button("##pick", value, new Vector2(p.X + nameW + 2, p.Y + 2), new Vector2(96, 20), Text, BtnFill)) result = 1; - if (IconButton("##del", PhosphorIcons.Trash, new Vector2(p.X + nameW + 102, p.Y + 2), new Vector2(42, 20), Red, BtnFill)) result = 2; + float bx = p.X + nameW + 2; + if (IconButton("##up", PhosphorIcons.CaretUp, new Vector2(bx, p.Y + 2), new Vector2(20, 20), canUp ? Teal : Mute, BtnFill) && canUp) result = 3; + ImGuiNET.ImGui.SetItemTooltip("Move up"); + if (IconButton("##down", PhosphorIcons.CaretDown, new Vector2(bx + 22, p.Y + 2), new Vector2(20, 20), canDown ? Teal : Mute, BtnFill) && canDown) result = 4; + ImGuiNET.ImGui.SetItemTooltip("Move down"); + bx += MoveW; + if (Button("##pick", value, new Vector2(bx, p.Y + 2), new Vector2(96, 20), Text, BtnFill)) result = 1; + if (IconButton("##del", PhosphorIcons.Trash, new Vector2(bx + 100, p.Y + 2), new Vector2(42, 20), Red, BtnFill)) result = 2; ImGuiNET.ImGui.SetItemTooltip("Remove"); NextLine(p, 24); return result; diff --git a/src/RynthCore.Engine/ImGui/Panels/LootAddDialog.cs b/src/RynthCore.Engine/ImGui/Panels/LootAddDialog.cs index 8e3bd8b..96fc069 100644 --- a/src/RynthCore.Engine/ImGui/Panels/LootAddDialog.cs +++ b/src/RynthCore.Engine/ImGui/Panels/LootAddDialog.cs @@ -9,7 +9,13 @@ // 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) +// each at least this item's (any match; 2026-10-07). With a +// RynthAi that has it, the attribute checklist below replaces it. +// attrs the attribute checklist (2026-10-18): every attribute the item +// has, grouped (Item, Weapon / Armor, Ratings, Spells, Pet +// essence, T11, Requirements); tick a row to require it, pick +// >= / = / <= (spells: or better / exact / any tier), type a +// value. "Items like this" pre-ticks its usual set. // 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 @@ -55,6 +61,13 @@ internal sealed class LootAddDialog private readonly byte[] _name = new byte[128]; private int _keepEdit = 1; + // The attribute checklist: the rows the player changed (sent with every ask; the rest keep + // RynthAi's defaults), each typed value's text box, and the box being typed in (a new + // draft doesn't overwrite it). + private readonly System.Collections.Generic.Dictionary _choices = new(); + private readonly System.Collections.Generic.Dictionary _valueBufs = new(); + private string _editingId = string.Empty; + // Seqs are unique across popups (the inventory's and the editor's share RynthAi's one draft): // a popup only takes an answer to something it asked. private static int s_seq; @@ -94,6 +107,9 @@ internal sealed class LootAddDialog _keep = -1; _includeT11 = false; Array.Clear(_name); + _choices.Clear(); + _valueBufs.Clear(); + _editingId = string.Empty; _draft = null; _adding = false; _addedAt = default; @@ -119,6 +135,8 @@ internal sealed class LootAddDialog { ItemId = _itemId, Match = _match, Action = _action, KeepCount = _keep, RuleName = Utf8(_name).Trim(), ToOpenProfile = _toOpenProfile, IncludeT11 = _includeT11, Seq = _seq, + // Null until the player changes a row: RynthAi's defaults (and its notes about them). + Choices = _choices.Count == 0 ? null : new System.Collections.Generic.List(_choices.Values), }, }); } @@ -198,13 +216,21 @@ internal sealed class LootAddDialog } } if (!ImGuiNET.ImGui.IsAnyItemActive() || first) _keepEdit = Math.Max(0, d.KeepCount); + // Value boxes show what the rule uses now, except the one being typed in. + foreach (LootEditItemAttributeDto a in d.Attributes) + { + if (!a.Editable || a.Id == _editingId) continue; + if (!_valueBufs.TryGetValue(a.Id, out byte[]? buf)) _valueBufs[a.Id] = buf = new byte[32]; + WriteUtf8(buf, a.Value); + } } } /// The popup's contents; true when it should close. private bool Body() { - const float w = 380; + // Wider with the checklist (label, comparison, value on one line). + float w = _draft?.AttributesSupported == true ? 440 : 380; ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber); ImGuiNET.ImGui.TextUnformatted(PhosphorIcons.Plus + " Add to loot profile"); ImGuiNET.ImGui.PopStyleColor(); @@ -260,24 +286,31 @@ internal sealed class LootAddDialog if (ImGuiNET.ImGui.IsItemHovered()) SafeImGui.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)) + if (d.AttributesSupported) { - _includeT11 = t11; - changed = true; + changed |= DrawAttributes(d, w); } - if (ImGuiNET.ImGui.IsItemHovered()) - SafeImGui.SetTooltip( - "Also require this item's T11 tier (the server's stamped tier when it sends one), weapon grade,\n" + - "damage %, gear grade, every modifier, slot special and Cast on Strike, each at least as good\n" + - "as this one. Works with any match.\n" + - "Not added: Can Wield (depends on your character), Zone Locked (depends on where it was assessed),\n" + - "and property slots / Tainted (bag state, not quality)."); - if (!d.IsT11) + else { - ImGuiNET.ImGui.SameLine(); - ImGuiNET.ImGui.TextDisabled("(not a T11 item)"); + // An older RynthAi: the single T11 box. 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()) + SafeImGui.SetTooltip( + "Also require this item's T11 tier (the server's stamped tier when it sends one), weapon grade,\n" + + "damage %, gear grade, every modifier, slot special and Cast on Strike, each at least as good\n" + + "as this one. Works with any match.\n" + + "Not added: Can Wield (depends on your character), Zone Locked (depends on where it was assessed),\n" + + "and property slots / Tainted (bag state, not quality)."); + if (!d.IsT11) + { + ImGuiNET.ImGui.SameLine(); + ImGuiNET.ImGui.TextDisabled("(not a T11 item)"); + } } // Action. @@ -370,6 +403,129 @@ internal sealed class LootAddDialog return false; } + /// + /// The attribute checklist: a scrolling list of the item's rows by group, each with a tick, + /// its comparison and its value (typed, or the item's named value). A group header's + /// "all" / "none" ticks its rows. True when a choice changed (the caller asks again). + /// + private bool DrawAttributes(LootEditItemDraftDto d, float w) + { + System.Collections.Generic.List rows = d.Attributes; + ImGuiNET.ImGui.TextDisabled("Attributes:"); + ImGuiNET.ImGui.SameLine(); + if (rows.Count == 0) + { + ImGuiNET.ImGui.TextDisabled("none known yet (assess the item, then reopen)"); + return false; + } + int ticked = rows.FindAll(r => r.On).Count; + SafeImGui.TextDisabled($"{ticked} of {rows.Count} required (tick what the rule needs)"); + + int groups = 0; + string? last = null; + foreach (LootEditItemAttributeDto r in rows) + if (r.Group != last) { groups++; last = r.Group; } + float lineH = ImGuiNET.ImGui.GetFrameHeightWithSpacing(); + float h = Math.Min(rows.Count * lineH + groups * lineH + 8, 300); + + bool changed = false; + const float opX = 230, valueX = 330; + ImGuiNET.ImGui.BeginChild("##la_attrs", new Vector2(w, h), ImGuiChildFlags.Borders); + string? group = null; + foreach (LootEditItemAttributeDto r in rows) + { + if (r.Group != group) + { + group = r.Group; + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber); + ImGuiNET.ImGui.TextUnformatted(group); + ImGuiNET.ImGui.PopStyleColor(); + ImGuiNET.ImGui.SameLine(opX); + if (ImGuiNET.ImGui.SmallButton("all##la_all_" + group)) changed |= TickGroup(rows, group, true); + ImGuiNET.ImGui.SameLine(); + if (ImGuiNET.ImGui.SmallButton("none##la_none_" + group)) changed |= TickGroup(rows, group, false); + } + + bool on = r.On; + if (ImGuiNET.ImGui.Checkbox(r.Label + "##la_on_" + r.Id, ref on)) + { + SetChoice(r, on: on); + changed = true; + } + if (ImGuiNET.ImGui.IsItemHovered() && r.Tip.Length > 0) SafeImGui.SetTooltip(r.Tip); + + // The comparison: a picker when the row offers more than one. + ImGuiNET.ImGui.SameLine(opX); + if (r.Ops.Count > 1) + { + ImGuiNET.ImGui.SetNextItemWidth(90); + if (ImGuiNET.ImGui.BeginCombo("##la_op_" + r.Id, LootAttrOps.Label(r.Op))) + { + foreach (int op in r.Ops) + if (ImGuiNET.ImGui.Selectable(LootAttrOps.Label(op) + "##la_opv_" + r.Id + op.ToString(CultureInfo.InvariantCulture), op == r.Op) && op != r.Op) + { + SetChoice(r, op: op, on: true); // picking a comparison means "require it" + changed = true; + } + ImGuiNET.ImGui.EndCombo(); + } + } + else + SafeImGui.TextDisabled(LootAttrOps.Label(r.Op)); + + // The value: a box for numbers, the item's value (by name) for the rest. + ImGuiNET.ImGui.SameLine(valueX); + if (r.Editable) + { + if (!_valueBufs.TryGetValue(r.Id, out byte[]? buf)) + { + _valueBufs[r.Id] = buf = new byte[32]; + WriteUtf8(buf, r.Value); + } + ImGuiNET.ImGui.SetNextItemWidth(w - valueX - 16); + ImGuiNET.ImGui.InputText("##la_val_" + r.Id, buf, (uint)buf.Length, ImGuiInputTextFlags.CharsDecimal); + if (ImGuiNET.ImGui.IsItemActive()) _editingId = r.Id; + if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) + { + _editingId = string.Empty; + SetChoice(r, value: Utf8(buf).Trim(), on: true); // typing a value means "require it" + changed = true; + } + else if (_editingId == r.Id && !ImGuiNET.ImGui.IsItemActive()) + _editingId = string.Empty; + if (ImGuiNET.ImGui.IsItemHovered()) + SafeImGui.SetTooltip("This item: " + r.ItemValue + ". Type another value to require that instead."); + } + else + SafeImGui.TextDisabled(r.ItemValue); + } + ImGuiNET.ImGui.EndChild(); + return changed; + } + + /// Ticks or clears every row of ; true when one changed. + private bool TickGroup(System.Collections.Generic.List rows, string group, bool on) + { + bool changed = false; + foreach (LootEditItemAttributeDto r in rows) + { + if (r.Group != group || r.On == on) continue; + SetChoice(r, on: on); + changed = true; + } + return changed; + } + + /// The player's choice for a row: its current state with the given parts changed. + private void SetChoice(LootEditItemAttributeDto r, bool? on = null, int? op = null, string? value = null) + { + if (!_choices.TryGetValue(r.Id, out LootEditItemChoiceDto? c)) + _choices[r.Id] = c = new LootEditItemChoiceDto { Id = r.Id, On = r.On, Op = r.Op, Value = r.Editable && r.Value != r.ItemValue ? r.Value : string.Empty }; + if (on.HasValue) c.On = on.Value; + if (op.HasValue) c.Op = op.Value; + if (value != null) c.Value = value == r.ItemValue ? string.Empty : value; + } + private bool CloseRow(float w) { Vector2 bp = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(0, 4); diff --git a/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.Sections.cs b/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.Sections.cs index f9342f4..b005d06 100644 --- a/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.Sections.cs +++ b/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.Sections.cs @@ -123,6 +123,10 @@ internal sealed partial class MiniRemoteFace _remoteWindowSize = ImGuiNET.ImGui.GetWindowSize() / ImGuiPanelHost.PlacementScale(); _section = next; _fitPending = true; + // Non-Remote sections need the left rail (or they draw as an orphan body with no + // hub tab bar). Rail-off is only for Remote + miniremote-window (Gear/Games/…). + if (!IsRemote && !RailShown) + PanelColumnStore.Set(RailKey, 1f); if (IsRemote) { // Back on the remote: RynthAi's asks again; the engine grid gets the size it had. @@ -504,8 +508,17 @@ internal sealed partial class MiniRemoteFace ImGuiNET.ImGui.Separator(); bool rail = RailShown; if (ImGuiNET.ImGui.MenuItem("Show the sections rail", "", rail)) - PanelColumnStore.Set(RailKey, rail ? 0f : 1f); - SafeImGui.SetItemTooltip("The column of sections down the left. Hidden, RynthAi's remote shows its own tab bar again " - + "(Gear, Games and the other ILT tabs), and a section is picked here or with /rc miniremote section ."); + { + bool hide = rail; + PanelColumnStore.Set(RailKey, hide ? 0f : 1f); + // Hiding the rail only restores the Remote tab bar when we are on Remote + // (Surface → miniremote-window). Off-Remote + rail off left Crafting/etc. + // as a lone body in docked and undocked windows (2026-10-16). + if (hide && !IsRemote) + SelectSection(SectionCatalog.RemoteId); + } + SafeImGui.SetItemTooltip("The column of sections down the left. Hidden, the window returns to Remote so " + + "RynthAi's tab bar shows again (Pets, Crafting, Gear, Games, Vaulted), and a section is picked " + + "here or with /rc miniremote section (that turns the rail back on)."); } } diff --git a/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.cs b/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.cs index d3cba40..cb83e5a 100644 --- a/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.cs @@ -48,6 +48,7 @@ using RynthCore.Engine.Compatibility; using RynthCore.Engine.Plugins; using RynthCore.Engine.UI.Data; using RynthCore.Engine.UI.ScriptWindows; +using RynthCore.Engine.UI.Sections; using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; namespace RynthCore.Engine.ImGuiBackend.Panels; @@ -137,6 +138,11 @@ internal sealed partial class MiniRemoteFace : IImGuiPanel UI.Sections.SectionRegistry.Snapshot snap = UI.Sections.SectionRegistry.Current; TakeRequestedSection(snap); + // Safety: rail-off + non-Remote draws only that section's body (no hub tabs). Snap + // back to Remote so undocked/docked Mini Remote keeps Pets/Crafting/Gear/Games/Vaulted. + if (!RailShown && !IsRemote) + SelectSection(SectionCatalog.RemoteId); + // The rail, then everything else to its right (the indent keeps each line there). float railW = RailShown ? DrawRail(snap, origin, size) : 0f; if (railW > 0) diff --git a/src/RynthCore.Engine/ImGui/Panels/NavFace.cs b/src/RynthCore.Engine/ImGui/Panels/NavFace.cs index f8ca69f..bfc3b8d 100644 --- a/src/RynthCore.Engine/ImGui/Panels/NavFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/NavFace.cs @@ -157,19 +157,21 @@ internal sealed class NavFace : IImGuiPanel // Breadcrumbs | Route overlay (RynthAi's NavOverlaySettings; saved per character) p = ImGuiNET.ImGui.GetCursorScreenPos(); - if (OverlayToggle("##crumbs", "Breadcrumbs", _data.TrackBreadcrumbs, p, half, - "Record the trail you walk and draw it on the ground (/ra navtrail on|off).\nTurning it off hides the trail; /ra navtrail clear wipes it.")) + // Also on Settings > Navigation. The local settings copy takes the new value too, so a reach + // save from this panel before the next settings fetch doesn't send the old one back. + if (OverlayToggle("##crumbs", "Breadcrumbs", _data.TrackBreadcrumbs, p, half, SettingsSchema.BreadcrumbsTip)) { bool on = !_data.TrackBreadcrumbs; NavCommands.Send(new NavCmd { Cmd = "setBreadcrumbs", On = on }); _data.TrackBreadcrumbs = on; + if (_settings?.TrackBreadcrumbs != null) _settings.TrackBreadcrumbs = on; } - if (OverlayToggle("##routeovl", "Route overlay", _data.ShowRouteOverlay, new Vector2(p.X + half + 4, p.Y), half, - "Draw the route in the world: waypoint rings and lines, waypoint labels and the guide line\nto the active waypoint (/ra navoverlay on|off). The waypoint HUD window is separate.")) + if (OverlayToggle("##routeovl", "Route overlay", _data.ShowRouteOverlay, new Vector2(p.X + half + 4, p.Y), half, SettingsSchema.RouteOverlayTip)) { bool on = !_data.ShowRouteOverlay; NavCommands.Send(new NavCmd { Cmd = "setRouteOverlay", On = on }); _data.ShowRouteOverlay = on; + if (_settings?.ShowRouteOverlay != null) _settings.ShowRouteOverlay = on; } NextLine(p, 26); diff --git a/src/RynthCore.Engine/ImGui/Panels/OracleSkillsEmbed.cs b/src/RynthCore.Engine/ImGui/Panels/OracleSkillsEmbed.cs new file mode 100644 index 0000000..4f50314 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/OracleSkillsEmbed.cs @@ -0,0 +1,120 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/OracleSkillsEmbed.cs +// Bridges RynthOracle's Skills / Attributes / Progress tabs to the engine +// SkillsFace body so raise/train/progression stay in one place under Oracle. +// Oracle sets ActiveTab (`/rc oracle-skills `) while +// those tabs are selected; ScriptWindowFace for the Oracle window draws the +// embed after the script tab strip. +// +// Idea and first version: Silentkelpie (RynthCore PR 6). +// +// Lifecycle (the part that must not leak): the embedded SkillsFace is "shown" +// exactly once when it first draws, and "hidden" exactly once when it stops: +// - Clear() (Oracle left the tabs: `/rc oracle-skills off`), +// - the Oracle window closed / removed / its plugin unloaded (ScriptWindowFace +// OnHidden, ScriptWindowRegistry removal and Reset on engine shutdown), +// - a safety sweep: no draw for IdleMs (window collapsed, owner crashed). +// Redraws while shown only refresh the idle clock (NoteDrawn). SkillsFace binds +// its OnShown / OnHidden here; the callbacks go through a ShownLatch, so they +// alternate no matter how often or from which thread these are called. +// +// Skills stays reachable without Oracle: TabsAvailable is true only while the +// Oracle window is registered AND Oracle has announced itself by sending any +// `/rc oracle-skills` (an older Oracle never does), so the standalone Skills bar +// icon / panel stays for everyone who cannot reach the Oracle tabs. +// +// Pure of ImGui and the plugin registry, so tools/BarDeclutterTests compiles it. +// ============================================================================ + +using System; +using System.Threading; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +/// Which SkillsFace body Oracle wants drawn inside its window (-1 = none). +internal static class OracleSkillsEmbed +{ + /// 0 = Skills, 1 = Attributes, 2 = Progress (ILT Progression). -1 = off. + private static int _activeTab = -1; + + /// 1 once Oracle has sent a `/rc oracle-skills` (any argument) in this engine generation. + private static int _announced; + + private static long _lastDrawnMs; + + private static Action? _onShown, _onHidden; + + private static readonly ShownLatch Latch = new( + static () => _onShown?.Invoke(), + static () => _onHidden?.Invoke()); + + /// No draw for this long and the embed counts as hidden (Oracle collapsed, closed unseen, crashed). + public const long IdleMs = 1000; + + /// Oracle panel key prefix used by ScriptWindowRegistry ("script:…"). + public const string OraclePanelKeyFragment = "RynthOracle/Oracle"; + + public static int ActiveTab => Volatile.Read(ref _activeTab); + + /// True between the first embed draw and the hide (Clear, window gone, idle). + public static bool IsShown => Latch.IsShown; + + /// SkillsFace hands over what to run on the shown / hidden edges. Once per engine generation. + public static void Bind(Action shown, Action hidden) + { + _onShown = shown; + _onHidden = hidden; + } + + /// The command saw `/rc oracle-skills` from the Oracle plugin: it has the tabs. Any thread. + public static void Announce() => Volatile.Write(ref _announced, 1); + + /// + /// Whether the Oracle Skills / Attributes / Progress tabs can be reached: the Oracle script window is + /// registered and Oracle has announced the bridge. False for an Oracle without the tabs, or none. + /// + public static bool TabsAvailable(bool oracleWindowRegistered) => + oracleWindowRegistered && Volatile.Read(ref _announced) != 0; + + /// Called from the Oracle plugin (pump/render) when a Skills-family tab is shown. Out of range = off. + public static void SetActiveTab(int tab) + { + if (tab is < 0 or > 2) { Clear(); return; } + Volatile.Write(ref _activeTab, tab); + } + + /// Clears the embed when Oracle leaves Skills / Attributes / Progress, and hides the face. Any thread. + public static void Clear() + { + Volatile.Write(ref _activeTab, -1); + Latch.Hide(); + } + + /// + /// The embed drew this frame (AC thread): keeps it shown. The face's OnShown runs on the first + /// frame only. Ignored when the embed was cleared meanwhile. + /// + public static void NoteDrawn(long nowMs) + { + if (ActiveTab < 0) return; + Volatile.Write(ref _lastDrawnMs, nowMs); + Latch.Show(); + } + + /// Once a frame (AC thread): hides an embed that stopped drawing for IdleMs. + public static void Sweep(long nowMs) + { + if (!Latch.IsShown) return; + if (nowMs - Volatile.Read(ref _lastDrawnMs) > IdleMs) Latch.Hide(); + } + + /// Engine shutdown / reload: hide the face and forget the announcement. + public static void Shutdown() + { + Clear(); + Volatile.Write(ref _announced, 0); + } + + public static bool IsOraclePanel(string panelKey) => + panelKey.Contains(OraclePanelKeyFragment, StringComparison.OrdinalIgnoreCase); +} diff --git a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs index f732aff..356ba5b 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs @@ -1020,6 +1020,22 @@ internal sealed partial class RynthAiFace : IImGuiPanel PanelRouter.Toggle(title); } + /// + /// A Character menu line that opens Skills (0), Attributes (1) or Progress (2): in RynthOracle when its tabs + /// are there, else the standalone Skills panel on that tab. Checked while the place it opens is showing it. + /// + private static void SkillsMenuItem(string label, string command, int tab, string tooltip) + { + bool viaOracle = SkillsRouting.OracleTabsAvailable; + if (!viaOracle && (tab != 0 || !ImGuiPanelHost.HasFace(SkillsFace.Title))) return; // standalone Skills has its own tab strip + bool on = viaOracle + ? UI.ScriptWindows.ScriptWindowRegistry.IsOpen(OracleMainKey) && OracleSkillsEmbed.ActiveTab == tab + : ImGuiPanelHost.IsOpen(SkillsFace.Title); + if (ImGuiNET.ImGui.MenuItem(label, viaOracle ? SkillsRouting.OracleCommand(tab) : command, on)) + SkillsRouting.Open(tab); + SafeImGui.SetItemTooltip(viaOracle ? "RynthOracle's " + label + " tab: " + tooltip : tooltip); + } + // RynthOracle's script window keys (RynthOraclePlugin: UiWindow keys). private const string OracleMainKey = "RynthOracle/Oracle"; private const string OracleTimersKey = "RynthOracle/QuestTimers"; @@ -1074,9 +1090,23 @@ internal sealed partial class RynthAiFace : IImGuiPanel SafeImGui.SetItemTooltip(hasOracle ? "RynthOracle's Fellowship tab: members, leader, open / locked, XP sharing and (Infinite Leaftide) the /fship commands." : "RynthOracle's Fellowship tab (RynthOracle isn't loaded)."); - PanelMenuItem(SkillsFace.Title, "/rc skills"); + // Skills / Attributes / Progress live under RynthOracle (raise/train + ILT planners) when Oracle + // provides the tabs; otherwise these open the standalone Skills panel (SkillsRouting). + SkillsMenuItem("Skills", "/rc skills", 0, "Raise and train skills."); + SkillsMenuItem("Attributes", "/ro attrs", 1, "Attributes and vitals."); + SkillsMenuItem("Progress", "/rc progression", 2, "Augmentation, Enlightenment and XP planners (Infinite Leaftide)."); PanelMenuItem(InventoryFace.Title, "/rc inventory"); PanelMenuItem(ItemCountFace.Title, "/rc itemcount"); + // RynthInventory's script window (same as /ginv and Inventory's GInv button). + const string ginvKey = "RynthInventory/Main"; + bool hasGinv = UI.ScriptWindows.ScriptWindowRegistry.Has(ginvKey); + if (ImGuiNET.ImGui.MenuItem("Global Inventory", "/ginv", + hasGinv && UI.ScriptWindows.ScriptWindowRegistry.IsOpen(ginvKey), hasGinv)) + UI.ScriptWindows.ScriptWindowRegistry.PlayerSetVisible(ginvKey, + !UI.ScriptWindows.ScriptWindowRegistry.IsOpen(ginvKey)); + SafeImGui.SetItemTooltip(hasGinv + ? "Every character's saved packs and storage (RynthInventory)." + : "Global Inventory (RynthInventory isn't loaded)."); PanelMenuItem(CharactersFace.Title, "/rc characters"); UI.ServerMenus.DrawImGuiMenu(separatorFirst: true); diff --git a/src/RynthCore.Engine/ImGui/Panels/ScriptWindowFace.cs b/src/RynthCore.Engine/ImGui/Panels/ScriptWindowFace.cs index bf9535a..c51f808 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ScriptWindowFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ScriptWindowFace.cs @@ -36,7 +36,14 @@ internal sealed unsafe class ScriptWindowFace : IImGuiPanel public void OnShown() => NoteVisibility(visible: true); /// Closed: as OnShown; a close the owner didn't ask for is the player's X unless the bar said otherwise. - public void OnHidden() => NoteVisibility(visible: false); + public void OnHidden() + { + // Leaving Oracle hides the Skills embed (its face's OnHidden runs once, releasing the + // Progression subscription) so a later non-Oracle script window never inherits ActiveTab. + if (OracleSkillsEmbed.IsOraclePanel(_window.PanelKey)) + OracleSkillsEmbed.Clear(); + NoteVisibility(visible: false); + } private void NoteVisibility(bool visible) { @@ -60,6 +67,13 @@ internal sealed unsafe class ScriptWindowFace : IImGuiPanel ScriptWindowMetrics.Refresh(); ReportGeometry(); ScriptWindowReplay.Draw(_window); + // Oracle Skills / Attributes / Progress: after the script tab strip, draw the + // engine SkillsFace body (raise/train/progression) into the remaining space. + if (OracleSkillsEmbed.IsOraclePanel(_window.PanelKey)) + { + int tab = OracleSkillsEmbed.ActiveTab; + if (tab >= 0) SkillsFace.DrawEmbedded(tab); + } } finally { diff --git a/src/RynthCore.Engine/ImGui/Panels/SettingsRows.cs b/src/RynthCore.Engine/ImGui/Panels/SettingsRows.cs index 7dceeb5..2469e20 100644 --- a/src/RynthCore.Engine/ImGui/Panels/SettingsRows.cs +++ b/src/RynthCore.Engine/ImGui/Panels/SettingsRows.cs @@ -243,7 +243,7 @@ internal sealed class SettingsRows } // Label | [caption]; Click posts its own work (never runs plugin code on AC's thread). - private static void ButtonRow(SettingRow row, float w) + private void ButtonRow(SettingRow row, float w) { ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, TextDim); @@ -252,7 +252,16 @@ internal sealed class SettingsRows ImGuiNET.ImGui.PopStyleColor(); ImGuiNET.ImGui.SameLine(Math.Max(ImGuiNET.ImGui.GetCursorPosX() + 8, w * 0.45f)); if (ImGuiNET.ImGui.Button(row.ButtonText ?? row.Label)) + { + // A settings edit is applied to this copy and saved like a typed value (the number + // boxes re-sync from the copy next frame); Click, when also set, runs after. + if (row.Edit != null) + { + row.Edit(_data); + SettingsCommands.Save(_data.Clone()); + } row.Click?.Invoke(); + } Tooltip(row); } diff --git a/src/RynthCore.Engine/ImGui/Panels/ShownLatch.cs b/src/RynthCore.Engine/ImGui/Panels/ShownLatch.cs new file mode 100644 index 0000000..6f7c607 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/ShownLatch.cs @@ -0,0 +1,62 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/ShownLatch.cs +// A shown / hidden pair that fires its callbacks once per transition. +// +// Show() runs the "shown" callback only when the latch is off; Hide() runs the +// "hidden" callback only when it is on. Calling either twice in a row is a no-op, +// so a face that wants to be "kept shown" every frame (Show) cannot re-run its +// setup, and a hide that never had a show (or a second hide) cannot unbalance a +// refcount like UiSource.Subscribe / Unsubscribe. +// +// Pure (no ImGui, no engine state). Any thread: the callbacks run under the +// latch's own lock, so a Show and a Hide from two threads still alternate. +// If the shown callback throws, the latch stays on, so the matching Hide runs. +// Tests: tools/BarDeclutterTests. +// ============================================================================ + +using System; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed class ShownLatch +{ + private readonly object _gate = new(); + private readonly Action _shown; + private readonly Action _hidden; + private volatile bool _on; + + public ShownLatch(Action shown, Action hidden) + { + _shown = shown; + _hidden = hidden; + } + + /// True between a Show that ran its callback and the Hide that ends it. + public bool IsShown => _on; + + /// Turns the latch on. Returns true (and runs the callback) only on the off to on edge. + public bool Show() + { + if (_on) return false; + lock (_gate) + { + if (_on) return false; + _on = true; + _shown(); + return true; + } + } + + /// Turns the latch off. Returns true (and runs the callback) only on the on to off edge. + public bool Hide() + { + if (!_on) return false; + lock (_gate) + { + if (!_on) return false; + _on = false; + _hidden(); + return true; + } + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/SkillsFace.Progression.cs b/src/RynthCore.Engine/ImGui/Panels/SkillsFace.Progression.cs index d4461dc..0b074c2 100644 --- a/src/RynthCore.Engine/ImGui/Panels/SkillsFace.Progression.cs +++ b/src/RynthCore.Engine/ImGui/Panels/SkillsFace.Progression.cs @@ -595,11 +595,15 @@ internal sealed partial class SkillsFace SendProg("enltarget " + Math.Max(e.Level + 1, target).ToString(CultureInfo.InvariantCulture)); foreach (string line in e.Plan) SafeImGui.BulletText(line); + DrawEnlCalculator(e, w); + int coinsPerToken = e.CoinsPerToken; ImGuiNET.ImGui.SetNextItemWidth(100); if (ImGuiNET.ImGui.InputInt("Coins per token (shop price)##prog_cpt", ref coinsPerToken)) SendProg("coinspertoken " + Math.Max(0, coinsPerToken).ToString(CultureInfo.InvariantCulture)); if (e.TokensShort.Length > 0) Label(e.TokensShort, Dim); + if (!string.IsNullOrEmpty(e.Ecoins)) Label(e.Ecoins, Text); + if (!string.IsNullOrEmpty(e.EcoinsLum)) Label(e.EcoinsLum, Dim); ImGuiNET.ImGui.Separator(); if (e.Blockers.Length == 0) Label("Client-side checks pass.", Green); @@ -649,6 +653,171 @@ internal sealed partial class SkillsFace } } + // ── Enl calculator ────────────────────────────────────────────────── + // + // RynthILT's AppendEnlCalculatorJson (Silentkelpie's rynth PR 6 drew it first): per-level cost rows, still-need / + // have materials and the 301-325 sigil craft chain. Read-only: it only draws the Progression snapshot already + // subscribed by ProgressionShown, so it adds no subscription and no per-frame work beyond the table rows + // (row text is formatted once per snapshot, in the DTOs). A snapshot without the fields (older RynthILT) has + // empty arrays and nothing here is drawn. + // + // Width: the three tables are w - 16 wide inside the Indent(8) of DrawEnlPlanner, with a stretch label + // column and narrow fixed number columns scaled down below the retail width (300); text in a cell wraps at + // the cell instead of running off the panel. Level rows show a preview (12), "Show all" lists up to 100 in a + // table that scrolls on its own. + + private const float EnlRetailTableWidth = 284f; // retail panel width (300) - 16 + private bool _enlShowAllLevels; + private string _enlToggleLabel = ""; + private int _enlToggleTotal = -1; + private bool _enlToggleAll; + + private void DrawEnlCalculator(EnlPlanner e, float w) + { + if (!e.HasCalculator) return; + + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + if (!ImGuiNET.ImGui.CollapsingHeader("Enl calculator##prog_enl_calc", ImGuiTreeNodeFlags.DefaultOpen)) + return; + + float tw = Math.Max(120f, w - 16); + float k = Math.Min(1f, tw / EnlRetailTableWidth); // fixed columns shrink on a narrower panel + DrawEnlLevels(e.Levels, tw, k); + DrawEnlMaterials(e.Materials, tw, k); + DrawEnlChain(e, tw, k); + } + + private void DrawEnlLevels(EnlLevelRow[] rows, float tw, float k) + { + if (rows.Length == 0) return; + bool canExpand = EnlCalculatorView.CanExpand(rows.Length); + bool all = canExpand && _enlShowAllLevels; + int shown = EnlCalculatorView.VisibleLevels(rows.Length, all); + + ImGuiTableFlags flags = ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp; + var size = new Vector2(tw, 0); + if (all) + { + // Own scroll area, a preview's worth of rows tall (+ header): the long list never pushes the panel. + flags |= ImGuiTableFlags.ScrollY; + size.Y = (ImGuiNET.ImGui.GetTextLineHeightWithSpacing() + 4f) * (EnlCalculatorView.PreviewLevels + 1); + } + + ImGuiNET.ImGui.PushTextWrapPos(0f); // wrap in the cell, not at the panel's wrap position + try + { + if (ImGuiNET.ImGui.BeginTable("##enl_levels", 4, flags, size)) + { + ImGuiNET.ImGui.TableSetupColumn("Enl", ImGuiTableColumnFlags.WidthFixed, 40 * k); + ImGuiNET.ImGui.TableSetupColumn("Item", ImGuiTableColumnFlags.WidthFixed, 84 * k); + ImGuiNET.ImGui.TableSetupColumn("Qty", ImGuiTableColumnFlags.WidthFixed, 44 * k); + ImGuiNET.ImGui.TableSetupColumn("Lum"); + if (all) ImGuiNET.ImGui.TableSetupScrollFreeze(0, 1); + ImGuiNET.ImGui.TableHeadersRow(); + for (int i = 0; i < shown; i++) + { + EnlLevelRow row = rows[i]; + uint c = row.Ok ? Green : Amber; + ImGuiNET.ImGui.TableNextRow(); + ImGuiNET.ImGui.TableNextColumn(); Label(row.LevelText, c); + ImGuiNET.ImGui.TableNextColumn(); Label(row.Item, c); + ImGuiNET.ImGui.TableNextColumn(); Label(row.CountText, c); + ImGuiNET.ImGui.TableNextColumn(); Label(row.Lum, c); + } + ImGuiNET.ImGui.EndTable(); + } + } + finally + { + ImGuiNET.ImGui.PopTextWrapPos(); + } + + if (canExpand) + { + // The label is rebuilt only when the row count or the mode changes, not every frame. + if (_enlToggleTotal != rows.Length || _enlToggleAll != all) + { + _enlToggleTotal = rows.Length; + _enlToggleAll = all; + _enlToggleLabel = (all ? "Show first " + EnlCalculatorView.PreviewLevels.ToString(CultureInfo.InvariantCulture) + : "Show all " + Math.Min(rows.Length, EnlCalculatorView.MaxLevels).ToString(CultureInfo.InvariantCulture) + " steps") + + "##enl_lv_all"; + } + if (ImGuiNET.ImGui.SmallButton(_enlToggleLabel)) _enlShowAllLevels = !all; + } + Label("Green = pack items and banked luminance still cover that step (simulated in order).", Dim); + } + + private static void DrawEnlMaterials(EnlMaterialRow[] rows, float tw, float k) + { + if (rows.Length == 0) return; + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + Label("Still need / have", Text); + ImGuiNET.ImGui.PushTextWrapPos(0f); + try + { + if (ImGuiNET.ImGui.BeginTable("##enl_mats", 3, + ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp, new Vector2(tw, 0))) + { + ImGuiNET.ImGui.TableSetupColumn("Material"); + ImGuiNET.ImGui.TableSetupColumn("Still need", ImGuiTableColumnFlags.WidthFixed, 72 * k); + ImGuiNET.ImGui.TableSetupColumn("Have", ImGuiTableColumnFlags.WidthFixed, 72 * k); + ImGuiNET.ImGui.TableHeadersRow(); + int n = Math.Min(rows.Length, EnlCalculatorView.MaxListRows); + for (int i = 0; i < n; i++) + { + EnlMaterialRow m = rows[i]; + uint c = m.Ok ? Green : Amber; + ImGuiNET.ImGui.TableNextRow(); + ImGuiNET.ImGui.TableNextColumn(); Label(m.Label, c); + ImGuiNET.ImGui.TableNextColumn(); Label(m.Need, c); + ImGuiNET.ImGui.TableNextColumn(); Label(m.Have, c); + } + ImGuiNET.ImGui.EndTable(); + } + } + finally + { + ImGuiNET.ImGui.PopTextWrapPos(); + } + } + + private static void DrawEnlChain(EnlPlanner e, float tw, float k) + { + EnlChainRow[] rows = e.Chain; + if (rows.Length == 0) return; + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + Label("Sigil craft chain (301-325)", Text); + if (!string.IsNullOrEmpty(e.ChainNote)) Label(e.ChainNote, Dim); // wraps at the panel's wrap position + ImGuiNET.ImGui.PushTextWrapPos(0f); + try + { + if (ImGuiNET.ImGui.BeginTable("##enl_chain", 3, + ImGuiTableFlags.RowBg | ImGuiTableFlags.BordersInnerV | ImGuiTableFlags.SizingStretchProp, new Vector2(tw, 0))) + { + ImGuiNET.ImGui.TableSetupColumn("Item"); + ImGuiNET.ImGui.TableSetupColumn("Need", ImGuiTableColumnFlags.WidthFixed, 72 * k); + ImGuiNET.ImGui.TableSetupColumn("Have", ImGuiTableColumnFlags.WidthFixed, 72 * k); + ImGuiNET.ImGui.TableHeadersRow(); + int n = Math.Min(rows.Length, EnlCalculatorView.MaxListRows); + for (int i = 0; i < n; i++) + { + EnlChainRow r = rows[i]; + uint c = r.Ok ? Green : Amber; + ImGuiNET.ImGui.TableNextRow(); + ImGuiNET.ImGui.TableNextColumn(); Label(r.DisplayLabel, c); + ImGuiNET.ImGui.TableNextColumn(); Label(r.NeedText, c); + ImGuiNET.ImGui.TableNextColumn(); Label(r.HaveText, c); + } + ImGuiNET.ImGui.EndTable(); + } + } + finally + { + ImGuiNET.ImGui.PopTextWrapPos(); + } + } + // ── Confirm ───────────────────────────────────────────────────────── /// The Progression tab's Yes/No popup (outside the body child, like DrawConfirm). diff --git a/src/RynthCore.Engine/ImGui/Panels/SkillsFace.cs b/src/RynthCore.Engine/ImGui/Panels/SkillsFace.cs index 8ca7790..d2d23b0 100644 --- a/src/RynthCore.Engine/ImGui/Panels/SkillsFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/SkillsFace.cs @@ -37,6 +37,7 @@ using System; using System.Collections.Generic; using System.Globalization; using System.Numerics; +using System.Threading; using ImGuiNET; using RynthCore.Engine.Compatibility; using RynthCore.Engine.ImGuiBackend.Hud; @@ -186,7 +187,17 @@ internal sealed partial class SkillsFace : IImGuiPanel private long _masteryPendingUntilMs; private int _masteryPendingVersion; - public void OnShown() + // Shown / hidden exactly once per visible stretch, however often the host (or the Oracle embed) asks: + // the Progression subscription it takes in OnShownCore is given back in OnHiddenCore, once. + private readonly ShownLatch _life; + + public SkillsFace() => _life = new ShownLatch(OnShownCore, OnHiddenCore); + + public void OnShown() => _life.Show(); + + public void OnHidden() => _life.Hide(); + + private void OnShownCore() { PlayerProgressHooks.Want(); PlayerProgressHooks.RefreshSoon(); @@ -196,22 +207,85 @@ internal sealed partial class SkillsFace : IImGuiPanel ProgressionShown(); } - public void OnHidden() => ProgressionHidden(); + private void OnHiddenCore() => ProgressionHidden(); public void Draw() { + int req = Interlocked.Exchange(ref _requestedTab, -1); + if (req >= 0) _tab = req; PlayerProgressHooks.Want(); Refresh(); ApplyProgressionRequest(); if (_tab == 2 && !ProgressionTabVisible) _tab = 0; float w = Begin(out Vector2 origin, out Vector2 size); + DrawBody(w, origin, size, showOwnTabs: true); + End(origin, size); + + _picker.Draw(); + DrawMulti(); + DrawConfirm(); + DrawProgressionConfirm(); + } + + /// + /// Oracle-hosted body (the old Skills panel's tabs, without its frame or tab strip). + /// Called each frame the Oracle window shows a Skills / Attributes / Progress tab. + /// The first frame runs OnShown (via OracleSkillsEmbed's latch); OracleSkillsEmbed.Clear, + /// the Oracle window closing and the idle sweep run OnHidden. AC thread. + /// + public static void DrawEmbedded(int tab) + { + if (_embed == null) + { + _embed = new SkillsFace(); + OracleSkillsEmbed.Bind(_embed.OnShown, _embed.OnHidden); + } + OracleSkillsEmbed.NoteDrawn(Environment.TickCount64); + _embed.DrawHosted(tab); + } + + /// Selects Skills (0), Attributes (1) or Progress (2) on the next standalone Draw. + public static void RequestTab(int tab) + { + tab = tab < 0 ? 0 : tab > 2 ? 2 : tab; + Volatile.Write(ref _requestedTab, tab); + } + + private static int _requestedTab = -1; + + /// Shared instance that draws inside Oracle (no separate Skills window). + private static SkillsFace? _embed; + + private void DrawHosted(int tab) + { + _tab = tab < 0 ? 0 : tab > 2 ? 2 : tab; + PlayerProgressHooks.Want(); + Refresh(); + ApplyProgressionRequest(); + // Progress tab on a world without ILT: the tab stays selected and DrawProgression explains. + + Vector2 avail = ImGuiNET.ImGui.GetContentRegionAvail(); + float w = Math.Max(40f, avail.X); + Vector2 origin = ImGuiNET.ImGui.GetCursorScreenPos(); + DrawBody(w, origin, new Vector2(w, Math.Max(120f, avail.Y)), showOwnTabs: false); + + _picker.Draw(); + DrawMulti(); + DrawConfirm(); + DrawProgressionConfirm(); + } + + private void DrawBody(float w, Vector2 origin, Vector2 size, bool showOwnTabs) + { DrawSummary(w); - DrawTabs(w); + if (showOwnTabs) DrawTabs(w); if (_tab == 0) DrawToolbar(w); if (_tab != 2) DrawColumnHeader(w, _tab == 0 ? "Skill" : "Attribute"); - float bodyH = Math.Max(60, Remaining(origin, size) - GripOverlap()); + float bodyH = Math.Max(60, showOwnTabs + ? Remaining(origin, size) - GripOverlap() + : size.Y - (ImGuiNET.ImGui.GetCursorScreenPos().Y - origin.Y)); ImGuiNET.ImGui.PushStyleColor(ImGuiCol.ChildBg, PanelBg); ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(0, 0)); ImGuiNET.ImGui.BeginChild("##skills_body", new Vector2(w, bodyH)); @@ -230,12 +304,6 @@ internal sealed partial class SkillsFace : IImGuiPanel ImGuiNET.ImGui.EndChild(); ImGuiNET.ImGui.PopStyleVar(); ImGuiNET.ImGui.PopStyleColor(); - End(origin, size); - - _picker.Draw(); - DrawMulti(); - DrawConfirm(); - DrawProgressionConfirm(); } // ── Data ──────────────────────────────────────────────────────────── diff --git a/src/RynthCore.Engine/ImGui/Panels/SkillsRouting.cs b/src/RynthCore.Engine/ImGui/Panels/SkillsRouting.cs new file mode 100644 index 0000000..a96e9ec --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/SkillsRouting.cs @@ -0,0 +1,84 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/SkillsRouting.cs +// Where "open Skills" goes. Skills / Attributes / Progress live under RynthOracle +// when its tabs can be reached; otherwise the standalone Skills panel stays the +// way in, so nobody loses Skills (bar icon, /rc skills, the Character menu). +// +// "Can be reached" = the Oracle script window is registered AND Oracle has +// announced the bridge with `/rc oracle-skills` (OracleSkillsEmbed.TabsAvailable); +// an Oracle without the tabs never announces, so it counts as absent. +// ============================================================================ + +using RynthCore.Engine.UI; +using RynthCore.Engine.UI.ScriptWindows; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal static class SkillsRouting +{ + /// Oracle's main script window (UiWindow "RynthOracle/Oracle"). + public const string OracleKey = OracleSkillsEmbed.OraclePanelKeyFragment; + + /// Oracle provides the Skills / Attributes / Progress tabs now. Any thread. + public static bool OracleTabsAvailable => OracleSkillsEmbed.TabsAvailable(ScriptWindowRegistry.Has(OracleKey)); + + /// The bar's Skills icon shows exactly when Oracle can't provide the tabs. Any thread. + public static bool ShowSkillsBarIcon => !OracleTabsAvailable; + + /// The Oracle command that selects a tab: skills, attrs or progress. + public static string OracleCommand(int tab) => tab switch + { + 1 => "/ro attrs", + 2 => "/ro progress", + _ => "/ro skills", + }; + + /// + /// Opens Skills (0), Attributes (1) or Progress (2): in Oracle when its tabs are there, else the + /// standalone Skills panel on that tab. Returns false when neither exists (no ImGui layer). + /// + public static bool Open(int tab) + { + if (OracleTabsAvailable) + { + ServerMenus.Run(OracleCommand(tab)); + return true; + } + if (!ImGuiPanelHost.HasFace(SkillsFace.Title)) return false; + if (tab == 2) + { + SkillsFace.ShowProgression(); + return true; + } + SkillsFace.RequestTab(tab); + if (!ImGuiPanelHost.IsOpen(SkillsFace.Title)) PanelRouter.Toggle(SkillsFace.Title); + return true; + } + + /// + /// "/rc skills show|hide|toggle". With Oracle: show opens Oracle on Skills, hide closes Oracle only while + /// it is showing a Skills-family tab, toggle closes it when it already shows Skills. Without: the panel. + /// + public static bool SetOpen(bool? show) + { + if (!OracleTabsAvailable) + { + if (!ImGuiPanelHost.HasFace(SkillsFace.Title)) return false; + if (show == null || show.Value != ImGuiPanelHost.IsOpen(SkillsFace.Title)) + PanelRouter.Toggle(SkillsFace.Title); + return true; + } + + bool oracleOpen = ScriptWindowRegistry.IsOpen(OracleKey); + int tab = OracleSkillsEmbed.ActiveTab; + bool onSkills = oracleOpen && tab == 0; + if (show == false || (show == null && onSkills)) + { + if (oracleOpen && tab >= 0) ScriptWindowRegistry.PlayerSetVisible(OracleKey, false); + return true; + } + if (show == true && onSkills) return true; + ServerMenus.Run(OracleCommand(0)); + return true; + } +} diff --git a/src/RynthCore.Engine/LogPaths.cs b/src/RynthCore.Engine/LogPaths.cs index e67cbf1..ee3e987 100644 --- a/src/RynthCore.Engine/LogPaths.cs +++ b/src/RynthCore.Engine/LogPaths.cs @@ -116,6 +116,39 @@ internal static class LogPaths } } + /// The shared native crash log every client appends to (see ). + internal const string NativeCrashLogName = "native-crash.log"; + + /// A native-crash.log larger than this is moved aside when a client starts. + internal const long NativeCrashLogRotateBytes = 1L * 1024 * 1024; + + /// + /// Engine-startup rotation of the SHARED native-crash.log (one fixed name for every client, + /// so 's per-PID rule does not cover it). Over + /// it moves to native-crash.log.old (replacing the + /// previous one). Must run BEFORE the native logger opens the file. A client that already has + /// it open (they open it share-delete) keeps writing to the moved file, which the logger's + /// own byte budget keeps bounded; nothing is lost, it just continues in the .old file. + /// Best-effort; never throws. Returns true when it moved the file. + /// + internal static bool RotateNativeCrashLogAtStartup() + { + try + { + string active = Path.Combine(LogDirectory, NativeCrashLogName); + if (!File.Exists(active)) return false; + if (new FileInfo(active).Length < NativeCrashLogRotateBytes) return false; + string rotated = active + ".old"; + try { if (File.Exists(rotated)) File.Delete(rotated); } catch { } + File.Move(active, rotated); + return true; + } + catch + { + return false; + } + } + /// /// Startup housekeeping: delete per-client session logs (and their .old /// rotations) older than . Each client launch produces a diff --git a/src/RynthCore.Engine/Plugins/EngineSettings.cs b/src/RynthCore.Engine/Plugins/EngineSettings.cs index d9d7060..506178f 100644 --- a/src/RynthCore.Engine/Plugins/EngineSettings.cs +++ b/src/RynthCore.Engine/Plugins/EngineSettings.cs @@ -41,10 +41,20 @@ internal static class EngineSettings private static bool _serverMessageStream = true; private static bool _flightRecorder = true; private static bool _insertReleasesUi; + // Settings > Display: strip AC window chrome while windowed (default off). + private static bool _borderlessWindowed; + // Settings > Display: reopen Rynth panels where they were (default on: panels have always been remembered). + private static bool _rememberWindowLayout = true; + // Settings > Display: save and restore the AC window's own position and size (default off, opt-in). + private static bool _rememberAcWindowPosition; // "LoadAllServerPlugins": hand-set only, written back only when true (PluginManifestGate). private static bool _loadAllServerPlugins; // Read-only, like EnableLargeAddressAlignmentFix: only a hand-set value is written back. private static int _maxHotReloads = ReloadCapNotice.DefaultMaxHotReloads; + // "HoldReloadInWorld": opt-in (default off). On = an automatic engine reload waits until the player + // leaves the world, for at most _holdReloadInWorldMaxMinutes (ReloadInWorldGate). + private static bool _holdReloadInWorld; + private static int _holdReloadInWorldMaxMinutes = ReloadInWorldGate.DefaultMaxMinutes; // "IltServerNames" / "IltHosts": what counts as Infinite Leaftide (Compatibility/IltInfo.cs). // null = not in the file: IltDetect's defaults. private static List? _iltServerNames; @@ -53,6 +63,8 @@ internal static class EngineSettings // For testing only (https, or http to this PC); read only, like MaxHotReloads. private static string? _reportEndpoint; private static Compatibility.AutoIdMode _autoIdMode = Compatibility.AutoIdPolicy.DefaultMode; + // "TransitionGate": default true. False = queued game actions are never held for a death / portal. + private static bool _transitionGate = true; private static bool _loaded; public static IReadOnlyList PluginPaths @@ -221,7 +233,7 @@ internal static class EngineSettings EnsureLoaded(); // populate _pluginPaths before Save() rewrites the file if (_enableImGuiBackend == value) return; _enableImGuiBackend = value; - Save(); + Save("EnableImGuiBackend"); } } @@ -282,7 +294,7 @@ internal static class EngineSettings EnsureLoaded(); // populate _pluginPaths before Save() rewrites the file if (_closeOnServerDisconnect == value) return; _closeOnServerDisconnect = value; - Save(); + Save("CloseOnServerDisconnect"); } } @@ -364,7 +376,7 @@ internal static class EngineSettings EnsureLoaded(); bool changed = enabled ? _disabledUiHooks.Remove(name) : _disabledUiHooks.Add(name); if (changed) - Save(); + Save("DisabledUiHooks"); } /// "ServerMessageStream" in engine.json (default true): the kill switch for the @@ -410,7 +422,68 @@ internal static class EngineSettings EnsureLoaded(); // populate _pluginPaths before Save() rewrites the file if (_insertReleasesUi == value) return; _insertReleasesUi = value; - Save(); + Save("InsertReleasesUi"); + } + } + + /// "BorderlessWindowed" in engine.json (default false, 2026-10-18): strip the AC + /// window caption and thick frame while staying windowed. Exclusive fullscreen is left alone, + /// and chrome is only ever given back to a window this setting stripped (AcWindowChrome). + /// Set in game in Settings > Display. From SilentKelpie's PR 6. + public static bool BorderlessWindowed + { + get + { + EnsureLoaded(); + return _borderlessWindowed; + } + set + { + EnsureLoaded(); + if (_borderlessWindowed == value) return; + _borderlessWindowed = value; + Save("BorderlessWindowed"); + // AcWindowChrome applies the style from the game thread; keep this file free of + // HWND / UI refs so EngineSettingsTests can compile it alone. + } + } + + /// "RememberWindowLayout" in engine.json (default true: Rynth panels have always been + /// remembered). Off: panel_state.txt is not overwritten and open panels are not reopened from + /// the last session. Does not touch the AC window itself (RememberAcWindowPosition). + /// Set in game in Settings > Display. + public static bool RememberWindowLayout + { + get + { + EnsureLoaded(); + return _rememberWindowLayout; + } + set + { + EnsureLoaded(); + if (_rememberWindowLayout == value) return; + _rememberWindowLayout = value; + Save("RememberWindowLayout"); + } + } + + /// "RememberAcWindowPosition" in engine.json (default false, opt-in): save the Asheron's + /// Call window's position and size per character and put it back at the next login. + /// Set in game in Settings > Display. + public static bool RememberAcWindowPosition + { + get + { + EnsureLoaded(); + return _rememberAcWindowPosition; + } + set + { + EnsureLoaded(); + if (_rememberAcWindowPosition == value) return; + _rememberAcWindowPosition = value; + Save("RememberAcWindowPosition"); } } @@ -429,6 +502,49 @@ internal static class EngineSettings } } + /// "HoldReloadInWorld" in engine.json (default false, opt-in; from SilentKelpie's PR 6): + /// when true, an automatic engine reload (the loader's file watcher, an engine deploy) waits until + /// the player logs out / reaches character select instead of reloading mid-session, for at most + /// . A reload asked for by hand (ERl, the bar RL button, + /// /rc rl, the hotkey) is never held. A workaround for CoreCLR re-init crashes on stacked + /// mid-session reloads. Only a true is written to the file. Set in game in Settings > Misc. + public static bool HoldReloadInWorld + { + get + { + EnsureLoaded(); + return _holdReloadInWorld; + } + set + { + EnsureLoaded(); + if (_holdReloadInWorld == value) return; + _holdReloadInWorld = value; + Save("HoldReloadInWorld"); + } + } + + /// "HoldReloadInWorldMaxMinutes" in engine.json (default 10, valid 1-240): how long + /// holds a reload before it gives up, logs once, and reloads + /// anyway. The hold never lasts forever. Out-of-range values are clamped; only a non-default + /// value is written to the file. + public static int HoldReloadInWorldMaxMinutes + { + get + { + EnsureLoaded(); + return _holdReloadInWorldMaxMinutes; + } + set + { + EnsureLoaded(); + int v = ReloadInWorldGate.ClampMaxMinutes(value); + if (_holdReloadInWorldMaxMinutes == v) return; + _holdReloadInWorldMaxMinutes = v; + Save("HoldReloadInWorldMaxMinutes"); + } + } + /// "ReportEndpoint" in engine.json: a test URL for "Report a problem" instead of the /// built-in https://aelrynth.com/rynth/report (ProblemReportCore.ResolveEndpoint accepts https, /// or http to this PC; anything else is ignored). Null when the file has none. Edited in the file. @@ -475,7 +591,7 @@ internal static class EngineSettings else list.RemoveAt(at); // Replaced, never edited in place: IltInfo reads the old list on other threads. _iltServerNames = list; - Save(); + Save("IltServerNames"); return true; } @@ -505,7 +621,29 @@ internal static class EngineSettings EnsureLoaded(); // populate _pluginPaths before Save() rewrites the file if (_autoIdMode == value) return; _autoIdMode = value; - Save(); + Save("AutoIdMode"); + } + } + + /// "TransitionGate" in engine.json (default true): the world-transition gate + /// (Compatibility/WorldTransitionState.cs) holds the engine's queued game actions (casts, uses, + /// appraisals, chat commands...) while the character is dead or in portal space, and for 5 s + /// after. False turns the gate off entirely: nothing is held. Even with it on, a gate held + /// continuously for WorldTransitionState.MaxHoldMs opens by itself (logged once, counted in the + /// heartbeat as gateov=N) in case a revived character reads as dead or the portal flag sticks. + public static bool TransitionGate + { + get + { + EnsureLoaded(); + return _transitionGate; + } + set + { + EnsureLoaded(); + if (_transitionGate == value) return; + _transitionGate = value; + Save("TransitionGate"); } } @@ -519,7 +657,7 @@ internal static class EngineSettings return; } _pluginPaths.Add(full); - Save(); + Save("PluginPaths"); } public static void RemovePluginPath(int index) @@ -528,7 +666,7 @@ internal static class EngineSettings if (index >= 0 && index < _pluginPaths.Count) { _pluginPaths.RemoveAt(index); - Save(); + Save("PluginPaths"); } } @@ -661,11 +799,32 @@ internal static class EngineSettings (iruEl.ValueKind == JsonValueKind.True || iruEl.ValueKind == JsonValueKind.False)) _insertReleasesUi = iruEl.GetBoolean(); + if (doc.RootElement.TryGetProperty("BorderlessWindowed", out var blwEl) && + (blwEl.ValueKind == JsonValueKind.True || blwEl.ValueKind == JsonValueKind.False)) + _borderlessWindowed = blwEl.GetBoolean(); + + if (doc.RootElement.TryGetProperty("RememberWindowLayout", out var rwlEl) && + (rwlEl.ValueKind == JsonValueKind.True || rwlEl.ValueKind == JsonValueKind.False)) + _rememberWindowLayout = rwlEl.GetBoolean(); + + if (doc.RootElement.TryGetProperty("RememberAcWindowPosition", out var rapEl) && + (rapEl.ValueKind == JsonValueKind.True || rapEl.ValueKind == JsonValueKind.False)) + _rememberAcWindowPosition = rapEl.GetBoolean(); + if (doc.RootElement.TryGetProperty("MaxHotReloads", out var mhrEl) && mhrEl.ValueKind == JsonValueKind.Number && mhrEl.TryGetInt32(out int mhr)) _maxHotReloads = mhr; + if (doc.RootElement.TryGetProperty("HoldReloadInWorld", out var hriwEl) && + (hriwEl.ValueKind == JsonValueKind.True || hriwEl.ValueKind == JsonValueKind.False)) + _holdReloadInWorld = hriwEl.GetBoolean(); + + if (doc.RootElement.TryGetProperty("HoldReloadInWorldMaxMinutes", out var hrimEl) && + hrimEl.ValueKind == JsonValueKind.Number && + hrimEl.TryGetInt32(out int hrim)) + _holdReloadInWorldMaxMinutes = ReloadInWorldGate.ClampMaxMinutes(hrim); + if (doc.RootElement.TryGetProperty("ReportEndpoint", out var repEl) && repEl.ValueKind == JsonValueKind.String && repEl.GetString() is { Length: > 0 } rep) @@ -676,6 +835,10 @@ internal static class EngineSettings Compatibility.AutoIdPolicy.TryParseMode(aimEl.GetString(), out Compatibility.AutoIdMode aim)) _autoIdMode = aim; + if (doc.RootElement.TryGetProperty("TransitionGate", out var tgEl) && + (tgEl.ValueKind == JsonValueKind.True || tgEl.ValueKind == JsonValueKind.False)) + _transitionGate = tgEl.GetBoolean(); + if (doc.RootElement.TryGetProperty("PreventIdleLogoff", out var pilEl) && (pilEl.ValueKind == JsonValueKind.True || pilEl.ValueKind == JsonValueKind.False)) { @@ -732,21 +895,38 @@ internal static class EngineSettings return list; } - /// Every engine.json key EnsureLoaded reads or Save writes. Save rewrites these from - /// memory (one written only when not the default is left out, as before) and keeps every - /// other key as the file had it. A new engine.json setting goes here too - /// (tools/EngineSettingsTests checks this list against this file). + /// Every engine.json key EnsureLoaded reads or Save writes. A save writes only the keys + /// this client changed (Save(key); one written only when not the default is left out, which + /// removes it) and keeps every other key as the file had it. A new engine.json setting goes + /// here too, and its setter calls Save("Key") (tools/EngineSettingsTests checks this list and + /// the Save calls against this file). internal static readonly HashSet OwnedKeys = new(StringComparer.Ordinal) { "PluginPaths", "EnableImGuiShell", "EnablePlugins", "EnableDatShareHook", "EnableAvaloniaOverlay", "EnableD3D9Hook", "EnableEngine", "EngineHookCount", "EnableImGuiBackend", "EnableHangMinidump", "PreventIdleLogoff", "DecalBridge", "DecalInGameImGui", "DecalStandDown", "DisabledUiHooks", "ServerMessageStream", - "FlightRecorder", "InsertReleasesUi", "IltServerNames", "IltHosts", "EnableLargeAddressAlignmentFix", + "FlightRecorder", "InsertReleasesUi", "BorderlessWindowed", "RememberWindowLayout", + "RememberAcWindowPosition", "IltServerNames", "IltHosts", "EnableLargeAddressAlignmentFix", "MaxHotReloads", "ReportEndpoint", "CloseOnServerDisconnect", "AutoIdMode", "EnablePluginOverlayWindows", "LoggingLevel", - "LoadAllServerPlugins", + "LoadAllServerPlugins", "TransitionGate", + "HoldReloadInWorld", "HoldReloadInWorldMaxMinutes", }; + // The engine.json keys this client changed this session. Every client keeps the whole settings + // in memory, so writing all of the engine's keys back let a client that never touched a setting + // put its stale value over another client's change (last writer won). Only these keys are + // written now; every other key keeps what the file holds. Idea from Silentkelpie (rynth PR #6). + private static readonly HashSet _changedKeys = new(StringComparer.Ordinal); + private static readonly object _changedLock = new(); + + /// Saves engine.json after changed (only changed keys are written). + private static void Save(string key) + { + lock (_changedLock) _changedKeys.Add(key); + Save(); + } + private static void Save() { try @@ -796,12 +976,24 @@ internal static class EngineSettings w.WriteBoolean("EnableLargeAddressAlignmentFix", false); if (_insertReleasesUi) // default false: leave the file as it was w.WriteBoolean("InsertReleasesUi", true); + if (_borderlessWindowed) // default false: leave the file as it was + w.WriteBoolean("BorderlessWindowed", true); + if (!_rememberWindowLayout) // default true: leave the file as it was + w.WriteBoolean("RememberWindowLayout", false); + if (_rememberAcWindowPosition) // default false: leave the file as it was + w.WriteBoolean("RememberAcWindowPosition", true); if (!_closeOnServerDisconnect) // default true: leave the file as it was w.WriteBoolean("CloseOnServerDisconnect", false); + if (!_transitionGate) // default true: only a hand-set false is written + w.WriteBoolean("TransitionGate", false); if (_loadAllServerPlugins) // default false: only a hand-set true is written w.WriteBoolean("LoadAllServerPlugins", true); if (_maxHotReloads != ReloadCapNotice.DefaultMaxHotReloads) // only a hand-set value is written w.WriteNumber("MaxHotReloads", _maxHotReloads); + if (_holdReloadInWorld) // default false: only a true is written + w.WriteBoolean("HoldReloadInWorld", true); + if (_holdReloadInWorldMaxMinutes != ReloadInWorldGate.DefaultMaxMinutes) // only a non-default value is written + w.WriteNumber("HoldReloadInWorldMaxMinutes", _holdReloadInWorldMaxMinutes); if (_reportEndpoint != null) // only a hand-set value is written w.WriteString("ReportEndpoint", _reportEndpoint); WriteStringList(w, "IltServerNames", _iltServerNames); // null (not in the file): left out @@ -813,7 +1005,13 @@ internal static class EngineSettings // Keep the keys others write (the launcher's), and swap the file in atomically. string? existing = File.Exists(SettingsPath) ? File.ReadAllText(SettingsPath) : null; - byte[]? merged = EngineSettingsFile.Merge(existing, ms.ToArray(), OwnedKeys, out string? readError); + string[] changed; + lock (_changedLock) + { + changed = new string[_changedKeys.Count]; + _changedKeys.CopyTo(changed); + } + byte[]? merged = EngineSettingsFile.Merge(existing, ms.ToArray(), OwnedKeys, out string? readError, changed); if (merged == null) { RynthLog.Warn($"EngineSettings: not saving - {SettingsPath} can't be read ({readError}), and rewriting it would lose what it holds. The change holds until the client closes; fix or delete the file to save again."); diff --git a/src/RynthCore.Engine/Plugins/EngineSettingsFile.cs b/src/RynthCore.Engine/Plugins/EngineSettingsFile.cs index f0bc58e..178b73a 100644 --- a/src/RynthCore.Engine/Plugins/EngineSettingsFile.cs +++ b/src/RynthCore.Engine/Plugins/EngineSettingsFile.cs @@ -25,7 +25,15 @@ internal static class EngineSettingsFile /// nothing to keep. Returns null, with set, when the existing file /// isn't a readable JSON object: overwriting it would lose whatever it holds. /// - public static byte[]? Merge(string? existingJson, byte[] ownedJson, ICollection ownedKeys, out string? error) + /// + /// When given (and the file exists): only these of the engine's keys are taken from + /// (one it left out, at its default, is removed); every other + /// key, owned or not, keeps the file's value. So a client that changed one setting doesn't + /// write its stale copy of the others over what other clients saved since. + /// Idea from Silentkelpie (rynth PR #6); re-implemented against our key set. + /// + public static byte[]? Merge(string? existingJson, byte[] ownedJson, ICollection ownedKeys, out string? error, + ICollection? changedKeys = null) { error = null; JsonDocument? existing = null; @@ -55,8 +63,11 @@ internal static class EngineSettingsFile using (var w = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = true })) { w.WriteStartObject(); + // Only the changed keys when there's a file to keep the rest from. + bool onlyChanged = changedKeys != null && existing != null; foreach (JsonProperty p in owned.RootElement.EnumerateObject()) { + if (onlyChanged && !changedKeys!.Contains(p.Name)) continue; if (!written.Add(p.Name)) continue; p.WriteTo(w); } @@ -64,7 +75,7 @@ internal static class EngineSettingsFile { foreach (JsonProperty p in existing.RootElement.EnumerateObject()) { - if (ownedKeys.Contains(p.Name)) continue; + if (onlyChanged ? changedKeys!.Contains(p.Name) : ownedKeys.Contains(p.Name)) continue; if (!written.Add(p.Name)) continue; // also drops a duplicate key in the old file p.WriteTo(w); } diff --git a/src/RynthCore.Engine/Plugins/ManagedPlugins.cs b/src/RynthCore.Engine/Plugins/ManagedPlugins.cs index 7048f74..e6ec2d4 100644 --- a/src/RynthCore.Engine/Plugins/ManagedPlugins.cs +++ b/src/RynthCore.Engine/Plugins/ManagedPlugins.cs @@ -134,6 +134,9 @@ internal static class ManagedPlugins } } + // How long the unload waits for the plugin contexts to be collected before naming the ones still held. + private const long UnloadCheckMs = 1500; + /// Unloads every retired plugin's context. Last step of EngineLifecycle.Shutdown. public static void UnloadRetired() { @@ -147,17 +150,59 @@ internal static class ManagedPlugins } #if ENGINE_CORECLR string vaBefore = retired.Count > 0 ? Compatibility.AddressSpace.Describe() : ""; + var refs = new List<(string Name, WeakReference Context)>(retired.Count); foreach (Entry e in retired) + { e.Context.Unload(); - // Context.Unload only starts the collection; "after" is right after the request, so the - // NEXT reload's "va before" is where a context that never collects shows up. - if (retired.Count > 0) - RynthLog.Plugin($"ManagedPlugins: {retired.Count} plugin context(s) unloading: {string.Join(", ", retired.ConvertAll(e => e.Name))} (va before: {vaBefore}, after: {Compatibility.AddressSpace.Describe()})."); + refs.Add((e.Name, new WeakReference(e.Context, trackResurrection: true))); + } + retired.Clear(); // drop our own strong references before checking + // Context.Unload only starts the collection. A context still alive after a few collections + // is held by something (a thread, a timer, an event, a cached type in a shared context) and + // keeps everything the plugin loaded: every reload then loses that much address space for + // good (300-480 MB on some reloads, 2026-10-19). Name the ones that stay, so the culprit shows. + if (refs.Count > 0) + { + var sw = System.Diagnostics.Stopwatch.StartNew(); + while (refs.Exists(r => r.Context.IsAlive) && sw.ElapsedMilliseconds < UnloadCheckMs) + { + GC.Collect(); + GC.WaitForPendingFinalizers(); + if (refs.Exists(r => r.Context.IsAlive)) System.Threading.Thread.Sleep(20); + } + var alive = refs.FindAll(r => r.Context.IsAlive).ConvertAll(r => r.Name); + RynthLog.Plugin($"ManagedPlugins: {refs.Count} plugin context(s) unloaded in {sw.ElapsedMilliseconds} ms (va before: {vaBefore}, after: {Compatibility.AddressSpace.Describe()})" + + (alive.Count == 0 ? "; all collected." : $"; STILL HELD after {UnloadCheckMs} ms (their memory stays): {string.Join(", ", alive)}.")); + } #endif } #if ENGINE_CORECLR - /// A plugin and its private dependencies (from the plugin's folder). + /// + /// Runtime\PluginShared: the RynthSuite plugins' common dependencies (RynthCore.PluginSdk, + /// PluginCore, MoonSharp, ...), installed with RynthCore so each plugin in the update feed stays + /// one DLL (v88, 2026-10-19). Each plugin still loads its own copy into its own collectible + /// context, so it unloads with the plugin. Null when the folder isn't there. + /// + internal static readonly string? SharedDir = FindSharedDir(); + + private static string? FindSharedDir() + { + try + { + // The shim sits in Runtime\ (the engine itself may run from Runtime\.engine_loads\). + foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies()) + { + if (a.GetName().Name != "RynthCore.Shim" || string.IsNullOrEmpty(a.Location)) continue; + string dir = Path.Combine(Path.GetDirectoryName(a.Location)!, "PluginShared"); + return Directory.Exists(dir) ? dir : null; + } + } + catch { } + return null; + } + + /// A plugin and its private dependencies (its own folder, then Runtime\PluginShared). private sealed class PluginLoadContext : AssemblyLoadContext { private readonly string _dir; @@ -190,16 +235,28 @@ internal static class ManagedPlugins string fx = Path.Combine(Path.GetDirectoryName(typeof(object).Assembly.Location)!, name.Name + ".dll"); return File.Exists(fx) ? LoadFromAssemblyPath(fx) : null; } - string candidate = Path.Combine(_dir, name.Name + ".dll"); - return File.Exists(candidate) ? LoadFromFile(candidate) : null; + string? path = Pick(name.Name + ".dll"); + return path != null ? LoadFromFile(path) : null; + } + + // The plugin's own copy or the shared one; with both, the newer file (a dev build carries + // fresh dependencies beside it; a launcher update leaves stale ones beside a new plugin). + private string? Pick(string fileName) + { + string own = Path.Combine(_dir, fileName); + string? shared = SharedDir != null ? Path.Combine(SharedDir, fileName) : null; + bool hasOwn = File.Exists(own), hasShared = shared != null && File.Exists(shared); + if (hasOwn && hasShared) + return File.GetLastWriteTimeUtc(shared!) > File.GetLastWriteTimeUtc(own) ? shared : own; + return hasOwn ? own : hasShared ? shared : null; } protected override IntPtr LoadUnmanagedDll(string unmanagedDllName) { - string candidate = Path.Combine(_dir, unmanagedDllName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) + string? path = Pick(unmanagedDllName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) ? unmanagedDllName : unmanagedDllName + ".dll"); - return File.Exists(candidate) ? LoadUnmanagedDllFromPath(candidate) : IntPtr.Zero; + return path != null ? LoadUnmanagedDllFromPath(path) : IntPtr.Zero; } } #endif diff --git a/src/RynthCore.Engine/Plugins/PluginContractVersion.cs b/src/RynthCore.Engine/Plugins/PluginContractVersion.cs index 849783a..32a2ccc 100644 --- a/src/RynthCore.Engine/Plugins/PluginContractVersion.cs +++ b/src/RynthCore.Engine/Plugins/PluginContractVersion.cs @@ -25,5 +25,8 @@ internal static class PluginContractVersion // server plugins declare their server in their manifest; from SilentKelpie's build). // v87: GetWieldedItems (what the player wields and where, from the server's wield / contain / // drop messages: EquipmentTracker; the client's own fields go stale, 2026-10-18). - public const uint Current = 87; + // v88: managed plugins find their common dependencies in Runtime\PluginShared (installed with + // RynthCore), so the update feed ships each managed plugin as one DLL; releases build the + // plugins managed (collectible: a reload frees them) and they declare minEngineApi 88. + public const uint Current = 88; } diff --git a/src/RynthCore.Engine/Plugins/PluginManager.cs b/src/RynthCore.Engine/Plugins/PluginManager.cs index 17ae8e6..05b4bd4 100644 --- a/src/RynthCore.Engine/Plugins/PluginManager.cs +++ b/src/RynthCore.Engine/Plugins/PluginManager.cs @@ -40,7 +40,12 @@ internal static partial class PluginManager private readonly record struct PendingEnchantmentAdded(uint SpellId, double DurationSeconds); private readonly record struct PendingEnchantmentRemoved(uint EnchantmentId); - private const int MaxPendingIncomingChats = 256; + // A /myquests reply is one line per quest flag (hundreds on a played character) and arrives + // in one burst; a slow pump tick (a busy plugin window) must not drop its head. Lines are short + // strings, so a deep queue costs little. Drops are counted and logged (DispatchQueuedChatWindowText). + private const int MaxPendingIncomingChats = 4096; + private static long _droppedIncomingChats; // lines dropped unheard since the last log + private static long _droppedIncomingChatsLoggedMs; // when that was last logged private const int MaxPendingBusyCountEvents = 128; private const int MaxPendingTargetChanges = 128; private const int MaxPendingCombatModeChanges = 128; @@ -674,7 +679,10 @@ internal static partial class PluginManager lock (PendingIncomingChatsLock) { if (_pendingIncomingChats.Count >= MaxPendingIncomingChats) + { _pendingIncomingChats.Dequeue().Held?.Decide(eat: false); // dropped unheard: it shows + _droppedIncomingChats++; + } _pendingIncomingChats.Enqueue(new PendingIncomingChat(text, chatType, held)); } @@ -1722,14 +1730,26 @@ internal static partial class PluginManager System.Threading.Interlocked.Exchange(ref _chatPumpBeatMs, Environment.TickCount64); PendingIncomingChat[] pending; + long dropped = 0; lock (PendingIncomingChatsLock) { - if (_pendingIncomingChats.Count == 0) - return; + // Report drops at most every 10 s (a flood would otherwise flood the log too). + long nowMs = Environment.TickCount64; + if (_droppedIncomingChats > 0 && nowMs - _droppedIncomingChatsLoggedMs >= 10_000) + { + dropped = _droppedIncomingChats; + _droppedIncomingChats = 0; + _droppedIncomingChatsLoggedMs = nowMs; + } - pending = _pendingIncomingChats.ToArray(); + pending = _pendingIncomingChats.Count == 0 ? Array.Empty() : _pendingIncomingChats.ToArray(); _pendingIncomingChats.Clear(); } + // Logged outside the lock: AC's main thread queues chat under it. + if (dropped > 0) + RynthLog.Plugin($"PluginManager: {dropped} incoming chat line(s) dropped before plugins heard them (queue full at {MaxPendingIncomingChats})."); + if (pending.Length == 0) + return; unsafe { @@ -1775,6 +1795,14 @@ internal static partial class PluginManager } eaten = HeldChatQueue.PluginsAteIt(eat, threw); + // RynthChat's Hide rules / standard filters live in the engine, not in a plugin, so + // without this a hidden line still printed in AC's own chat window. Only a held line + // can still be kept out (one already printed has gone); a failure lets it show. + if (!eaten && evt.Held != null) + { + try { eaten = UI.Data.ChatModel.ShouldHideInRetail(evt.Text, unchecked((int)evt.ChatType)); } + catch (Exception ex) { RynthLog.Plugin($"PluginManager: retail chat filter check failed ({ex.GetType().Name}: {ex.Message})."); } + } } finally { diff --git a/src/RynthCore.Engine/ReloadInWorldGate.cs b/src/RynthCore.Engine/ReloadInWorldGate.cs new file mode 100644 index 0000000..94c5e78 --- /dev/null +++ b/src/RynthCore.Engine/ReloadInWorldGate.cs @@ -0,0 +1,123 @@ +// ============================================================================ +// RynthCore.Engine - ReloadInWorldGate.cs +// Optionally holds an automatic hot reload while the player is in the world. +// +// From SilentKelpie's RynthCore PR 6 (2026-10-16), reworked 2026-10-18 into an opt-in: +// stacked FileWatcher reloads mid-session were killing clients on his machine: the loader +// shut the engine down, then CoreCLR re-init AVed / never logged "Reload: complete". +// ReloadDeferral only waits for plugin blockers; it does not stop a quiet in-world unload. +// This gate waits with the old engine still mapped until the player is out of the world. +// +// Differences from the PR, all the owner's decisions: +// - OFF by default: engine.json "HoldReloadInWorld" (Settings > Misc, "Hold reloads while in +// the world"). Off, nothing here runs and a reload behaves exactly as before. +// - A reload asked for by hand (ERl, the bar RL button, /rc rl, the hotkey) is never held; +// only automatic ones (the file watcher, an engine deploy) are. +// - It never holds forever: after "HoldReloadInWorldMaxMinutes" (default 10) it gives up, +// logs once that it is reloading anyway, and the reload goes ahead. +// +// Pure: the "still hold?" query, clock, sleep and log are injected so tools\ReloadInWorldGateTests +// can run offline. EntryPoint wires it from DeferReloadWhilePluginsObject. +// ============================================================================ + +using System; +using System.Threading; + +namespace RynthCore.Engine; + +internal static class ReloadInWorldGate +{ + /// How often we ask again while holding for the world. + public static readonly TimeSpan DefaultPoll = TimeSpan.FromSeconds(2); + /// While waiting, the "still holding" line repeats this often (first line at once). + public static readonly TimeSpan DefaultLogEvery = TimeSpan.FromSeconds(30); + + /// Default for engine.json "HoldReloadInWorldMaxMinutes". + public const int DefaultMaxMinutes = 10; + public const int MinMaxMinutes = 1; + public const int MaxMaxMinutes = 240; + + /// Keeps a configured bound inside its valid range (1-240 minutes). + public static int ClampMaxMinutes(int minutes) => Math.Clamp(minutes, MinMaxMinutes, MaxMaxMinutes); + + public enum Outcome + { + /// Not holding (off, by hand, or not in the world): reload at once. + Clear, + /// Was in the world, then left (or the hold was switched off / bypassed by hand); reload now. + ClearedAfterWait, + /// Still in the world at the bound: the hold gave up, reload anyway. + TimedOut, + } + + /// + /// True when a reload should wait: the hold is switched on, the client is in the world, and + /// the reload is an automatic one. A reload asked for by hand is never held. + /// + public static bool ShouldHold(bool byHand, bool holdEnabled, bool inWorld) + => holdEnabled && inWorld && !byHand; + + /// + /// Polls until it is false or has passed + /// (then : the caller reloads anyway). A query that throws counts + /// as "not holding", so a broken gate cannot wedge the client. + /// + public static Outcome Run( + Func stillHold, + Action log, + Action? notify, + TimeSpan maxWait, + out TimeSpan waited, + Func? clock = null, + Action? sleep = null, + TimeSpan? poll = null, + TimeSpan? logEvery = null) + { + clock ??= static () => DateTime.UtcNow; + sleep ??= static t => Thread.Sleep(t); + TimeSpan pollSpan = poll ?? DefaultPoll; + TimeSpan logSpan = logEvery ?? DefaultLogEvery; + + waited = TimeSpan.Zero; + if (!SafeHold(stillHold)) return Outcome.Clear; + + DateTime start = clock(); + log($"engine reload waiting: player is in the world (Hold reloads while in the world is on; loads after logout / character select, or after at most {maxWait.TotalMinutes:0.#} min)."); + try + { + notify?.Invoke("player is in the world"); + } + catch { /* chat must not abort the wait */ } + DateTime lastLog = start; + + while (true) + { + // Never sleep past the bound: the give-up happens on time, not up to a poll late. + TimeSpan left = maxWait - (clock() - start); + sleep(left > TimeSpan.Zero && left < pollSpan ? left : pollSpan); + DateTime now = clock(); + waited = now - start; + if (!SafeHold(stillHold)) + { + log($"engine reload: hold released after {waited.TotalSeconds:0.0} s (left the world, or reload asked for by hand, or the hold was switched off); reloading now."); + return Outcome.ClearedAfterWait; + } + if (waited >= maxWait) + { + log($"engine reload: held {waited.TotalMinutes:0.#} min, reloading anyway (still in the world at the HoldReloadInWorldMaxMinutes bound of {maxWait.TotalMinutes:0.#} min)."); + return Outcome.TimedOut; + } + if (now - lastLog >= logSpan) + { + lastLog = now; + log($"engine reload waiting: still in the world ({waited.TotalSeconds:0} s so far; loads after logout / character select, or at {maxWait.TotalMinutes:0.#} min)."); + } + } + } + + private static bool SafeHold(Func stillHold) + { + try { return stillHold(); } + catch { return false; } // fail open: a broken query must not wedge the client + } +} diff --git a/src/RynthCore.Engine/UI/AcWindowChrome.cs b/src/RynthCore.Engine/UI/AcWindowChrome.cs new file mode 100644 index 0000000..c1753ff --- /dev/null +++ b/src/RynthCore.Engine/UI/AcWindowChrome.cs @@ -0,0 +1,412 @@ +// ============================================================================ +// RynthCore.Engine - UI/AcWindowChrome.cs +// Settings > Display helpers for the Asheron's Call game HWND: +// - Borderless windowed: strip caption / thick frame while leaving the client +// windowed (not exclusive fullscreen). Chrome is only given back to a window +// WE stripped: that is recorded as an HWND property (SetProp) holding the +// window's style from before, which outlives an in-process engine hot reload +// and dies with the process. No marker and the setting off = hands off. +// - Remember placement (opt-in): persist the outer window rect per client +// (ac_window..txt) and put it back once after login. +// Original: SilentKelpie (RynthCore PR 6). Decisions live in AcWindowChromePolicy. +// +// Threading. Tick runs inside EndScene (the render callback) and only READS there +// (styles, rect, the marker); anything that changes the window - the style, a +// SetWindowPos that moves or resizes it - is posted to the game window's own WndProc +// (Win32Backend.PostToGameThread, the way pop-out windows are created), so it never +// runs inside the render call. Rect files are written by UiBackgroundWriter, never +// on the render thread. With no WndProc subclass (ImGui backend off) the feature +// stays inactive instead of touching the window from the render thread. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.InteropServices; +using System.Threading; +using RynthCore.Engine.Compatibility; +using RynthCore.Engine.Plugins; +using static RynthCore.Engine.UI.AcWindowChromePolicy; + +namespace RynthCore.Engine.UI; + +internal static class AcWindowChrome +{ + private const int GwlStyle = -16; + + private const uint SwpNosize = 0x0001; + private const uint SwpNomove = 0x0002; + private const uint SwpNozorder = 0x0004; + private const uint SwpNoactivate = 0x0010; + private const uint SwpFramechanged = 0x0020; + + // HWND properties: they live on the window, so they survive an engine hot reload. + private const string StyleProp = "RynthCore.AcWindowChrome.StyleBeforeBorderless"; + private const string PlacementDoneProp = "RynthCore.AcWindowChrome.PlacementRestored"; + + private const long TickIntervalMs = 2000; + private const long SaveIntervalMs = 10000; + private const long NoKeyFallbackMs = 90000; // no character this long: use the shared file + private const long PostStuckMs = 10000; // a posted job that never ran may be posted again + private const long StyleRetryMs = 10000; // a style change that does not stick is not retried every tick + + private static readonly object Sync = new(); + private static readonly Action PostedWork = RunOnGameThread; + private static long _nextTickMs, _nextSaveMs, _firstTickMs, _workPostedAtMs, _nextStyleActionMs; + private static int _workPosted; + private static Rect? _lastWritten; + private static bool _loggedNoExecutor; + + // ── Frame loop (EndScene): reads + posts only ──────────────────────── + + /// Call from the frame loop; throttled. Never changes the window itself. + public static void Tick(IntPtr hwnd) + { + if (hwnd == IntPtr.Zero) return; + long now = Environment.TickCount64; + if (now < _nextTickMs) return; + _nextTickMs = now + TickIntervalMs; + if (_firstTickMs == 0) _firstTickMs = now; + + try + { + if (!ImGuiBackend.Win32Backend.CanRunOnGameThread) + { + // No WndProc subclass to run window changes from: stay out of the window. + if (!_loggedNoExecutor && (EngineSettings.BorderlessWindowed || EngineSettings.RememberAcWindowPosition)) + { + _loggedNoExecutor = true; + RynthLog.UI("AcWindowChrome: no game-thread executor (ImGui backend off); display chrome inactive."); + } + return; + } + + int style = GetWindowLong(hwnd, GwlStyle); + bool work = now >= Interlocked.Read(ref _nextStyleActionMs) + && DecideBorderless(EngineSettings.BorderlessWindowed, ReadMarker(hwnd), style, + LooksExclusiveFullscreen(hwnd, style)).Action != ChromeAction.None; + + if (EngineSettings.RememberAcWindowPosition && !PlacementDone(hwnd) && KeyReady(now, out _)) + work = true; + + if (work) PostWork(now); + + MaybeSavePlacement(hwnd, now, style); + } + catch (Exception ex) + { + try { RynthLog.UI($"AcWindowChrome: tick failed - {ex.Message}"); } catch { } + } + } + + /// A Settings > Display toggle changed: apply it on the game thread soon (not inline). + public static void RequestApply() + { + try + { + if (ImGuiBackend.Win32Backend.CanRunOnGameThread) + PostWork(Environment.TickCount64); + // else: Tick applies it once a game-thread executor exists. + } + catch (Exception ex) + { + try { RynthLog.UI($"AcWindowChrome: apply request failed - {ex.Message}"); } catch { } + } + } + + private static void PostWork(long now) + { + // One job in flight; a job that never ran (window gone, reload) may be re-posted after a while. + if (Interlocked.CompareExchange(ref _workPosted, 1, 0) != 0 && now - _workPostedAtMs < PostStuckMs) + return; + _workPostedAtMs = now; + Volatile.Write(ref _workPosted, 1); + if (!ImGuiBackend.Win32Backend.PostToGameThread(PostedWork)) + Volatile.Write(ref _workPosted, 0); + } + + // ── Game thread (the game WndProc) ─────────────────────────────────── + + private static void RunOnGameThread() + { + Volatile.Write(ref _workPosted, 0); + try + { + IntPtr hwnd = ResolveGameHwnd(); + if (hwnd == IntPtr.Zero) return; + lock (Sync) + { + if (EngineSettings.RememberAcWindowPosition && !PlacementDone(hwnd)) + TryRestorePlacement(hwnd); + ApplyBorderless(hwnd); + } + } + catch (Exception ex) + { + try { RynthLog.UI($"AcWindowChrome: apply failed - {ex.Message}"); } catch { } + } + } + + private static void ApplyBorderless(IntPtr hwnd) + { + int style = GetWindowLong(hwnd, GwlStyle); + ChromeDecision d = DecideBorderless(EngineSettings.BorderlessWindowed, ReadMarker(hwnd), style, + LooksExclusiveFullscreen(hwnd, style)); + if (d.Action != ChromeAction.None) + Interlocked.Exchange(ref _nextStyleActionMs, Environment.TickCount64 + StyleRetryMs); + switch (d.Action) + { + case ChromeAction.Strip: + SetWindowLong(hwnd, GwlStyle, d.NewStyle); + SetProp(hwnd, StyleProp, new IntPtr(d.NewMarker)); + Refresh(hwnd); + RynthLog.UI("AcWindowChrome: borderless windowed on."); + break; + case ChromeAction.Restore: + SetWindowLong(hwnd, GwlStyle, d.NewStyle); + RemoveProp(hwnd, StyleProp); + Refresh(hwnd); + RynthLog.UI("AcWindowChrome: window borders restored."); + break; + case ChromeAction.ClearMarker: + RemoveProp(hwnd, StyleProp); + RynthLog.UI("AcWindowChrome: borderless marker cleared (" + d.Reason + ")."); + break; + } + } + + // Style change only: same outer rect, non-client area rebuilt. + private static void Refresh(IntPtr hwnd) + => SetWindowPos(hwnd, IntPtr.Zero, 0, 0, 0, 0, + SwpNomove | SwpNosize | SwpNozorder | SwpNoactivate | SwpFramechanged); + + private static void TryRestorePlacement(IntPtr hwnd) + { + if (!KeyReady(Environment.TickCount64, out string? key)) return; // still at the login screen + // One attempt per window, even a skipped one; the HWND carries it across a hot reload. + SetProp(hwnd, PlacementDoneProp, new IntPtr(1)); + + if (IsIconic(hwnd) || IsZoomed(hwnd)) return; + string path = PlacementPath(key); + if (!File.Exists(path)) return; + + Rect saved; + try + { + if (!TryParsePlacement(File.ReadAllLines(path), out saved)) return; + } + catch (Exception ex) + { + try { RynthLog.UI($"AcWindowChrome: read placement failed - {ex.Message}"); } catch { } + return; + } + + PlacementVerdict v = EvaluatePlacement(true, LooksExclusiveFullscreen(hwnd, GetWindowLong(hwnd, GwlStyle)), + saved, Monitors()); + if (v != PlacementVerdict.Ok) + { + RynthLog.UI($"AcWindowChrome: saved placement not restored ({v}); leaving AC where it is."); + return; + } + + SetWindowPos(hwnd, IntPtr.Zero, saved.Left, saved.Top, saved.Width, saved.Height, + SwpNozorder | SwpNoactivate); + _lastWritten = saved; + RynthLog.UI(FormattableString.Invariant( + $"AcWindowChrome: restored AC window to ({saved.Left},{saved.Top}) {saved.Width}x{saved.Height}.")); + } + + // ── Saving the rect (read on the render thread, written in the background) ── + + private static void MaybeSavePlacement(IntPtr hwnd, long now, int style) + { + if (!EngineSettings.RememberAcWindowPosition) return; + if (now < _nextSaveMs) return; + // Not before the restore attempt: it would overwrite the saved rect with the launch position. + if (!PlacementDone(hwnd)) return; + _nextSaveMs = now + SaveIntervalMs; + TrySavePlacement(hwnd, style, now, force: false); + } + + private static void TrySavePlacement(IntPtr hwnd, int style, long now, bool force) + { + if (!KeyReady(now, out string? key)) return; + if (IsIconic(hwnd) || IsZoomed(hwnd)) return; + if (!GetWindowRect(hwnd, out RECT wr)) return; + var cur = new Rect(wr.Left, wr.Top, wr.Right, wr.Bottom); + PlacementVerdict v = EvaluatePlacement(true, LooksExclusiveFullscreen(hwnd, style), cur, Monitors()); + if (!force && !ShouldWritePlacement(v, cur, _lastWritten)) return; + if (v != PlacementVerdict.Ok) return; + _lastWritten = cur; + string path = PlacementPath(key); + UiBackgroundWriter.Enqueue("ac window placement", () => WritePlacement(path, cur)); + } + + private static void WritePlacement(string path, Rect r) + { + try + { + string? dir = Path.GetDirectoryName(path); + if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); + File.WriteAllText(path, FormatPlacement(r)); + } + catch (Exception ex) + { + try { RynthLog.UI($"AcWindowChrome: save placement failed - {ex.Message}"); } catch { } + } + } + + /// Settings > Display "Save Layout Now". Runs on the render thread (a button in a + /// frame): everything that touches a file is queued to the background writer. + public static void SaveLayoutNow() + { + try + { + IntPtr hwnd = ResolveGameHwnd(); + if (hwnd != IntPtr.Zero && EngineSettings.RememberAcWindowPosition) + TrySavePlacement(hwnd, GetWindowLong(hwnd, GwlStyle), Environment.TickCount64, force: true); + } + catch (Exception ex) + { + try { RynthLog.UI($"AcWindowChrome: save window failed - {ex.Message}"); } catch { } + } + + try { ImGuiBackend.Hud.MonsterHudSettings.Save(); } catch { /* best-effort */ } + + try + { + if (ImGuiNET.ImGui.GetCurrentContext() != IntPtr.Zero) + { + string ini = ImGuiNET.ImGui.SaveIniSettingsToMemory(); + string iniPath = Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "imgui.ini"); + UiBackgroundWriter.Enqueue("imgui.ini", () => + { + Directory.CreateDirectory(RynthCore.Install.RynthInstallPaths.RynthAiDir); + File.WriteAllText(iniPath, ini); + }); + } + } + catch (Exception ex) + { + try { RynthLog.UI($"AcWindowChrome: imgui.ini save failed - {ex.Message}"); } catch { } + } + + // Rewrites panel_state.txt from the in-memory state (even with Remember Open Windows off). + UiBackgroundWriter.Enqueue("panel state (save now)", PanelStateStore.Flush); + + try + { + AcMainThreadQueue.EnqueueWriteToChat("[RynthCore] Saved open windows and HUD positions.", 1); + } + catch { /* chat may not be ready */ } + } + + // ── Helpers ────────────────────────────────────────────────────────── + + private static bool KeyReady(long now, out string? key) + => TryResolveKey(SessionStateRegistry.LastServerName, SessionStateRegistry.LastCharacterName, + _firstTickMs == 0 ? 0 : now - _firstTickMs, NoKeyFallbackMs, out key); + + private static string PlacementPath(string? key) + { + string root = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); + return Path.Combine(root, "RynthCore", PlacementFileName(key)); + } + + private static int ReadMarker(IntPtr hwnd) => unchecked((int)GetProp(hwnd, StyleProp).ToInt64()); + + private static bool PlacementDone(IntPtr hwnd) => GetProp(hwnd, PlacementDoneProp) != IntPtr.Zero; + + /// Game HWND for Settings toggles (EntryPoint, else Win32Backend). + internal static IntPtr ResolveGameHwndForSettings() => ResolveGameHwnd(); + + private static IntPtr ResolveGameHwnd() + { + IntPtr hwnd = EntryPoint.GameHwnd; + if (hwnd != IntPtr.Zero) return hwnd; + try { return ImGuiBackend.Win32Backend.GameHwnd; } catch { return IntPtr.Zero; } + } + + /// True when the outer rect fills a monitor and has no caption: exclusive fullscreen or + /// an already borderless fullscreen; do not fight it. + private static bool LooksExclusiveFullscreen(IntPtr hwnd, int style) + { + if ((style & WsCaption) != 0) return false; + if (!GetWindowRect(hwnd, out RECT wr)) return false; + IntPtr mon = MonitorFromWindow(hwnd, 2 /* MONITOR_DEFAULTTONEAREST */); + if (mon == IntPtr.Zero) return false; + var mi = new MONITORINFO { cbSize = Marshal.SizeOf() }; + if (!GetMonitorInfo(mon, ref mi)) return false; + int mw = mi.rcMonitor.Right - mi.rcMonitor.Left; + int mh = mi.rcMonitor.Bottom - mi.rcMonitor.Top; + int ww = wr.Right - wr.Left; + int wh = wr.Bottom - wr.Top; + return Math.Abs(ww - mw) <= 4 && Math.Abs(wh - mh) <= 4 + && Math.Abs(wr.Left - mi.rcMonitor.Left) <= 4 + && Math.Abs(wr.Top - mi.rcMonitor.Top) <= 4; + } + + private static List Monitors() + { + var list = new List(4); + EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, (IntPtr mon, IntPtr dc, ref RECT rc, IntPtr data) => + { + var mi = new MONITORINFO { cbSize = Marshal.SizeOf() }; + if (GetMonitorInfo(mon, ref mi)) + list.Add(new Rect(mi.rcMonitor.Left, mi.rcMonitor.Top, mi.rcMonitor.Right, mi.rcMonitor.Bottom)); + return true; + }, IntPtr.Zero); + return list; + } + + [StructLayout(LayoutKind.Sequential)] + private struct RECT { public int Left, Top, Right, Bottom; } + + [StructLayout(LayoutKind.Sequential)] + private struct MONITORINFO + { + public int cbSize; + public RECT rcMonitor; + public RECT rcWork; + public uint dwFlags; + } + + private delegate bool MonitorEnumProc(IntPtr hMonitor, IntPtr hdcMonitor, ref RECT lprcMonitor, IntPtr dwData); + + [DllImport("user32.dll")] + private static extern int GetWindowLong(IntPtr hWnd, int nIndex); + + [DllImport("user32.dll")] + private static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong); + + [DllImport("user32.dll")] + private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, + int X, int Y, int cx, int cy, uint uFlags); + + [DllImport("user32.dll")] + private static extern bool GetWindowRect(IntPtr hWnd, out RECT lpRect); + + [DllImport("user32.dll")] + private static extern bool IsIconic(IntPtr hWnd); + + [DllImport("user32.dll")] + private static extern bool IsZoomed(IntPtr hWnd); + + [DllImport("user32.dll")] + private static extern IntPtr MonitorFromWindow(IntPtr hwnd, uint dwFlags); + + [DllImport("user32.dll", CharSet = CharSet.Auto)] + private static extern bool GetMonitorInfo(IntPtr hMonitor, ref MONITORINFO lpmi); + + [DllImport("user32.dll")] + private static extern bool EnumDisplayMonitors(IntPtr hdc, IntPtr lprcClip, MonitorEnumProc lpfnEnum, IntPtr dwData); + + [DllImport("user32.dll", CharSet = CharSet.Unicode)] + private static extern bool SetProp(IntPtr hWnd, string lpString, IntPtr hData); + + [DllImport("user32.dll", CharSet = CharSet.Unicode)] + private static extern IntPtr GetProp(IntPtr hWnd, string lpString); + + [DllImport("user32.dll", CharSet = CharSet.Unicode)] + private static extern IntPtr RemoveProp(IntPtr hWnd, string lpString); +} diff --git a/src/RynthCore.Engine/UI/AcWindowChromePolicy.cs b/src/RynthCore.Engine/UI/AcWindowChromePolicy.cs new file mode 100644 index 0000000..1cb786c --- /dev/null +++ b/src/RynthCore.Engine/UI/AcWindowChromePolicy.cs @@ -0,0 +1,202 @@ +// ============================================================================ +// RynthCore.Engine - UI/AcWindowChromePolicy.cs +// The decisions behind Settings > Display for the Asheron's Call window, as pure +// functions (no HWND, no engine state) so tools\EngineSettingsTests can run them: +// - Borderless windowed: what to do given the setting, the "we stripped it" marker +// and the window's current style bits. +// - Window position: whether a saved or current rect is worth restoring / saving, +// and which file a client's rect lives in. +// AcWindowChrome does the Win32 work and asks these first. +// Idea and first version: SilentKelpie (RynthCore PR 6). +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text; + +namespace RynthCore.Engine.UI; + +internal static class AcWindowChromePolicy +{ + public const int WsCaption = 0x00C00000; // WS_BORDER | WS_DLGFRAME + public const int WsThickFrame = 0x00040000; + public const int WsSysMenu = 0x00080000; + public const int WsMinimizeBox = 0x00020000; + public const int WsMaximizeBox = 0x00010000; + public const int WsBorder = 0x00800000; + + /// Caption + frame + sysmenu / min / max: the chrome Borderless Windowed removes. + public const int BorderChromeMask = + WsCaption | WsThickFrame | WsSysMenu | WsMinimizeBox | WsMaximizeBox | WsBorder; + + // ── Borderless windowed ────────────────────────────────────────────── + + internal enum ChromeAction + { + /// Leave the window alone. + None, + /// Remove the chrome and remember the style it had (NewMarker). + Strip, + /// Put the chrome we removed back (NewStyle) and drop the marker. + Restore, + /// The marker is stale (chrome is back already, or the marker is unusable): drop it. + ClearMarker, + } + + internal readonly record struct ChromeDecision(ChromeAction Action, int NewStyle, int NewMarker, string Reason) + { + public static readonly ChromeDecision NoChange = new(ChromeAction.None, 0, 0, ""); + } + + /// + /// What to do about the window chrome right now. + /// is the durable "WE stripped this window" record: the window's style + /// as it was before we stripped it (0 = never stripped by us). Chrome is only ever restored when + /// that marker exists, so a window that is chrome-less for any other reason (exclusive + /// fullscreen, an external borderless tool, a game option) is never touched with the setting off. + /// + public static ChromeDecision DecideBorderless(bool want, int marker, int style, bool looksExclusiveFullscreen) + { + bool hasChrome = (style & WsCaption) != 0; + + if (want) + { + // Not ours to take over: it already looks like exclusive fullscreen. + if (marker == 0 && looksExclusiveFullscreen) + return new ChromeDecision(ChromeAction.None, 0, 0, "looks like exclusive fullscreen"); + // No chrome: either we already did it (marker) or it never had any. Nothing to strip. + if (!hasChrome) + return ChromeDecision.NoChange; + // Strip. (Marker present with chrome back means the game put it back; strip again and + // remember this newer style.) + return new ChromeDecision(ChromeAction.Strip, style & ~BorderChromeMask, style, "strip"); + } + + // Setting off. + if (marker == 0) + return ChromeDecision.NoChange; // never ours: do nothing at all + if (hasChrome || (marker & WsCaption) == 0) + return new ChromeDecision(ChromeAction.ClearMarker, 0, 0, "marker stale"); + return new ChromeDecision(ChromeAction.Restore, style | (marker & BorderChromeMask), 0, "restore"); + } + + // ── Window position ────────────────────────────────────────────────── + + public const int MinWidth = 160, MinHeight = 120, MaxExtent = 16384; + private const int TitleProbeY = 16; + + internal readonly record struct Rect(int Left, int Top, int Right, int Bottom) + { + public int Width => Right - Left; + public int Height => Bottom - Top; + public bool Contains(int x, int y) => x >= Left && x < Right && y >= Top && y < Bottom; + } + + internal enum PlacementVerdict { Ok, OptedOut, ExclusiveFullscreen, TooSmall, TooLarge, OffScreen } + + /// + /// Whether is a rect worth saving or restoring. Off-screen rects (a monitor + /// that is gone) are refused: the window's centre and the middle of its top edge must both be on + /// a monitor, so neither the window nor its title bar ends up unreachable. + /// + public static PlacementVerdict EvaluatePlacement(bool optedIn, bool looksExclusiveFullscreen, + Rect r, IReadOnlyList monitors) + { + if (!optedIn) return PlacementVerdict.OptedOut; + if (looksExclusiveFullscreen) return PlacementVerdict.ExclusiveFullscreen; + if (r.Width < MinWidth || r.Height < MinHeight) return PlacementVerdict.TooSmall; + if (r.Width > MaxExtent || r.Height > MaxExtent) return PlacementVerdict.TooLarge; + int cx = r.Left + r.Width / 2; + if (!OnAnyMonitor(monitors, cx, r.Top + r.Height / 2) || !OnAnyMonitor(monitors, cx, r.Top + TitleProbeY)) + return PlacementVerdict.OffScreen; + return PlacementVerdict.Ok; + } + + private static bool OnAnyMonitor(IReadOnlyList monitors, int x, int y) + { + for (int i = 0; i < monitors.Count; i++) + if (monitors[i].Contains(x, y)) return true; + return false; + } + + /// Write only when the rect is saveable and differs from what was last written. + public static bool ShouldWritePlacement(PlacementVerdict verdict, Rect current, Rect? lastWritten) + => verdict == PlacementVerdict.Ok && (lastWritten is null || lastWritten.Value != current); + + // ── Per-client file ────────────────────────────────────────────────── + + public const string SharedFileName = "ac_window.txt"; + + /// The per-client key: "<server>/<character>" (same shape as the other per-character + /// stores), or null while no character is known. + public static string? ClientKey(string? server, string? character) + { + string c = (character ?? string.Empty).Trim(); + if (c.Length == 0) return null; + string s = (server ?? string.Empty).Trim(); + return s.Length > 0 ? s + "/" + c : c; + } + + /// + /// The file for a client's rect: "ac_window.<safe name>-<hash>.txt", or the shared + /// "ac_window.txt" when there is no key. The hash keeps names that sanitise alike apart. + /// + public static string PlacementFileName(string? key) + { + if (string.IsNullOrWhiteSpace(key)) return SharedFileName; + string k = key.Trim(); + var sb = new StringBuilder(k.Length); + foreach (char ch in k) + { + if (sb.Length >= 48) break; + sb.Append(char.IsAsciiLetterOrDigit(ch) || ch == '-' ? char.ToLowerInvariant(ch) : '_'); + } + uint h = 2166136261; // FNV-1a over the lower-cased key + foreach (char ch in k.ToLowerInvariant()) + h = (h ^ ch) * 16777619; + return "ac_window." + sb + "-" + h.ToString("x8", CultureInfo.InvariantCulture) + ".txt"; + } + + /// + /// Whether the placement file can be read or written yet, and which key it uses. The character + /// is only known after login; the shared file is the fallback once a client has gone + /// without one. + /// + public static bool TryResolveKey(string? server, string? character, long msSinceFirstTick, + long fallbackAfterMs, out string? key) + { + key = ClientKey(server, character); + if (key != null) return true; + return msSinceFirstTick >= fallbackAfterMs; // key stays null: the shared file + } + + // ── File format ────────────────────────────────────────────────────── + + public static string FormatPlacement(Rect r) + => string.Create(CultureInfo.InvariantCulture, + $"# RynthCore AC window placement - auto-generated.\nleft={r.Left}\ntop={r.Top}\nwidth={r.Width}\nheight={r.Height}\n"); + + public static bool TryParsePlacement(IEnumerable lines, out Rect rect) + { + rect = default; + int left = 0, top = 0, width = 0, height = 0; + bool haveLeft = false, haveTop = false; + 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(); + if (!int.TryParse(line[(eq + 1)..].Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int n)) continue; + if (key.Equals("left", StringComparison.OrdinalIgnoreCase)) { left = n; haveLeft = true; } + else if (key.Equals("top", StringComparison.OrdinalIgnoreCase)) { top = n; haveTop = true; } + else if (key.Equals("width", StringComparison.OrdinalIgnoreCase)) width = n; + else if (key.Equals("height", StringComparison.OrdinalIgnoreCase)) height = n; + } + if (!haveLeft || !haveTop || width <= 0 || height <= 0) return false; + rect = new Rect(left, top, left + width, top + height); + return true; + } +} diff --git a/src/RynthCore.Engine/UI/AvaloniaOverlay.cs b/src/RynthCore.Engine/UI/AvaloniaOverlay.cs index 87af52f..86e0c65 100644 --- a/src/RynthCore.Engine/UI/AvaloniaOverlay.cs +++ b/src/RynthCore.Engine/UI/AvaloniaOverlay.cs @@ -1513,6 +1513,11 @@ internal class RynthOverlayWindow : Window { try { + // Settings > Display "Remember Open Windows and Positions" (default on). + // Off: leave panels closed so a hand-arranged layout is not forced back. + if (!Plugins.EngineSettings.RememberWindowLayout) + return; + // Bar floating mode restores once AC's HWND is available. If we // pop out before that, the FloatingPanelHost ctor takes its // legacy code path (no marshal to game thread) and the layered diff --git a/src/RynthCore.Engine/UI/Data/ChatCoords.cs b/src/RynthCore.Engine/UI/Data/ChatCoords.cs index 311b697..2173866 100644 --- a/src/RynthCore.Engine/UI/Data/ChatCoords.cs +++ b/src/RynthCore.Engine/UI/Data/ChatCoords.cs @@ -4,8 +4,8 @@ // "33.6E 42.1N", "0.5S, 101.2W"), for the chat window's right-click menu // ("Arrow to ..." / "Go to ..." send them to RynthNav). // -// Runs when a line's menu opens, never per frame. No engine dependencies: -// tools/ChatCoordTests compiles this file. +// Runs when a line's menu opens or a line is measured (the underlined links), never per +// frame. No engine dependencies besides ChatSpan: tools/ChatCoordTests compiles this file. // // To keep ordinary chat from turning into coordinates ("give me 5 s, 2 e"), // a pair counts when both letters are capitals, or both numbers have a decimal @@ -53,6 +53,42 @@ internal static class ChatCoords return found; } + /// Cheap pre-check before the coordinate regex: a digit followed (soon) by a compass letter. + /// Never false for a line would find something in. + public static bool MayHaveCoords(string text) + { + for (int i = 0; i + 1 < text.Length; i++) + if (char.IsDigit(text[i])) + for (int j = i + 1; j < text.Length && j <= i + 2; j++) + if ("NnSsEeWw".IndexOf(text[j]) >= 0) return true; + return false; + } + + /// + /// The rules' highlight spans with the coordinate links laid over them: a link keeps its own + /// colour (), and any highlight it overlaps is cut around it. The result + /// is sorted by start and never overlaps (given sorted, non-overlapping spans and coords). + /// + public static ChatSpan[] LinkSpans(ChatSpan[]? spans, List coords, uint linkArgb) + { + var result = new List(); + foreach (ChatSpan s in spans ?? Array.Empty()) + { + int a = s.Start, b = s.Start + s.Length; + foreach (ChatCoord c in coords) + { + int ca = c.Start, cb = c.Start + c.Length; + if (cb <= a || ca >= b) continue; + if (ca > a) result.Add(new ChatSpan(a, ca - a, s.Argb)); + a = Math.Max(a, cb); + } + if (b > a) result.Add(new ChatSpan(a, b - a, s.Argb)); + } + foreach (ChatCoord c in coords) result.Add(new ChatSpan(c.Start, c.Length, linkArgb)); + result.Sort((x, y) => x.Start.CompareTo(y.Start)); + return result.ToArray(); + } + private static void Collect(Regex rx, string text, bool nsFirst, List found) { foreach (Match m in rx.Matches(text)) diff --git a/src/RynthCore.Engine/UI/Data/ChatData.cs b/src/RynthCore.Engine/UI/Data/ChatData.cs index dfe6464..e88043d 100644 --- a/src/RynthCore.Engine/UI/Data/ChatData.cs +++ b/src/RynthCore.Engine/UI/Data/ChatData.cs @@ -92,6 +92,8 @@ internal sealed unsafe class ChatSource : UiSource protected internal override void Poll() { + // Another client saved the shared settings: pick up its rules / filters (every 2 s at most). + ChatModel.PollSettingsFile(); try { PollLines(); } finally { @@ -392,14 +394,7 @@ internal static class ChatModel }; /// The channel tab a ChatMessageType lands in; mirrors ChatClassifier.ChannelFor in the plugin. - public static string ChannelForType(int chatType) => (uint)chatType switch - { - 0x02 or 0x03 or 0x04 or 0x0A or 0x0B or 0x0C or 0x12 or 0x13 => "Chat", - 0x08 or 0x09 => "Channels", - 0x00 or 0x05 or 0x0D or 0x14 or 0x17 or 0x18 or 0x19 or 0x1F => "System", - 0x06 or 0x07 or 0x11 or 0x15 or 0x16 => "Combat", - _ => "Other", - }; + public static string ChannelForType(int chatType) => ChatRetailVerdict.ChannelForType(chatType); public static string ConditionLabel(string when) { @@ -421,6 +416,11 @@ internal static class ChatModel public static volatile bool ShowTimestamps = true; /// Highlight your character's name (and MentionWords) in chat and channel lines. public static volatile bool MentionHighlight = true; + /// + /// A line the rules or standard filters hide is also kept out of AC's own chat window, not + /// just RynthChat's (ShouldHideInRetail, from PluginManager's held-line verdict). + /// + public static volatile bool HideInRetailChat = true; /// A short system beep on a new mention (at most every 3 s). public static volatile bool MentionSound; /// Extra words to highlight, comma-separated. @@ -739,6 +739,34 @@ internal static class ChatModel return router; } + // The retail-chat verdict's own router: no hit counting (RynthChat's pass already counts the + // same line), rebuilt when the rules or the name change. Pump thread only, like PumpRouter. + private static (long Version, string Name, ChatRouter Router)? _retailRouter; + + /// + /// True when the rules or standard filters hide this incoming line, so AC shouldn't print + /// it either (HideInRetailChat). Pump thread (PluginManager, before the held line's verdict). + /// The channel is worked out the way the RynthChat plugin files the line (ChatRetailVerdict). + /// + internal static bool ShouldHideInRetail(string? text, int chatType) + { + if (!HideInRetailChat || string.IsNullOrEmpty(text)) return false; + string line = ChatSource.StripAcLinks(text, out _); + if (line.Length == 0) return false; + + string name = PumpCharacterName(); + long version = FiltersVersion; + var cached = _retailRouter; + ChatRouter router; + if (cached is { } c && c.Version == version && c.Name == name) router = c.Router; + else + { + router = new ChatRouter(Filters, mention: null, name, countHits: false); + _retailRouter = (version, name, router); + } + return ChatRetailVerdict.IsHidden(router, line, chatType); + } + /// A router for the rule editor's test box (UI thread, on an edit). public static ChatRouter TestRouter() { @@ -1309,13 +1337,54 @@ internal static class ChatModel LoadSettings(); } + // Every client shares rynthchat_settings.json and saves its whole state, so a client that + // never re-read the file wrote back stale presets/rules over another client's change (last + // writer won; a ticked standard filter came back off). Each client now re-reads the file + // when someone else changes it (PollSettingsFile). SharedFileWatch remembers this client's own + // last write, so its own saves don't count as a change. + private static readonly SharedFileWatch SettingsWatch = new(pollMs: 2000); + + /// + /// Pump thread (ChatSource.Poll): reloads the settings when another client saved the file. + /// Rules, standard filters, tabs and display options follow; this client's selected tab stays. + /// + internal static void PollSettingsFile() + { + if (Volatile.Read(ref _settingsLoaded) == 0) return; + try + { + string? json = SettingsWatch.Changed(Environment.TickCount64, SettingsPath); // null: nobody else saved + if (json == null) return; + RynthLog.UI("ChatModel: rynthchat_settings.json changed (another client saved it); reloading the rules and filters."); + LoadSettings(json, reload: true); + } + catch (Exception ex) { RynthLog.UI($"ChatModel: settings re-read failed ({ex.GetType().Name}: {ex.Message})."); } + } + private static void LoadSettings() { try { string path = SettingsPath; if (!File.Exists(path)) return; - var dto = JsonSerializer.Deserialize(File.ReadAllText(path), RynthChatJsonContext.Default.RynthChatSettingsDto); + SettingsWatch.Seen(File.GetLastWriteTimeUtc(path)); + LoadSettings(File.ReadAllText(path), reload: false); + } + catch (Exception ex) + { + RynthLog.UI($"ChatModel: settings load failed: {ex.Message}"); + KeepUnreadable(); + } + } + + /// Another client changed the file: presets it doesn't list go off, and + /// this client's selected tab is kept. + private static void LoadSettings(string json, bool reload) + { + try + { + string path = SettingsPath; + var dto = JsonSerializer.Deserialize(json, RynthChatJsonContext.Default.RynthChatSettingsDto); if (dto == null) return; if (dto.Version < SettingsVersion) @@ -1338,6 +1407,7 @@ internal static class ChatModel AvaloniaOverlay.ChatCtrlGatedClickThrough = dto.CtrlGatedClickThrough; ShowTimestamps = dto.ShowTimestamps; MentionHighlight = dto.MentionHighlight; + HideInRetailChat = dto.HideInRetail ?? true; // absent before 2026-10-16: on MentionSound = dto.MentionSound; MentionWords = dto.MentionWords ?? ""; HistoryLines = ChatHistory.Clamp(dto.HistoryLines ?? 0); // absent before 2026-10-11: the default @@ -1358,6 +1428,13 @@ internal static class ChatModel && !IsBaseTab(rule.Tab) && !tabs.Contains(rule.Tab, StringComparer.OrdinalIgnoreCase)) tabs.Add(rule.Tab); } + // The file lists only presets that are on or moved; on a reload every other one goes back off. + if (reload) + foreach (var preset in RynthCore.Engine.UI.Panels.RynthChatPresets.All) + { + preset.Enabled = false; + preset.Tab = ""; + } foreach (RynthChatPresetDto p in dto.Presets ?? Array.Empty()) { var preset = p.Id == null ? null : RynthCore.Engine.UI.Panels.RynthChatPresets.Get(p.Id); @@ -1372,13 +1449,15 @@ internal static class ChatModel _filters = rules.ToArray(); Interlocked.Increment(ref _filtersVersion); - if (!string.IsNullOrEmpty(dto.ActiveChannel) && AllTabs().Contains(dto.ActiveChannel, StringComparer.OrdinalIgnoreCase)) + if (!reload && !string.IsNullOrEmpty(dto.ActiveChannel) && AllTabs().Contains(dto.ActiveChannel, StringComparer.OrdinalIgnoreCase)) ActiveChannel = dto.ActiveChannel; + else if (reload && !AllTabs().Contains(ActiveChannel, StringComparer.OrdinalIgnoreCase)) + ActiveChannel = "All"; // the tab this client was on was removed elsewhere } - catch (Exception ex) + catch (Exception ex) when (reload) { - RynthLog.UI($"ChatModel: settings load failed: {ex.Message}"); - KeepUnreadable(); + // A half-written or broken file from another client: keep what this client has. + RynthLog.UI($"ChatModel: settings re-read skipped (unreadable: {ex.Message})."); } } @@ -1415,6 +1494,7 @@ internal static class ChatModel ActiveChannel = ActiveChannel, ShowTimestamps = ShowTimestamps, MentionHighlight = MentionHighlight, + HideInRetail = HideInRetailChat, MentionSound = MentionSound, MentionWords = MentionWords, // Left out at the default, so a file follows the default if it ever changes. @@ -1440,7 +1520,10 @@ internal static class ChatModel string tmp = $"{path}.{Environment.ProcessId}.tmp"; // every client shares the file try { - File.WriteAllText(tmp, JsonSerializer.Serialize(dto, RynthChatJsonContext.Default.RynthChatSettingsDto)); + string json = JsonSerializer.Serialize(dto, RynthChatJsonContext.Default.RynthChatSettingsDto); + // Before the swap: PollSettingsFile must see this text as ours, not another client's. + SettingsWatch.Saved(json); + File.WriteAllText(tmp, json); File.Move(tmp, path, overwrite: true); } catch diff --git a/src/RynthCore.Engine/UI/Data/ChatFilterPresets.cs b/src/RynthCore.Engine/UI/Data/ChatFilterPresets.cs index 5cdf759..db348ec 100644 --- a/src/RynthCore.Engine/UI/Data/ChatFilterPresets.cs +++ b/src/RynthCore.Engine/UI/Data/ChatFilterPresets.cs @@ -142,6 +142,53 @@ internal static class ChatFilterPresets L("Olthoi Swarm Gardener blisters your lower leg for 1 point of acid damage!", "Combat", EnemyCombat) }, new[] { L("You evaded Tusker Guard!", "Combat", EnemyCombat), L("Bob says, \"it hit your head for 5 points of damage\"", "Chat", Say) }), + new("combat.melee_dealt", "Combat", "Melee / missile damage you deal", + "You slash … for N points of … damage!", + ChatMatchMode.Regex, @"^(?:(?:Critical [Hh]it|Sneak Attack|Recklessness)!\s+)*You \S+ .+ for \d+ points? of .+ damage", "chan:Combat", + new[] { L("You slash Drudge Slinker for 54 points of slashing damage!", "Combat", 22), + L("Recklessness! You slash Drudge for 80 points of slashing damage!", "Combat", 22) }, + new[] { L("Bob says, \"You slash for fun\"", "Chat", Say) }), + new("combat.magic_dealt", "Combat", "Magic damage you deal", + "You … for N points with SpellName.", + ChatMatchMode.Regex, @"^(?:(?:Critical [Hh]it|Sneak Attack|Recklessness)!\s+)*You \S+ .+ for \d+ points? with ", "chan:Combat", + new[] { L("You freeze Drudge Slinker for 120 points with Frost Bolt VI.", "Combat", Magic) }, + new[] { L("Bob says, \"points with Frost Bolt\"", "Chat", Say) }), + new("combat.melee_taken", "Combat", "Melee / missile damage you take", + "… your foot for N points of … damage!", + ChatMatchMode.Regex, @"^(?:(?:Critical [Hh]it|Sneak Attack|Recklessness)!\s+)*(?!You ).+ your [a-z ]+ for \d+ points? of .+ damage", "type:21", + new[] { L("Tusker Guard grazes your foot for 4 points of bludgeoning damage!", "Combat", EnemyCombat), + L("Critical hit! Olthoi Swarm Nymph nicks your head for 21 points of piercing damage!", "Combat", EnemyCombat) }, + new[] { L("Bob says, \"your foot for 5 points\"", "Chat", Say) }), + new("combat.magic_taken", "Combat", "Magic damage you take", + "… you for N points with SpellName.", + ChatMatchMode.Regex, @"^(?:(?:Critical [Hh]it|Sneak Attack|Recklessness)!\s+)*(?!You ).+ you for \d+ points? with ", "chan:Combat", + new[] { L("Drudge Sorcerer scorches you for 40 points with Flame Bolt III.", "Combat", Magic) }, + new[] { L("Bob says, \"you for 40 points with\"", "Chat", Say) }), + new("combat.recklessness", "Combat", "Recklessness hits", + "Recklessness! …", + ChatMatchMode.Contains, "Recklessness!", "chan:Combat", + new[] { L("Recklessness! You slash Drudge for 80 points of slashing damage!", "Combat", 22) }, + new[] { L("Bob says, \"Recklessness!\"", "Chat", Say) }), + new("combat.sneak_attack", "Combat", "Sneak Attack hits", + "Sneak Attack! …", + ChatMatchMode.Contains, "Sneak Attack!", "chan:Combat", + new[] { L("Sneak Attack! You slash Drudge for 54 points of slashing damage!", "Combat", 22) }, + new[] { L("Bob says, \"Sneak Attack!\"", "Chat", Say) }), + new("combat.periodic_healing", "Combat", "Periodic healing ticks", + "You receive N points of periodic healing.", + ChatMatchMode.Regex, @"^You receive \d+ points of periodic healing", "", + new[] { L("You receive 12 points of periodic healing.", "Other", Notice) }, + new[] { L("Bob says, \"periodic healing\"", "Chat", Say) }), + new("combat.stamina", "Combat", "Stamina restore / spend", + "Restore / lose / gain stamina lines (Combat channel).", + ChatMatchMode.Regex, @"(?:restore|restores|regain|lose|loses) \d+ points? of (?:your )?stamina\b", "chan:Combat", + new[] { L("You cast Revitalize Self V and restore 40 points of your stamina.", "Combat", Magic) }, + new[] { L("Bob says, \"restore 40 points of your stamina\"", "Chat", Say) }), + new("combat.mana", "Combat", "Mana restore / spend", + "Restore / gain / lose mana lines (Combat channel).", + ChatMatchMode.Regex, @"(?:restore|restores|regain|gain|gains|lose|loses) \d+ points? of (?:your )?mana\b|and also gain \d+ points of mana", "chan:Combat", + new[] { L("You cast Stamina to Mana Self V on yourself and lose 17 points of stamina and also gain 23 points of mana", "Combat", Magic) }, + new[] { L("Bob says, \"gain 23 points of mana\"", "Chat", Say) }), // ── Notices ───────────────────────────────────────────────────── new("notice.busy", "Notices", "You're too busy", @@ -179,6 +226,63 @@ internal static class ChatFilterPresets ChatMatchMode.StartsWith, "[LFG]", "", new[] { L("[LFG] Bob says, \"LF tank for the Graveyard\"", "Other", ServerChannel) }, Array.Empty<(string, string, int)>()), + + // ── Combat extras and items (UB-IT ChatFilterTool / classic ChatHandler) ────── + new("combat.attack_resists", "Combat", "Your spells resisted", + "A target resists one of your spells.", + ChatMatchMode.Contains, " resists your spell", "chan:Combat", + new[] { L("Drudge Slinker resists your spell", "Combat", EnemyCombat) }, + new[] { L("Bob says, \"it resists your spell\"", "Chat", Say) }), + new("combat.defense_resists", "Combat", "You resist spells", + "You resist a spell cast by a monster.", + ChatMatchMode.StartsWith, "You resist the spell cast by ", "chan:Combat", + new[] { L("You resist the spell cast by Drudge Sorcerer", "Combat", EnemyCombat) }, + new[] { L("Bob says, \"You resist the spell cast by him\"", "Chat", Say) }), + new("combat.dirty_fighting", "Combat", "Dirty Fighting procs", + "Dirty Fighting assault announcements.", + ChatMatchMode.StartsWith, "Dirty Fighting! ", "", + new[] { L("Dirty Fighting! Bob delivers a Traumatic Assault to Drudge!", "Combat", EnemyCombat) }, + new[] { L("Bob says, \"Dirty Fighting!\"", "Chat", Say) }), + new("combat.missile_miss", "Combat", "Missile hit the environment", + "Your missile attack hit the environment.", + ChatMatchMode.StartsWith, "Your missile attack hit the environment", "", + new[] { L("Your missile attack hit the environment.", "Combat", EnemyCombat) }, + Array.Empty<(string, string, int)>()), + new("item.heal_ok", "Items", "Healing kit success", + "You heal yourself for N Health points…", + ChatMatchMode.Contains, " heal yourself for ", "", + new[] { L("You heal yourself for 80 Health points. Your Treated Healing Kit has 16 uses left.", "Other", Notice) }, + new[] { L("Bob says, \"heal yourself for fun\"", "Chat", Say) }), + new("item.salvage", "Items", "Salvage results", + "You obtain … using your knowledge of …", + ChatMatchMode.Regex, @"^You obtain .+ using your knowledge of ", "", + new[] { L("You obtain 12 Steel (ws 7.00) using your knowledge of Weapon Tinkering.", "Other", Notice) }, + Array.Empty<(string, string, int)>()), + new("item.aetheria_surge", "Items", "Aetheria surges", + "Aetheria surges on…", + ChatMatchMode.StartsWith, "Aetheria surges on", "", + new[] { L("Aetheria surges on Bob, increasing his damage.", "Other", Notice) }, + Array.Empty<(string, string, int)>()), + new("item.banked_lum", "Items", "Banked luminance", + "You've banked N Luminance.", + ChatMatchMode.StartsWith, "You've banked ", "", + new[] { L("You've banked 1,250 Luminance.", "Other", Notice) }, + Array.Empty<(string, string, int)>()), + new("social.kill_task", "Social", "Kill task complete", + "You have killed N Xs! Your task is complete!", + ChatMatchMode.Regex, @"^You have killed \d+ .+Your task is complete!", "", + new[] { L("You have killed 50 Drudges! Your task is complete!", "Other", Notice) }, + Array.Empty<(string, string, int)>()), + new("social.kill_task_progress", "Social", "Kill task progress", + "You have killed N Xs! You must kill M to complete your task.", + ChatMatchMode.Regex, @"^You have killed \d+ .+! You must kill \d+ to complete your task\.", "", + new[] { L("You have killed 12 Drudges! You must kill 50 to complete your task.", "Other", Notice) }, + Array.Empty<(string, string, int)>()), + new("cast.expires", "Casting", "Spell expiry", + "… has expired. (does not spare rares — use Standard filters for that).", + ChatMatchMode.Contains, "has expired.", "type:7", + new[] { L("Strength Self VII has expired.", "Combat", Magic) }, + new[] { L("Bob tells you, \"has expired.\"", "Chat", Tell) }), }; public static ChatFilterPreset? Get(string id) diff --git a/src/RynthCore.Engine/UI/Data/ChatRetailVerdict.cs b/src/RynthCore.Engine/UI/Data/ChatRetailVerdict.cs new file mode 100644 index 0000000..ec40f06 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/ChatRetailVerdict.cs @@ -0,0 +1,66 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/ChatRetailVerdict.cs +// Whether RynthChat's Hide rules / standard filters keep an incoming line out of +// AC's own chat window too (ChatModel.ShouldHideInRetail, asked from the plugin +// pump before a held line's verdict). The pure part, so tools/ChatFilterTests can +// run the real router over it: which channel the RynthChat plugin files the line +// under, and whether the rules hide it. +// +// Idea from Silentkelpie (rynth PR 6, 2026.10.16.23). The channel order follows the +// plugin's ChatBuffer.Add: RynthAi item info, then "[Rynth..." output, then a +// [General]/[Trade]-style tag, then the chat type. +// ============================================================================ + +using System; + +namespace RynthCore.Engine.UI.Data; + +internal static class ChatRetailVerdict +{ + /// RynthAi's item info prefix (RynthChat's ChatClassifier.IsItemInfo): the Items tab. + public const string ItemInfoPrefix = "[RynthAi Item] "; + + /// + /// The channel tab the RynthChat plugin files an incoming line under, so a rule held to a + /// channel ("chan:Channels") sees the same channel for the retail verdict as for RynthChat. + /// + public static string ChannelFor(string line, int chatType) + { + if (line.StartsWith(ItemInfoPrefix, StringComparison.Ordinal)) return "Items"; + if (line.StartsWith("[Rynth", StringComparison.OrdinalIgnoreCase)) return "Rynth"; + if (IsChannelTagged(line)) return "Channels"; + return ChannelForType(chatType); + } + + /// The channel tab for an AC ChatMessageType alone. + public static string ChannelForType(int chatType) => (uint)chatType switch + { + 0x02 or 0x03 or 0x04 or 0x0A or 0x0B or 0x0C or 0x12 or 0x13 => "Chat", + // 0x08/0x09 = retail channel; 0x1C (28) = ILT/ACECustom tagged [Trade]/[General] lines. + 0x08 or 0x09 or 0x1C => "Channels", + 0x00 or 0x05 or 0x0D or 0x14 or 0x17 or 0x18 or 0x19 or 0x1F => "System", + 0x06 or 0x07 or 0x11 or 0x15 or 0x16 => "Combat", + _ => "Other", + }; + + /// The RynthChat plugin's channel tags (ChatClassifier.IsChannelTagged): "[Trade] ..." etc. + public static bool IsChannelTagged(string text) => + text.Length > 0 && text[0] == '[' + && (text.StartsWith("[General]", StringComparison.OrdinalIgnoreCase) + || text.StartsWith("[Trade]", StringComparison.OrdinalIgnoreCase) + || text.StartsWith("[LFG]", StringComparison.OrdinalIgnoreCase) + || text.StartsWith("[Roleplay]", StringComparison.OrdinalIgnoreCase) + || text.StartsWith("[Society]", StringComparison.OrdinalIgnoreCase) + || text.StartsWith("[Celestial Hand]", StringComparison.OrdinalIgnoreCase) + || text.StartsWith("[Eldrytch Web]", StringComparison.OrdinalIgnoreCase) + || text.StartsWith("[Radiant Blood]", StringComparison.OrdinalIgnoreCase) + || text.StartsWith("[Admin]", StringComparison.OrdinalIgnoreCase)); + + /// + /// True when (the rules, then the ticked standard filters) hides the + /// line. A rule or filter that only moves or copies a line to a tab is not a hide: that line + /// still prints in AC's window. + /// + public static bool IsHidden(ChatRouter router, string line, int chatType) => + router.Evaluate(line, ChannelFor(line, chatType), chatType, null).Hidden; +} diff --git a/src/RynthCore.Engine/UI/Data/ChatSettingsDto.cs b/src/RynthCore.Engine/UI/Data/ChatSettingsDto.cs index 87ba2b3..5654d10 100644 --- a/src/RynthCore.Engine/UI/Data/ChatSettingsDto.cs +++ b/src/RynthCore.Engine/UI/Data/ChatSettingsDto.cs @@ -57,6 +57,8 @@ internal sealed class RynthChatSettingsDto [JsonPropertyName("activeChannel")] public string? ActiveChannel { get; set; } [JsonPropertyName("showTimestamps")] public bool ShowTimestamps { get; set; } = true; [JsonPropertyName("mentionHighlight")] public bool MentionHighlight { get; set; } = true; + /// Hidden lines are also kept out of AC's chat window; null (older files) = on. + [JsonPropertyName("hideInRetail")] public bool? HideInRetail { get; set; } [JsonPropertyName("mentionSound")] public bool MentionSound { get; set; } [JsonPropertyName("mentionWords")] public string? MentionWords { get; set; } // 2026-10-08: per-kind line colours (ChatLineColors), { "say": "#RRGGBB", "chan:General": ..., "tab:Chat": ... }; diff --git a/src/RynthCore.Engine/UI/Data/DamageData.cs b/src/RynthCore.Engine/UI/Data/DamageData.cs index 0c4b849..dbb4f28 100644 --- a/src/RynthCore.Engine/UI/Data/DamageData.cs +++ b/src/RynthCore.Engine/UI/Data/DamageData.cs @@ -676,22 +676,22 @@ internal static unsafe class DamageCommands MonstersPanel.Rule? from = string.IsNullOrEmpty(copyFrom) ? null : rules.Rules.Find(r => !IsDefault(r) && r.Name.Equals(copyFrom, StringComparison.OrdinalIgnoreCase)); MonstersPanel.Rule clone = CopyOfDefault(from ?? s, name); - if (from != null) { clone.OffhandId = from.OffhandId; clone.PetDamage = from.PetDamage; clone.PreferredDamage = from.PreferredDamage; } // a name rule's own choices, kept + if (from != null) { clone.OffhandId = from.OffhandId; clone.PetDamage = from.PetDamage; clone.AttackPower = from.AttackPower; clone.Kite = from.Kite; clone.PreferredDamage = from.PreferredDamage; } // a name rule's own choices, kept rules.Rules.Insert(defIdx >= 0 ? defIdx + 1 : 0, clone); return clone; } /// - /// A new rule named with Default's settings. Off hand, pet and preferred - /// damage are left on "follow Default" (0 / PAuto / Auto) rather than copied, so a later change - /// on the DEFAULT line still reaches it. + /// A new rule named with Default's settings. Off hand, pet, attack + /// power, kite and preferred damage are left on "follow Default" (0 / PAuto / Default / + /// Default / Auto) rather than copied, so a later change on the DEFAULT line still reaches it. /// private static MonstersPanel.Rule CopyOfDefault(MonstersPanel.Rule s, string name) => new() { Name = name, Category = s.Category, MatchExpression = "", // an exact-name rule matches by name, not by a (possibly false) expression Priority = s.Priority, DamageType = s.DamageType, WeaponId = s.WeaponId, OffhandId = 0, - ExVuln = s.ExVuln, PetDamage = "PAuto", PreferredDamage = "Auto", + ExVuln = s.ExVuln, PetDamage = "PAuto", AttackPower = "Default", Kite = "Default", PreferredDamage = "Auto", Fester = s.Fester, Broadside = s.Broadside, GravityWell = s.GravityWell, Imperil = s.Imperil, Yield = s.Yield, Vuln = s.Vuln, UseArc = s.UseArc, UseBolt = s.UseBolt, UseRing = s.UseRing, UseStreak = s.UseStreak, UseBlast = s.UseBlast, UseWall = s.UseWall, @@ -793,6 +793,14 @@ internal static unsafe class DamageCommands /// Rule.OffhandId as RynthAi reads it: 0 = follow the DEFAULT line, 1-4 a mode, anything else an item id. public static readonly string[] OffhandModeNames = { "Default", "Auto", "Shield", "Dual wield", "None" }; + /// Rule.AttackPower choices, spelled as RynthAi reads them (AttackPowerModes). + public static readonly string[] AttackPowerModes = + { "Default", "High", "Reckless", "Variable", "Reckless + Variable" }; + + /// Rule.Kite choices, spelled as RynthAi reads them (KiteModes). + public static readonly string[] KiteModes = + { "Default", "Off", "PullAway" }; + /// Rule.PetDamage choices; "PAuto" is shown as Auto. public static readonly string[] PetDamageTypes = { "PAuto", "Slash", "Pierce", "Bludgeon", "Fire", "Cold", "Lightning", "Acid", "Nether" }; diff --git a/src/RynthCore.Engine/UI/Data/EnlRowConverters.cs b/src/RynthCore.Engine/UI/Data/EnlRowConverters.cs new file mode 100644 index 0000000..1e01df4 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/EnlRowConverters.cs @@ -0,0 +1,167 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/EnlRowConverters.cs +// Lenient readers for the Enl calculator's row arrays (levels / materials / chain +// in the Progression snapshot). The calculator is an add-on of the planner: a bad +// field in it must not turn the whole Progression snapshot into "unavailable" (the +// default for a JsonException), which would also hide the Augmentation planner and +// the attribute raiser. So: +// - null, or anything that is not an array, reads as an empty array; +// - a row that is not an object is skipped; +// - a field of the wrong type keeps its default, other fields of the row still read; +// - unknown fields are ignored; at most MaxRows rows are kept (RynthILT sends 100 at most). +// Read only (the engine never writes this JSON). No reflection: safe under trimming / NativeAOT. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace RynthCore.Engine.UI.Data; + +/// Reads a JSON array of row objects, tolerating whatever else shows up. +internal abstract class EnlRowsConverter : JsonConverter where TRow : class +{ + /// Rows kept per array; the producer's own cap is 100 (levels). + internal const int MaxRows = 200; + + // A JSON null reaches Read (and becomes an empty array) instead of null. + public override bool HandleNull => true; + + /// Reads one row. The reader is on its StartObject; leave it on the matching EndObject. + protected abstract TRow ReadRow(ref Utf8JsonReader reader); + + public override TRow[] Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType != JsonTokenType.StartArray) + { + reader.Skip(); // a scalar stays as it is, an object is skipped whole + return Array.Empty(); + } + + var rows = new List(); + while (reader.Read() && reader.TokenType != JsonTokenType.EndArray) + { + if (reader.TokenType != JsonTokenType.StartObject) + { + reader.Skip(); + continue; + } + TRow row = ReadRow(ref reader); + if (rows.Count < MaxRows) rows.Add(row); + } + return rows.Count == 0 ? Array.Empty() : rows.ToArray(); + } + + public override void Write(Utf8JsonWriter writer, TRow[] value, JsonSerializerOptions options) + => throw new NotSupportedException("The Enl calculator rows are read-only."); + + // -- Field readers: the reader is on the value; each consumes exactly that value. -- + + protected static int ReadInt(ref Utf8JsonReader reader, int fallback = 0) + { + long v = ReadLong(ref reader, fallback); + return v > int.MaxValue ? int.MaxValue : v < int.MinValue ? int.MinValue : (int)v; + } + + protected static long ReadLong(ref Utf8JsonReader reader, long fallback = 0) + { + switch (reader.TokenType) + { + case JsonTokenType.Number: + if (reader.TryGetInt64(out long l)) return l; + if (reader.TryGetDouble(out double d) && double.IsFinite(d)) + return d >= long.MaxValue ? long.MaxValue : d <= long.MinValue ? long.MinValue : (long)d; + return fallback; + case JsonTokenType.String: + return long.TryParse(reader.GetString(), NumberStyles.Integer | NumberStyles.AllowThousands, + CultureInfo.InvariantCulture, out long s) ? s : fallback; + default: + reader.Skip(); + return fallback; + } + } + + protected static bool ReadBool(ref Utf8JsonReader reader, bool fallback = false) + { + switch (reader.TokenType) + { + case JsonTokenType.True: return true; + case JsonTokenType.False: return false; + default: + reader.Skip(); + return fallback; + } + } + + protected static string ReadString(ref Utf8JsonReader reader, string fallback = "") + { + switch (reader.TokenType) + { + case JsonTokenType.String: return reader.GetString() ?? fallback; + case JsonTokenType.Number: return Encoding.UTF8.GetString(reader.ValueSpan); + default: + reader.Skip(); + return fallback; + } + } + + /// Moves to the next property name of the object being read; false at its EndObject. + protected static bool NextProperty(ref Utf8JsonReader reader) + => reader.Read() && reader.TokenType == JsonTokenType.PropertyName; +} + +internal sealed class EnlLevelRowsConverter : EnlRowsConverter +{ + protected override EnlLevelRow ReadRow(ref Utf8JsonReader reader) + { + var row = new EnlLevelRow(); + while (NextProperty(ref reader)) + { + if (reader.ValueTextEquals("t")) { reader.Read(); row.Level = ReadInt(ref reader); } + else if (reader.ValueTextEquals("item")) { reader.Read(); row.Item = ReadString(ref reader, "-"); } + else if (reader.ValueTextEquals("count")) { reader.Read(); row.Count = ReadInt(ref reader); } + else if (reader.ValueTextEquals("lum")) { reader.Read(); row.Lum = ReadString(ref reader, "-"); } + else if (reader.ValueTextEquals("ok")) { reader.Read(); row.Ok = ReadBool(ref reader); } + else { reader.Read(); reader.Skip(); } + } + return row; + } +} + +internal sealed class EnlMaterialRowsConverter : EnlRowsConverter +{ + protected override EnlMaterialRow ReadRow(ref Utf8JsonReader reader) + { + var row = new EnlMaterialRow(); + while (NextProperty(ref reader)) + { + if (reader.ValueTextEquals("label")) { reader.Read(); row.Label = ReadString(ref reader); } + else if (reader.ValueTextEquals("need")) { reader.Read(); row.Need = ReadString(ref reader, "0"); } + else if (reader.ValueTextEquals("have")) { reader.Read(); row.Have = ReadString(ref reader, "0"); } + else if (reader.ValueTextEquals("ok")) { reader.Read(); row.Ok = ReadBool(ref reader); } + else { reader.Read(); reader.Skip(); } + } + return row; + } +} + +internal sealed class EnlChainRowsConverter : EnlRowsConverter +{ + protected override EnlChainRow ReadRow(ref Utf8JsonReader reader) + { + var row = new EnlChainRow(); + while (NextProperty(ref reader)) + { + if (reader.ValueTextEquals("label")) { reader.Read(); row.Label = ReadString(ref reader); } + else if (reader.ValueTextEquals("need")) { reader.Read(); row.Need = ReadLong(ref reader); } + else if (reader.ValueTextEquals("have")) { reader.Read(); row.Have = ReadLong(ref reader); } + else if (reader.ValueTextEquals("ok")) { reader.Read(); row.Ok = ReadBool(ref reader); } + else if (reader.ValueTextEquals("craft")) { reader.Read(); row.Craft = ReadBool(ref reader); } + else { reader.Read(); reader.Skip(); } + } + return row; + } +} diff --git a/src/RynthCore.Engine/UI/Data/LootEditData.cs b/src/RynthCore.Engine/UI/Data/LootEditData.cs index 3a89213..ee7361f 100644 --- a/src/RynthCore.Engine/UI/Data/LootEditData.cs +++ b/src/RynthCore.Engine/UI/Data/LootEditData.cs @@ -141,9 +141,55 @@ internal sealed class LootEditItemRequestDto public bool ToOpenProfile { get; set; } /// Also require the item's T11 attributes (added 2026-10-07; an older RynthAi ignores it). public bool IncludeT11 { get; set; } + /// The attribute checklist's choices (added 2026-10-18); null: every row at its default. + public List? Choices { get; set; } public int Seq { get; set; } } +/// One checklist row as the player set it (LootEditWire's LootEditItemChoice). +internal sealed class LootEditItemChoiceDto +{ + public string Id { get; set; } = string.Empty; + public bool On { get; set; } + /// A comparison code (LootAttrOps); -1 = the row's default. + public int Op { get; set; } = -1; + /// The typed value; empty = the item's own. + public string Value { get; set; } = string.Empty; +} + +/// One row of the popup's attribute checklist (LootEditWire's LootEditItemAttribute). +internal sealed class LootEditItemAttributeDto +{ + public string Id { get; set; } = string.Empty; + public string Group { get; set; } = string.Empty; + public string Label { get; set; } = string.Empty; + public string ItemValue { get; set; } = string.Empty; + public string Value { get; set; } = string.Empty; + public int Op { get; set; } + public List Ops { get; set; } = new(); + public bool Editable { get; set; } + public bool On { get; set; } + public string Tip { get; set; } = string.Empty; +} + +/// The checklist's comparison codes (LootSdk LootItemAttributeOp) and how the popup labels them. +internal static class LootAttrOps +{ + public const int AtLeast = 0, Exactly = 1, AtMost = 2, Not = 3, SpellExact = 10, SpellOrBetter = 11, SpellAnyTier = 12; + + public static string Label(int op) => op switch + { + AtLeast => ">=", + Exactly => "=", + AtMost => "<=", + Not => "not", + SpellExact => "exact", + SpellOrBetter => "or better", + SpellAnyTier => "any tier", + _ => "?", + }; +} + /// The rule an item makes and what an add did (LootEditWire's LootEditItemDraft). internal sealed class LootEditItemDraftDto { @@ -172,6 +218,10 @@ internal sealed class LootEditItemDraftDto public int RuleCount { get; set; } public string OrderNote { get; set; } = string.Empty; public List Notes { get; set; } = new(); + /// RynthAi has the attribute checklist (added 2026-10-18; false from an older one: the T11 box shows instead). + public bool AttributesSupported { get; set; } + /// The item's checklist rows in display order (added 2026-10-18). + public List Attributes { get; set; } = new(); public bool Added { get; set; } public string Message { get; set; } = string.Empty; } diff --git a/src/RynthCore.Engine/UI/Data/ProgressionData.cs b/src/RynthCore.Engine/UI/Data/ProgressionData.cs index 43e700d..62af741 100644 --- a/src/RynthCore.Engine/UI/Data/ProgressionData.cs +++ b/src/RynthCore.Engine/UI/Data/ProgressionData.cs @@ -8,6 +8,7 @@ // ============================================================================ using System; +using System.Globalization; using System.Runtime.InteropServices; using System.Text.Json; using System.Text.Json.Serialization; @@ -171,6 +172,94 @@ internal sealed class EnlPlanner [JsonPropertyName("spendFirst")] public bool SpendFirst { get; set; } [JsonPropertyName("checkEvery")] public int CheckEvery { get; set; } [JsonPropertyName("status")] public string Status { get; set; } = ""; + + // Enl calculator (RynthILT's IltProgression.AppendEnlCalculatorJson; Silentkelpie's rynth PR 6): per-level + // rows, materials still-need / have, the 301-325 sigil chain and the e-coin lines. All of it is absent from + // an older RynthILT (or RynthAi) and from a server without ILT: the arrays stay empty, the strings "", and + // the calculator is not drawn. The row arrays are read leniently (see EnlRowConverters): a null, a + // non-array, a non-object row or a mistyped field costs that row, never the whole Progression snapshot. + [JsonPropertyName("levels")] [JsonConverter(typeof(EnlLevelRowsConverter))] + public EnlLevelRow[] Levels { get; set; } = Array.Empty(); + [JsonPropertyName("materials")] [JsonConverter(typeof(EnlMaterialRowsConverter))] + public EnlMaterialRow[] Materials { get; set; } = Array.Empty(); + [JsonPropertyName("chain")] [JsonConverter(typeof(EnlChainRowsConverter))] + public EnlChainRow[] Chain { get; set; } = Array.Empty(); + [JsonPropertyName("chainNote")] public string ChainNote { get; set; } = ""; + /// "E-coins needed: N have M (bank + pack)..." ("" when no e-coins are involved). + [JsonPropertyName("ecoins")] public string Ecoins { get; set; } = ""; + /// "Lum to buy e-coins: ~X" or the hint to set Lum per e-coin ("" when no coins are needed). + [JsonPropertyName("ecoinsLum")] public string EcoinsLum { get; set; } = ""; + + /// The snapshot has anything for the calculator section to draw. + [JsonIgnore] public bool HasCalculator => Levels.Length > 0 || Materials.Length > 0 || Chain.Length > 0; +} + +/// One enlightenment step of the calculator's per-level table (RynthILT lists at most 100). +internal sealed class EnlLevelRow +{ + private string? _levelText, _countText; + + /// The enlightenment level this step reaches. + [JsonPropertyName("t")] public int Level { get; set; } + /// "Tokens" / "Medallions" / "Sigils" / "Crests", or "-" for a step with no item. + [JsonPropertyName("item")] public string Item { get; set; } = "-"; + [JsonPropertyName("count")] public int Count { get; set; } + /// Luminance for the step, preformatted ("1.50B"), "-" for none. + [JsonPropertyName("lum")] public string Lum { get; set; } = "-"; + /// The simulated stock (pack items, the sigil chain, luminance) still covers this step. + [JsonPropertyName("ok")] public bool Ok { get; set; } + + // Display text, formatted once per snapshot instead of every frame. + [JsonIgnore] public string LevelText => _levelText ??= Level.ToString(CultureInfo.InvariantCulture); + [JsonIgnore] public string CountText => _countText ??= Count > 0 ? Count.ToString("N0", CultureInfo.InvariantCulture) : "-"; +} + +/// Still-need vs have for one material (or luminance); need / have arrive preformatted. +internal sealed class EnlMaterialRow +{ + [JsonPropertyName("label")] public string Label { get; set; } = ""; + [JsonPropertyName("need")] public string Need { get; set; } = "0"; + [JsonPropertyName("have")] public string Have { get; set; } = "0"; + [JsonPropertyName("ok")] public bool Ok { get; set; } +} + +/// One row of the 301-325 sigil craft chain. Craft rows count crafts left, raw rows what to get. +internal sealed class EnlChainRow +{ + private string? _needText, _haveText, _displayLabel; + + [JsonPropertyName("label")] public string Label { get; set; } = ""; + [JsonPropertyName("need")] public long Need { get; set; } + [JsonPropertyName("have")] public long Have { get; set; } + [JsonPropertyName("ok")] public bool Ok { get; set; } + /// An in-between item the player crafts (Ascension Coins, Lifeblood Elixirs, Lifebloom Resins). + [JsonPropertyName("craft")] public bool Craft { get; set; } + + /// The label with "(craft)" for an in-between item the player crafts. + [JsonIgnore] public string DisplayLabel => _displayLabel ??= Craft ? Label + " (craft)" : Label; + [JsonIgnore] public string NeedText => _needText ??= Need.ToString("N0", CultureInfo.InvariantCulture); + [JsonIgnore] public string HaveText => _haveText ??= Have.ToString("N0", CultureInfo.InvariantCulture); +} + +/// How much of the Enl calculator the Progression tab draws (pure, so it is tested). +internal static class EnlCalculatorView +{ + /// Per-level rows shown until "Show all" is pressed. + public const int PreviewLevels = 12; + /// Per-level rows drawn at most (RynthILT sends 100 at most), in a scrolling table. + public const int MaxLevels = 100; + /// Material / chain rows drawn at most (RynthILT sends 5 and 8). + public const int MaxListRows = 16; + + /// Per-level rows to draw for rows; lifts the preview limit. + public static int VisibleLevels(int total, bool showAll) + { + if (total <= 0) return 0; + return Math.Min(total, showAll ? MaxLevels : PreviewLevels); + } + + /// There are more rows than the preview shows, so the Show all toggle is offered. + public static bool CanExpand(int total) => total > PreviewLevels; } [JsonSerializable(typeof(ProgressionInfo))] @@ -201,10 +290,27 @@ internal sealed unsafe class ProgressionSource : UiSource if (_getProgressionJson == null) return; IntPtr p = _getProgressionJson(); string json = p == IntPtr.Zero ? "{}" : (_utf8 ? Marshal.PtrToStringUTF8(p) : Marshal.PtrToStringAnsi(p)) ?? "{}"; + Publish(ParseJson(json)); + } + + /// + /// The snapshot for a plugin's JSON: an unreadable payload is an empty snapshot (Available false, the tab + /// hides), never an exception. The Enl calculator's own fields degrade on their own (EnlRowConverters). + /// + internal static ProgressionInfo ParseJson(string? json) + { ProgressionInfo info; - try { info = JsonSerializer.Deserialize(json, ProgressionJsonContext.Default.ProgressionInfo) ?? new ProgressionInfo(); } + try { info = JsonSerializer.Deserialize(json ?? "{}", ProgressionJsonContext.Default.ProgressionInfo) ?? new ProgressionInfo(); } catch (JsonException) { info = new ProgressionInfo(); } - Publish(info); + EnlPlanner? enl = info.Enl; + if (enl != null) + { + // JSON null into a string property: the UI reads .Length. + enl.ChainNote ??= ""; + enl.Ecoins ??= ""; + enl.EcoinsLum ??= ""; + } + return info; } protected internal override void Reset() diff --git a/src/RynthCore.Engine/UI/Data/RynthAiData.cs b/src/RynthCore.Engine/UI/Data/RynthAiData.cs index 29af4a0..2e3189c 100644 --- a/src/RynthCore.Engine/UI/Data/RynthAiData.cs +++ b/src/RynthCore.Engine/UI/Data/RynthAiData.cs @@ -371,6 +371,7 @@ internal static unsafe class RynthAiCommands finally { Marshal.FreeHGlobal(p); } if (refreshPatrol) UiSources.Patrol.RequestRefresh(); UiSources.Nav.RequestRefresh(); // the plugin applied it: the Nav panels show it next poll + UiSources.Settings.RequestRefresh(); // Breadcrumbs / Route overlay are on Settings > Navigation too }); /// diff --git a/src/RynthCore.Engine/UI/Data/SettingsData.cs b/src/RynthCore.Engine/UI/Data/SettingsData.cs index 980061f..03ea657 100644 --- a/src/RynthCore.Engine/UI/Data/SettingsData.cs +++ b/src/RynthCore.Engine/UI/Data/SettingsData.cs @@ -124,6 +124,22 @@ internal sealed class RynthAiSettings public bool UseNativeAttack { get; set; } = true; public bool SummonPets { get; set; } public int PetMinMonsters { get; set; } = 1; + // RynthAi's Variable attack power, environment-hit throttle and pull-away kite (2026-10-12 and + // 2026-10-16; Silentkelpie's). Mirrors of RynthAi's own settings, nullable like the Vaulted + // switch below: a RynthAi that predates them omits them, the rows stay hidden, and a save + // sends null, which RynthAi leaves alone. Their defaults here are only what a row shows for a + // value that arrived. + public int? VariablePowerMin { get; set; } + public int? VariablePowerMax { get; set; } + public int? MissileEnvironmentResponse { get; set; } + public int? MagicEnvironmentResponse { get; set; } + public int? EnvironmentImpactLimit { get; set; } + public int? EnvironmentImpactWindowSec { get; set; } + public int? EnvironmentApproachMeters { get; set; } + public int? EnvironmentMinDistance { get; set; } + public int? EnvironmentSkipSec { get; set; } + public int? KitePullMeters { get; set; } + public bool? KiteTagFirst { get; set; } // Spell Combat public int SpellCastIntervalMs { get; set; } = 400; public int AttackSpellIntervalMs { get; set; } = 1500; @@ -151,6 +167,14 @@ internal sealed class RynthAiSettings public double CorpseApproachRangeMin { get; set; } = 2.0; // Navigation public bool BoostNavPriority { get; set; } + /// + /// RynthAi's "Vaulted Dungeons" setting: the master switch of RynthILT's Vaulted Dungeons keeper + /// (Infinite Leaftide / ACECustom only), off by default. It lives in the RynthAi profile (this is + /// only a mirror, so there is exactly one copy); RynthILT reads it from RynthAi. Nullable like + /// the Nav panel's switches: a RynthAi that predates it omits it, the row then stays hidden and a + /// save sends null, which RynthAi leaves alone. + /// + public bool? EnableVaultedDungeons { get; set; } public float FollowNavMin { get; set; } = 1.5f; public float NavRingThickness { get; set; } = 6f; public float NavLineThickness { get; set; } = 6f; @@ -163,6 +187,11 @@ internal sealed class RynthAiSettings // RynthAi NavResumeNearest: macro start, route loads and resuming after a pause that moved // the character head for the closest waypoint. On by default; an older plugin ignores it. public bool NavResumeNearest { get; set; } = true; + // RynthAi NavOverlay.TrackBreadcrumbs / ShowRouteMarkers: the Nav panel's Breadcrumbs and Route + // overlay switches, also on Settings > Navigation. Null = a RynthAi that doesn't send them: the + // rows hide, and a save sends null back, which RynthAi reads as unchanged. + public bool? TrackBreadcrumbs { get; set; } + public bool? ShowRouteOverlay { get; set; } // RynthAi dungeon patrol (/ra dunnav-patrol; RynthAi DungeonPatrolOptions). The defaults are // the patrol as it was before these settings; an older plugin ignores them. public int DunPatrolCoverage { get; set; } // 0 whole dungeon, 1 loops only, 2 everything, 3 sweep @@ -324,10 +353,40 @@ internal static unsafe class SettingsCommands try { _setSettingsJson(ansi); } finally { Marshal.FreeHGlobal(ansi); } UiSources.Settings.RequestRefresh(); + UiSources.Nav.RequestRefresh(); // the Nav panel's Breadcrumbs / Route overlay switches }); } } +/// +/// The optimized loot timer defaults, in ms: the same values as RynthSuite's LootBaseline.cs +/// (RynthAi), measured from live corpse looting on ACE (226 corpses, 39 pickups; from +/// Silentkelpie's PR 6). Keep the two in step. The "Use optimized defaults" button on Settings +/// writes them; the properties of keep their own initial values. +/// +internal static class LootTimerDefaults +{ + public const int ContentSettleMs = 100; + public const int EmptyCorpseMs = 300; + /// Above the 256 ms 95th percentile of the measured appraisal replies. + public const int AssessWindowMs = 300; + /// No pickup needed a retry at 1000 ms (it counts from when the character is still). + public const int RetryTimeoutMs = 1000; + public const int OpenRetryMs = 1500; + public const int CorpseTimeoutMs = 12000; + + /// Writes the six optimized defaults into . + public static void Apply(RynthAiSettings s) + { + s.LootContentSettleMs = ContentSettleMs; + s.LootEmptyCorpseMs = EmptyCorpseMs; + s.LootAssessWindowMs = AssessWindowMs; + s.LootRetryTimeoutMs = RetryTimeoutMs; + s.LootOpenRetryMs = OpenRetryMs; + s.LootCorpseTimeoutMs = CorpseTimeoutMs; + } +} + // ── Schema ───────────────────────────────────────────────────────────────── internal enum SettingKind { Bool, Int, Float, Double, Combo, Section, Spacer, Note, CraftingStatus, Button, TraceCategories, Text, Status, @@ -419,7 +478,10 @@ internal sealed record SettingRow( Func? GetText = null, Action? SetText = null, // Text rows: greyed hint shown while the box is empty. - string? Hint = null) + string? Hint = null, + // Button rows that change settings: applied to the panel's copy, which is then saved like + // any other edit (Click, when also set, runs after). + Action? Edit = null) { public bool IsVisible(RynthAiSettings s) => VisibleWhen == null || VisibleWhen(s); } @@ -430,12 +492,23 @@ internal static class SettingsSchema { // Also drawn on the Nav panel (ImGui/Panels/NavFace.cs). public const string NavPointReachLabel = "Nav point reach (yd)"; + /// The Navigation row of RynthAi's Vaulted Dungeons master switch (). + public const string VaultedDungeonsLabel = "Vaulted Dungeons"; public const string NavPointReachTip = "How close to get to each nav point before moving on to the next, in yards. VTank calls it " + "Follow/Nav Min Distance (metas: FollowNavMin, or VTank's NavCloseStopRange). Follow stops this " + "close to its leader, and the nav marker ring shows it. Dungeon doorways use at most 1 yd. Up to 2 yd, " + "nav walks right up to each point before turning (tight dungeons); bigger values round corners."; + // The Nav panel's two overlay switches (ImGui/Panels/NavFace.cs), also on Settings > Navigation. + public const string BreadcrumbsTip = + "Record the trail you walk and draw it on the ground (/ra navtrail on|off).\n" + + "Turning it off hides the trail; /ra navtrail clear wipes it."; + public const string RouteOverlayTip = + "Draw the route in the world: waypoint rings and lines, waypoint labels and the guide line\n" + + "to the active waypoint (/ra navoverlay on|off). The waypoint HUD window is separate."; + private const string SameAsNavPanel = "\nThe same switch as on the Nav panel."; + // Also shown by the dashboard's Ranges slide-out (ImGui/Panels/RangesSlideOut.cs), which // edits these same rows (found by label with Find). public const string MonsterRangeTip = @@ -460,6 +533,12 @@ internal static class SettingsSchema } public static readonly string[] AttackHeights = { "Low", "Medium", "High" }; + // RynthAi's EnvironmentResponse, in its order (0 Off .. 3). + public static readonly string[] EnvironmentResponses = { "Off", "Move closer", "New target", "Move closer, then new target" }; + // The rows below show only once RynthAi has sent the value (an older RynthAi omits them). + private static bool HasVariablePower(RynthAiSettings s) => s.VariablePowerMin.HasValue; + private static bool HasEnvironmentThrottle(RynthAiSettings s) => s.EnvironmentImpactLimit.HasValue; + private static bool HasKite(RynthAiSettings s) => s.KitePullMeters.HasValue; public static readonly string[] LootOwnershipModes = { "My Kills Only", "Fellowship Kills", "All Corpses" }; public static readonly string[] NavLabelModes = { "Off", "Numbers", "Numbers and names" }; public static readonly string[] DunPatrolCoverages = { "Whole dungeon", "Loops only", "Everything", "Sweep (by sight)" }; @@ -498,8 +577,8 @@ internal static class SettingsSchema new(SettingKind.Double, label, tip, get, set, min, max, step); private static SettingRow Combo(string label, string[] items, Func get, Action set, - string? tip = null) => - new(SettingKind.Combo, label, tip, s => get(s), (s, v) => set(s, (int)v), 0, items.Length - 1, 1, items); + string? tip = null, Func? when = null) => + new(SettingKind.Combo, label, tip, s => get(s), (s, v) => set(s, (int)v), 0, items.Length - 1, 1, items, VisibleWhen: when); // Text size rows are stored by the engine (PanelTextScale), not in the // RynthAi profile, so the settings object is ignored here. @@ -525,6 +604,10 @@ internal static class SettingsSchema private static SettingRow Button(string label, string buttonText, Action click, string? tip = null) => new(SettingKind.Button, label, tip, ButtonText: buttonText, Click: click); + // A button that edits the settings (the panel saves the result like a typed value). + private static SettingRow EditButton(string label, string buttonText, Action edit, string? tip = null) => + new(SettingKind.Button, label, tip, ButtonText: buttonText, Edit: edit); + private static SettingRow Text(string label, Func get, Action set, string? tip = null, string? hint = null) => new(SettingKind.Text, label, tip, GetText: get, SetText: set, Hint: hint); @@ -604,6 +687,27 @@ internal static class SettingsSchema Bool("Insert Key Releases the UI", _ => Plugins.EngineSettings.InsertReleasesUi, (_, v) => { Plugins.EngineSettings.InsertReleasesUi = v; if (!v) ImGuiBackend.Win32Backend.ReclaimUi(); }, "On: Insert switches between UI and GAME (shown on the RynthCore bar). In GAME, clicks pass through\nRynth windows to the game and Rynth text boxes can't be typed in. Press Insert again to get the UI back.\nOff (default): Insert does nothing. Applies to all your clients; others pick it up when they start."), + Bool("Borderless Windowed", _ => Plugins.EngineSettings.BorderlessWindowed, + (_, v) => + { + Plugins.EngineSettings.BorderlessWindowed = v; + AcWindowChrome.RequestApply(); // applied from the game thread, not inside this frame + }, + "On: hide the Asheron's Call window title bar and borders while staying windowed (exclusive fullscreen is left alone).\nOff (default): normal window chrome. Turning it off only gives back the chrome this setting removed.\nApplies to all your clients; others pick it up when they start."), + Spacer(), + Section("Window and HUD Layout"), + Bool("Remember Open Windows and Positions", _ => Plugins.EngineSettings.RememberWindowLayout, + (_, v) => Plugins.EngineSettings.RememberWindowLayout = v, + "On (default): reopen Rynth panels where you left them.\nOff: do not overwrite the saved panel layout or reopen panels from the last session. Applies to all your clients."), + Bool("Remember Game Window Position", _ => Plugins.EngineSettings.RememberAcWindowPosition, + (_, v) => + { + Plugins.EngineSettings.RememberAcWindowPosition = v; + AcWindowChrome.RequestApply(); + }, + "On: save the Asheron's Call window's position and size for each character and put it back after you log in.\nOff (default): the game window is never moved. A saved spot that is off-screen (a monitor that is gone) is ignored."), + Button("Save Layout Now", "Save", () => AcWindowChrome.SaveLayoutNow(), + "Write the open panels, the game window position (when Remember Game Window Position is on),\nthe Vision HUD and the ImGui window positions to disk now."), Spacer(), // The colour theme is stored by the engine (theme.txt, ImGuiBackend.RynthTheme), not in the RynthAi profile. Section("Colour Theme"), @@ -719,6 +823,19 @@ internal static class SettingsSchema "items after 30 s, at most 5 a second. Unselected monsters' nameplates show no level.\n" + "Off: nothing in the background.\n" + "RynthAi's own identifies (loot, monster weaknesses) are never limited. Applies to all your clients. Also: /rc autoid."), + // Stored in engine.json for every client (EngineSettings.HoldReloadInWorld, ReloadInWorldGate); opt-in. + Bool("Hold reloads while in the world", _ => Plugins.EngineSettings.HoldReloadInWorld, + (_, v) => Plugins.EngineSettings.HoldReloadInWorld = v, + "On: when a new RynthCore build is deployed (the automatic engine reload), the reload waits until you\n" + + "log out or reach character select instead of reloading mid-session. A workaround for client crashes\n" + + "when reloads stack up while you are in the world (SilentKelpie's).\n" + + "It never waits forever: after the time below it reloads anyway. A reload you ask for yourself\n" + + "(the RL button, ERl, /rc rl, the hotkey) is never held.\n" + + "Off (default): the engine reloads as soon as the new build is there. Applies to all your clients.", gates: true), + Int(" Give up holding after (min)", _ => Plugins.EngineSettings.HoldReloadInWorldMaxMinutes, + (_, v) => Plugins.EngineSettings.HoldReloadInWorldMaxMinutes = v, 1, 240, 1, + "How long a held reload waits for you to leave the world before it reloads anyway (default 10).", + when: _ => Plugins.EngineSettings.HoldReloadInWorld), Spacer(), Bool("Auto Cram", s => s.EnableAutocram, (s, v) => s.EnableAutocram = v, "Automatically moves items from your main pack into side packs.\nNote: recently used weapons stay in the main pack."), @@ -863,6 +980,48 @@ internal static class SettingsSchema Int("Missile Power %", s => s.MissileAttackPower, (s, v) => s.MissileAttackPower = v, 0, 100, 5, when: s => s.MissileAttackPower >= 0), Combo("Missile Attack Height", AttackHeights, s => s.MissileAttackHeight, (s, v) => s.MissileAttackHeight = v), Spacer(), + Section("Variable Power (monster rules)", HasVariablePower), + Int("Variable Min %", s => s.VariablePowerMin ?? 50, (s, v) => s.VariablePowerMin = v, 0, 100, 5, + "A monster rule's Power picks per monster (Damage panel, a monster's detail):\n" + + "Default (the settings above), High (100%), Reckless (80%, needs Recklessness trained),\n" + + "Variable (a new random power each attack, between these two), or Reckless + Variable\n" + + "(random, kept inside the Recklessness band 20-80%).", + when: HasVariablePower), + Int("Variable Max %", s => s.VariablePowerMax ?? 100, (s, v) => s.VariablePowerMax = v, 0, 100, 5, + when: HasVariablePower), + Spacer(HasVariablePower), + Section("Hitting the Environment", HasEnvironmentThrottle), + Combo("Missile Response", EnvironmentResponses, s => s.MissileEnvironmentResponse ?? 0, (s, v) => s.MissileEnvironmentResponse = v, + "When arrows or bolts keep hitting walls or objects instead of the target\n" + + "(\"Your missile attack hit the environment.\"), stop shooting and:\n" + + " Move closer - run toward the target for a clearer shot\n" + + " New target - skip this one for a while and fight another\n" + + " Move closer, then new target - one approach, then switch\n" + + "The only monster in reach is never skipped. Off by default. Magic: Spell Combat tab.", + when: HasEnvironmentThrottle), + Int("Hits to trip", s => s.EnvironmentImpactLimit ?? 2, (s, v) => s.EnvironmentImpactLimit = v, 1, 10, 1, + "Environment hits on one target, within the window, before combat reacts (missiles and magic).", + when: HasEnvironmentThrottle), + Int("Window (s)", s => s.EnvironmentImpactWindowSec ?? 20, (s, v) => s.EnvironmentImpactWindowSec = v, 5, 120, 5, + when: HasEnvironmentThrottle), + Int("Move closer by (m)", s => s.EnvironmentApproachMeters ?? 6, (s, v) => s.EnvironmentApproachMeters = v, 1, 30, 1, + when: HasEnvironmentThrottle), + Int("Closest (m)", s => s.EnvironmentMinDistance ?? 3, (s, v) => s.EnvironmentMinDistance = v, 1, 30, 1, + "Never moves nearer than this. Already this close, a new target is picked instead.", + when: HasEnvironmentThrottle), + Int("Skip target (s)", s => s.EnvironmentSkipSec ?? 30, (s, v) => s.EnvironmentSkipSec = v, 5, 300, 5, + when: HasEnvironmentThrottle), + Spacer(HasEnvironmentThrottle), + Section("Pull Away (Kite)", HasKite), + Int("Pull Distance (m)", s => s.KitePullMeters ?? 20, (s, v) => s.KitePullMeters = v, 3, 100, 1, + "When a monster rule's Kite is PullAway (or Default follows the DEFAULT row set to PullAway),\n" + + "tag the mob then run until it has been dragged this many metres from where it stood, then kill it.\n" + + "Set per mob on the Damage panel (Kite). Off for every monster until a rule asks for it.", + when: HasKite), + Bool("Tag Before Fleeing", s => s.KiteTagFirst ?? true, (s, v) => s.KiteTagFirst = v, + "Land a hit before running so aggro sticks. Off = flee as soon as locked.", + when: HasKite), + Spacer(HasKite), Bool("Use Native Attack", s => s.UseNativeAttack, (s, v) => s.UseNativeAttack = v, "Uses the client's combat pipeline for attacks.\nThe client handles turn-to-face naturally (no backwards arrows)."), Spacer(), @@ -894,6 +1053,17 @@ internal static class SettingsSchema Int("Min Wall Targets", s => s.MinWallTargets, (s, v) => s.MinWallTargets = v, 1, 20, 1, "How many monsters (the target included) must be in the wall's path, within Wall Range."), Spacer(), + Section("Hitting the Environment", HasEnvironmentThrottle), + Combo("Magic Response", EnvironmentResponses, s => s.MagicEnvironmentResponse ?? 0, (s, v) => s.MagicEnvironmentResponse = v, + "When bolts, streaks, arcs or blasts keep stopping short of the target\n" + + "(a wall, a pillar, the ceiling) with no hit or resist, stop casting and:\n" + + " Move closer - run toward the target for a clearer line\n" + + " New target - skip this one for a while and fight another\n" + + " Move closer, then new target - one approach, then switch\n" + + "Rings and walls aren't judged. The only monster in reach is never skipped. Off by default.\n" + + "Hits to trip, the window, distances and the skip time: Melee Combat tab.", + when: HasEnvironmentThrottle), + Spacer(HasEnvironmentThrottle), Section("Spell Difficulty (Min Buffed Skill)"), Tiers( new Func[] { s => s.MinSkillLevelTier1, s => s.MinSkillLevelTier2, s => s.MinSkillLevelTier3, s => s.MinSkillLevelTier4, @@ -930,7 +1100,24 @@ internal static class SettingsSchema Bool("Boost Nav Priority", s => s.BoostNavPriority, (s, v) => s.BoostNavPriority = v), Float(NavPointReachLabel, s => s.FollowNavMin, (s, v) => s.FollowNavMin = v, 0.5f, 20f, 0.1f, NavPointReachTip), Spacer(), + Section("Infinite Leaftide"), + Bool(VaultedDungeonsLabel, s => s.EnableVaultedDungeons ?? false, (s, v) => s.EnableVaultedDungeons = v, + "Master switch of the Vaulted Dungeons keeper (Infinite Leaftide / ACECustom only). Off by default.\n" + + "While off the keeper does nothing: no recalls, no /rc quit, no Mini Remote tab, and a saved On or\n" + + "Auto Start is ignored. Turning it off while it runs stops it at once.\n" + + "On: the Mini Remote shows the \"Vaulted Dungeons\" tab on those worlds, where you pick a dungeon and a\n" + + "tied Portal Recall Gem and start it yourself (/ilt vaulted on); it never resumes by itself after a\n" + + "relog unless Auto Start On Arrival is ticked. Recalls wait while RynthAi is in combat or buffing.\n" + + "Kill Client (/rc quit after N minutes without a kill) restarts on luminance, your killing blows and\n" + + "pet captures; kills by pets or fellows that pay you no luminance do NOT.\n" + + "Needs RynthILT and a RynthAi that has this setting; the other settings are per character in RynthILT.", + when: s => s.EnableVaultedDungeons.HasValue), + Spacer(), Section("Nav Marker Display"), + Bool("Breadcrumbs", s => s.TrackBreadcrumbs ?? true, (s, v) => s.TrackBreadcrumbs = v, + BreadcrumbsTip + SameAsNavPanel, when: s => s.TrackBreadcrumbs.HasValue), + Bool("Route Overlay", s => s.ShowRouteOverlay ?? true, (s, v) => s.ShowRouteOverlay = v, + RouteOverlayTip + SameAsNavPanel, when: s => s.ShowRouteOverlay.HasValue), Float("Ring Thickness", s => s.NavRingThickness, (s, v) => s.NavRingThickness = v, 1f, 16f, 1f), Float("Line Thickness", s => s.NavLineThickness, (s, v) => s.NavLineThickness = v, 1f, 16f, 1f), Float("Height Offset", s => s.NavHeightOffset, (s, v) => s.NavHeightOffset = v, -5f, 5f, 0.05f, @@ -1086,19 +1273,30 @@ internal static class SettingsSchema Bool("Combine Bags During Salvage", s => s.CombineBagsDuringSalvage, (s, v) => s.CombineBagsDuringSalvage = v, "When salvaging an item, also add any under-full salvage bag of the same material to the salvage panel."), Button("Floating HUDs", "Inventory HUDs...", () => RynthAiCommands.ApplyRemoteCommand("huds", "show"), - "Opens the item count HUD / Mini Remote setup window (/ra huds)."), + "Opens the floating pack item count HUD / Mini Remote setup (/ra huds).\nThe Item Count panel is separate (/rc itemcount; Inventory's Count button)."), Bool("Salvage Without The Panel", s => s.SalvageWithoutPanel, (s, v) => s.SalvageWithoutPanel = v, "Salvage (and combine bags) by sending the salvage request to the server directly:\nAC's salvage panel never opens. When a request changes nothing, that batch is tried once\nthrough the panel. Needs an engine with plugin API v82; otherwise the panel is used."), Spacer(), Section("Loot Timers (ms)"), + EditButton("Optimized defaults", "Use optimized defaults", LootTimerDefaults.Apply, + "Set the six loot timers RynthAi's corpse looting reads (everything here except Inter-Item\n" + + "Delay and Closing Delay) to the optimized defaults, measured from live looting on ACE\n" + + "(226 corpses): Content Settle 100, Empty Corpse Wait 300, Assess Window 300,\n" + + "Loot Retry Timeout 1000, Corpse Open Retry 1500, Corpse Timeout 12000."), Int("Inter-Item Delay", s => s.LootInterItemDelayMs, (s, v) => s.LootInterItemDelayMs = v, 0, 5000, 25), - Int("Content Settle", s => s.LootContentSettleMs, (s, v) => s.LootContentSettleMs = v, 0, 5000, 25), - Int("Empty Corpse Wait", s => s.LootEmptyCorpseMs, (s, v) => s.LootEmptyCorpseMs = v, 0, 5000, 25), + Int("Content Settle", s => s.LootContentSettleMs, (s, v) => s.LootContentSettleMs = v, 0, 5000, 25, + "Wait after an open for the container's items. Only used when the items\naren't already known; on ACE they always were. Optimized default: 100."), + Int("Empty Corpse Wait", s => s.LootEmptyCorpseMs, (s, v) => s.LootEmptyCorpseMs = v, 0, 5000, 25, + "Wait for a corpse's contents before probing it or calling it empty. Optimized default: 300."), Int("Closing Delay", s => s.LootClosingDelayMs, (s, v) => s.LootClosingDelayMs = v, 0, 5000, 25), - Int("Assess Window", s => s.LootAssessWindowMs, (s, v) => s.LootAssessWindowMs = v, 0, 5000, 25), - Int("Loot Retry Timeout", s => s.LootRetryTimeoutMs, (s, v) => s.LootRetryTimeoutMs = v, 0, 10000, 100), - Int("Corpse Open Retry", s => s.LootOpenRetryMs, (s, v) => s.LootOpenRetryMs = v, 0, 10000, 100), - Int("Corpse Timeout", s => s.LootCorpseTimeoutMs, (s, v) => s.LootCorpseTimeoutMs = v, 0, 60000, 500), + Int("Assess Window", s => s.LootAssessWindowMs, (s, v) => s.LootAssessWindowMs = v, 0, 5000, 25, + "Hold items for their appraisal. Measured replies: 127 ms typical,\n256 ms at the 95th percentile, 350 ms at most. Optimized default: 300."), + Int("Loot Retry Timeout", s => s.LootRetryTimeoutMs, (s, v) => s.LootRetryTimeoutMs = v, 0, 10000, 100, + "Wait, once the character is still, before resending a pickup that hasn't\nlanded. Too short resends pickups the server is still doing. Optimized default: 1000."), + Int("Corpse Open Retry", s => s.LootOpenRetryMs, (s, v) => s.LootOpenRetryMs = v, 0, 10000, 100, + "Wait before sending another open to a corpse that hasn't opened. Optimized default: 1500."), + Int("Corpse Timeout", s => s.LootCorpseTimeoutMs, (s, v) => s.LootCorpseTimeoutMs = v, 0, 60000, 500, + "Give up on a claimed corpse after this long. The clock stops during combat\nand buffing. Optimized default: 12000."), Spacer(), Section("Salvage Timers (ms) - First / Fast"), Int("Open (First)", s => s.SalvageOpenDelayFirstMs, (s, v) => s.SalvageOpenDelayFirstMs = v, 0, 5000, 50), diff --git a/src/RynthCore.Engine/UI/Data/SharedFileWatch.cs b/src/RynthCore.Engine/UI/Data/SharedFileWatch.cs new file mode 100644 index 0000000..4f090b2 --- /dev/null +++ b/src/RynthCore.Engine/UI/Data/SharedFileWatch.cs @@ -0,0 +1,57 @@ +// ============================================================================ +// RynthCore.Engine - UI/Data/SharedFileWatch.cs +// Notices that ANOTHER client rewrote a settings file all clients share +// (rynthchat_settings.json), so ChatModel can re-read it. Every client saves its +// whole state, so a client that never re-read the file wrote back stale rules and +// ticked filters over another client's change (last writer won). +// +// Polled, not a FileSystemWatcher: no thread or event subscription to outlive an +// engine reload. A cheap timestamp check at most every PollMs; the file is only +// read when the timestamp moved, and a write this client made itself (Saved, called +// just before its swap) does not count as a change. Pure (no AC, no engine state): +// tools/ChatFilterTests compiles this file. +// +// Idea from Silentkelpie (rynth PR 6, 2026.10.16.23, ChatModel.PollSettingsFile). +// A read that fails (the other client is mid-swap) is retried at the next poll; his +// version marked the change as seen before reading, so a failed read lost it until +// somebody saved again. +// ============================================================================ + +using System; +using System.IO; +using System.Threading; + +namespace RynthCore.Engine.UI.Data; + +internal sealed class SharedFileWatch +{ + private readonly long _pollMs; + private DateTime _seenWriteUtc; + private string? _lastSavedText; + private long _nextPollMs; + + public SharedFileWatch(long pollMs = 2000) => _pollMs = pollMs; + + /// The file was just loaded at start: its timestamp is not a change. + public void Seen(DateTime writtenUtc) => _seenWriteUtc = writtenUtc; + + /// This client is about to write (call before the swap): that write is its own. + public void Saved(string text) => Volatile.Write(ref _lastSavedText, text); + + /// + /// The file's text when another client changed it since the last look, else null (not time to + /// look yet, no file, same timestamp, or the text is this client's own last save). Throws when + /// the file can't be read; the change is then offered again at the next poll. + /// + public string? Changed(long nowMs, string path) + { + if (nowMs < _nextPollMs) return null; + _nextPollMs = nowMs + _pollMs; + if (!File.Exists(path)) return null; + DateTime written = File.GetLastWriteTimeUtc(path); + if (written == _seenWriteUtc) return null; + string text = File.ReadAllText(path); + _seenWriteUtc = written; // only after a good read + return text == Volatile.Read(ref _lastSavedText) ? null : text; + } +} diff --git a/src/RynthCore.Engine/UI/InventoryTitleLayout.cs b/src/RynthCore.Engine/UI/InventoryTitleLayout.cs new file mode 100644 index 0000000..00758f5 --- /dev/null +++ b/src/RynthCore.Engine/UI/InventoryTitleLayout.cs @@ -0,0 +1,266 @@ +// ============================================================================ +// RynthCore.Engine - UI/InventoryTitleLayout.cs +// The Classic Inventory title bar's left half: where the title, the Vault button +// and the related-panel buttons (Mini Remote, RynthSort, Item Count, Global +// Inventory) go, so nothing lands off the panel when the bar is narrow. +// +// The bar is 300 retail units wide (x scale), so at the retail size the room left of the +// four fixed toggles (- + tools Modern) is about 186 units. Vault is always placed (it is +// the only one with no other way in); the four related buttons collapse by priority: +// Text four text buttons (Remote Sort Count GInv), when the title keeps its minimum +// Icons four icon squares +// Menu one "more" square that opens a menu of the four +// None nothing fits (a bar far narrower than any real panel); the Character menu has them all +// The title gets what is left (TitleLeft..TitleRight) and is elided with an ellipsis. +// +// Pure (no ImGui, no files, no engine state). All X values are relative to the bar's +// left edge, in pixels; callers add the bar origin. Tests: tools/BarDeclutterTests. +// ============================================================================ + +using System; + +namespace RynthCore.Engine.UI; + +internal enum TitleExtrasMode { Text, Icons, Menu, None } + +/// A button's span on the bar: left edge and width (width 0 = not drawn). +internal readonly record struct TitleSlot(float X, float W) +{ + public float Right => X + W; + public bool Present => W > 0f; +} + +/// The positions InventoryFace's Classic title bar draws, in bar-relative pixels. +internal readonly record struct InventoryTitleLayout( + TitleExtrasMode Mode, + float Btn, + TitleSlot Smaller, TitleSlot Bigger, TitleSlot Tools, TitleSlot Modern, + TitleSlot Vault, + TitleSlot Remote, TitleSlot Sort, TitleSlot Count, TitleSlot GInv, + TitleSlot More, + float TitleLeft, float TitleRight) +{ + // Units at scale 1 (the retail art's), multiplied by the bar's scale. + public const float BtnUnits = 18, EdgeUnits = 8, PadUnits = 6, GapSmall = 2, GapGroup = 6, VaultGap = 8, + VaultUnits = 38, RemoteUnits = 48, SortUnits = 36, CountUnits = 40, GInvUnits = 42, + TextGap = 4, IconGap = 2, LeadGap = 4, TitleMinUnits = 56, TitleGap = 4; + + /// The title's room (TitleRight - TitleLeft), never negative. + public float TitleWidth => Math.Max(0f, TitleRight - TitleLeft); + + /// The left edge of everything drawn left of the title (Vault and the related buttons): the drag surface ends here. + public float LeftmostX + { + get + { + float x = Math.Min(Modern.X, Smaller.X); + if (Vault.Present) x = Math.Min(x, Vault.X); + if (Mode is TitleExtrasMode.Text or TitleExtrasMode.Icons) x = Math.Min(x, Remote.X); + if (Mode == TitleExtrasMode.Menu) x = Math.Min(x, More.X); + return x; + } + } + + /// + /// Lays the bar out. is the bar's width in pixels (the panel width less + /// the close button), its scale, whether the Vault + /// button exists (VaultFeed.Available), the title text's full + /// width in pixels (it only decides how much room the title is owed: at most 56 units). + /// + public static InventoryTitleLayout Compute(float barW, float s, bool vault, float titleWantW) + { + if (!(s > 0f) || !float.IsFinite(s)) s = 1f; + if (!float.IsFinite(barW)) barW = 0f; + if (!float.IsFinite(titleWantW) || titleWantW < 0f) titleWantW = 0f; + + float btn = MathF.Round(BtnUnits * s); + float pad = PadUnits * s; + + // The four fixed toggles at the bar's right end (unchanged from the original Classic layout). + float modernX = barW - EdgeUnits * s - btn; + float toolsX = modernX - btn - GapSmall * s; + float biggerX = toolsX - btn - GapGroup * s; + float smallerX = biggerX - btn - GapSmall * s; + var modern = new TitleSlot(modernX, btn); + var tools = new TitleSlot(toolsX, btn); + var bigger = new TitleSlot(biggerX, btn); + var smaller = new TitleSlot(smallerX, btn); + + // Vault sits next to the toggles, and is never dropped. On a bar too narrow to hold it + // without crossing the title area it is pushed to the left edge, never past it. + float edge = smallerX; + TitleSlot vaultSlot = default; + if (vault) + { + float vw = MathF.Round(VaultUnits * s); + float vx = Math.Max(0f, edge - vw - VaultGap * s); + vaultSlot = new TitleSlot(vx, vw); + edge = vx; + } + + // The room left of `edge` is shared by the title and the related buttons. The title is owed + // TitleMinUnits (less if its whole text is shorter); take the richest button style that leaves it. + float titleMin = Math.Min(titleWantW, TitleMinUnits * s); + float lead = LeadGap * s; + + float rw = MathF.Round(RemoteUnits * s), sw = MathF.Round(SortUnits * s), + cw = MathF.Round(CountUnits * s), gw = MathF.Round(GInvUnits * s); + float tg = TextGap * s, ig = IconGap * s; + + // Right to left: GInv, Count, Sort, Remote. + float tGinvX = edge - lead - gw; + float tCountX = tGinvX - tg - cw; + float tSortX = tCountX - tg - sw; + float tRemoteX = tSortX - tg - rw; + + float iGinvX = edge - lead - btn; + float iCountX = iGinvX - ig - btn; + float iSortX = iCountX - ig - btn; + float iRemoteX = iSortX - ig - btn; + + float moreX = edge - lead - btn; + + TitleExtrasMode mode; + float groupLeft; + if (tRemoteX - pad >= titleMin) { mode = TitleExtrasMode.Text; groupLeft = tRemoteX; } + else if (iRemoteX - pad >= titleMin) { mode = TitleExtrasMode.Icons; groupLeft = iRemoteX; } + else if (moreX - pad >= 0f) { mode = TitleExtrasMode.Menu; groupLeft = moreX; } + else { mode = TitleExtrasMode.None; groupLeft = edge; } + + TitleSlot remote = default, sort = default, count = default, ginv = default, more = default; + switch (mode) + { + case TitleExtrasMode.Text: + remote = new TitleSlot(tRemoteX, rw); + sort = new TitleSlot(tSortX, sw); + count = new TitleSlot(tCountX, cw); + ginv = new TitleSlot(tGinvX, gw); + break; + case TitleExtrasMode.Icons: + remote = new TitleSlot(iRemoteX, btn); + sort = new TitleSlot(iSortX, btn); + count = new TitleSlot(iCountX, btn); + ginv = new TitleSlot(iGinvX, btn); + break; + case TitleExtrasMode.Menu: + more = new TitleSlot(moreX, btn); + break; + } + + float titleRight = Math.Max(pad, groupLeft - TitleGap * s); + return new InventoryTitleLayout(mode, btn, smaller, bigger, tools, modern, vaultSlot, + remote, sort, count, ginv, more, pad, titleRight); + } + + /// Header (Modern look) buttons: four 22 px icons at a 24 px pitch, or one "more" button. + public const float HeaderIconsW = 96, HeaderMenuW = 24, HeaderCountGap = 10; + + /// + /// The Modern header's related-panel buttons for pixels between the pyreals + /// and the Classic / Close buttons, shared with the item count text (). + /// Icons when all four and the count fit, else the one menu button, with the count text dropped last. + /// Text mode never applies here (Icons, Menu or None). + /// + public static TitleExtrasMode ChooseHeaderExtras(float freeW, float countW, out bool showCount) + { + if (!float.IsFinite(freeW)) freeW = 0f; + if (!float.IsFinite(countW) || countW < 0f) countW = 0f; + float count = countW + HeaderCountGap; + if (freeW >= HeaderIconsW + count) { showCount = true; return TitleExtrasMode.Icons; } + if (freeW >= HeaderMenuW + count) { showCount = true; return TitleExtrasMode.Menu; } + if (freeW >= HeaderMenuW) { showCount = false; return TitleExtrasMode.Menu; } + showCount = freeW >= count; + return TitleExtrasMode.None; + } + + /// The Modern header's Vault button (Aelrynth): one 22 px icon at a 24 px pitch, left of the Classic button. + public const float HeaderVaultW = 24; + + /// + /// with the Vault button in the picture: when + /// the Vault takes its 24 px first and is never dropped (it is the only way into the vault in the Modern + /// look); the four related buttons, the "more" menu and the count text share what is left, as before. + /// Without a vault the result is exactly ChooseHeaderExtras'. + /// + internal static HeaderPlan ChooseHeader(float freeW, float countW, bool vault) + { + if (!float.IsFinite(freeW)) freeW = 0f; + TitleExtrasMode extras = ChooseHeaderExtras(vault ? freeW - HeaderVaultW : freeW, countW, out bool showCount); + return new HeaderPlan(vault, extras, showCount); + } + + /// + /// cut to fit pixels, ending in an ellipsis when + /// cut ("" when not even the ellipsis fits). gives a string's width. + /// + public static string Elide(string text, float maxW, Func measure) + { + if (text.Length == 0 || !(maxW > 0f)) return ""; + if (measure(text) <= maxW) return text; + const string Ellipsis = "..."; + if (measure(Ellipsis) > maxW) return ""; + int lo = 0, hi = text.Length - 1; // longest prefix whose prefix + ellipsis still fits + while (lo < hi) + { + int mid = (lo + hi + 1) / 2; + if (measure(text.Substring(0, mid).TrimEnd() + Ellipsis) <= maxW) lo = mid; else hi = mid - 1; + } + return text.Substring(0, lo).TrimEnd() + Ellipsis; + } +} + +/// What the Modern header draws between the pyreals and the Classic / Close buttons. +internal readonly record struct HeaderPlan(bool Vault, TitleExtrasMode Extras, bool ShowCount); + +/// The Modern header's button positions, header-relative pixels (add the header's left edge). +internal readonly record struct InventoryHeaderLayout( + HeaderPlan Plan, + TitleSlot Close, TitleSlot Classic, TitleSlot Vault, + TitleSlot Remote, TitleSlot Sort, TitleSlot Count, TitleSlot GInv, TitleSlot More, + float RightEdge, float CountX) +{ + public const float Btn = 22, Pitch = 24; + + /// + /// Right to left: Close, Classic, the Vault (when there is one), then four related icons or the + /// "more" button, then the count text. is the header's width, + /// where the pyreals text ends (header-relative), the count text's width. + /// + public static InventoryHeaderLayout Compute(float w, float leftEnd, float countW, bool vault) + { + if (!float.IsFinite(w)) w = 0f; + if (!float.IsFinite(leftEnd)) leftEnd = 0f; + if (!float.IsFinite(countW) || countW < 0f) countW = 0f; + + var close = new TitleSlot(w - 22, Btn); + float classicX = w - 46; + var classic = new TitleSlot(classicX, Btn); + HeaderPlan plan = InventoryTitleLayout.ChooseHeader(classicX - 4 - leftEnd, countW, vault); + + float anchor = classicX; // the next button goes at anchor - 24 + TitleSlot vaultSlot = default; + if (plan.Vault) + { + vaultSlot = new TitleSlot(anchor - Pitch, Btn); + anchor = vaultSlot.X; + } + + TitleSlot remote = default, sort = default, count = default, ginv = default, more = default; + float rightEdge = anchor - 2; + if (plan.Extras == TitleExtrasMode.Icons) + { + ginv = new TitleSlot(anchor - Pitch, Btn); + count = new TitleSlot(ginv.X - Pitch, Btn); + sort = new TitleSlot(count.X - Pitch, Btn); + remote = new TitleSlot(sort.X - Pitch, Btn); + rightEdge = remote.X - 2; + } + else if (plan.Extras == TitleExtrasMode.Menu) + { + more = new TitleSlot(anchor - Pitch, Btn); + rightEdge = more.X - 2; + } + return new InventoryHeaderLayout(plan, close, classic, vaultSlot, remote, sort, count, ginv, more, + rightEdge, rightEdge - countW - 4); + } +} diff --git a/src/RynthCore.Engine/UI/PanelStateStore.cs b/src/RynthCore.Engine/UI/PanelStateStore.cs index 924c652..329325c 100644 --- a/src/RynthCore.Engine/UI/PanelStateStore.cs +++ b/src/RynthCore.Engine/UI/PanelStateStore.cs @@ -25,6 +25,7 @@ using System; using System.Collections.Generic; using System.Globalization; using System.IO; +using RynthCore.Engine.Plugins; namespace RynthCore.Engine.UI; @@ -170,6 +171,18 @@ internal static class PanelStateStore } } + /// Rewrite panel_state.txt from the in-memory snapshot (Settings > Display "Save Layout + /// Now"). An explicit user action, so unlike the automatic saves it is NOT gated by + /// RememberWindowLayout: it writes even when that is off. + public static void Flush() + { + lock (Sync) + { + Load(); + Save(force: true); + } + } + private static void Load() { if (_loaded) return; @@ -249,8 +262,13 @@ internal static class PanelStateStore } } - private static void Save() + private static void Save(bool force = false) { + // Settings > Display "Remember Open Windows and Positions" (default on). Off: keep the last + // file; do not overwrite it while the user is rearranging. + if (!force && !EngineSettings.RememberWindowLayout) + return; + try { string path = FilePath; diff --git a/src/RynthCore.Engine/UI/Panels/MonstersPanel.cs b/src/RynthCore.Engine/UI/Panels/MonstersPanel.cs index 908af51..3a876f0 100644 --- a/src/RynthCore.Engine/UI/Panels/MonstersPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/MonstersPanel.cs @@ -129,6 +129,13 @@ internal static class MonstersPanel public string PetDamage { get; set; } = "PAuto"; /// Debuffs the player typed in, comma separated (spell base or full names). public string CustomDebuffs { get; set; } = string.Empty; + /// Melee/missile attack power for this monster: one of DamageData.AttackPowerModes + /// ("Default" follows the DEFAULT line, which follows the global Power settings). Rules saved + /// before 2026-10-12 load as Default. + public string AttackPower { get; set; } = "Default"; + /// Pull-away kite for this monster: Default / Off / PullAway (RynthAi KiteModes). + /// Default follows the DEFAULT line (Off on that line). Rules saved before 2026-10-16 load as Default. + public string Kite { get; set; } = "Default"; public bool GetToggle(string field) => field switch { @@ -1018,6 +1025,8 @@ internal static class MonstersPanel var x = a[i]; var y = b[i]; if (x.Name != y.Name || x.Category != y.Category || x.Priority != y.Priority || x.DamageType != y.DamageType || x.PreferredDamage != y.PreferredDamage || x.ExVuln != y.ExVuln || x.PetDamage != y.PetDamage + || (x.AttackPower ?? "") != (y.AttackPower ?? "") + || (x.Kite ?? "") != (y.Kite ?? "") || x.WeaponId != y.WeaponId || x.OffhandId != y.OffhandId || x.MatchExpression != y.MatchExpression || x.Fester != y.Fester || x.Broadside != y.Broadside || x.GravityWell != y.GravityWell diff --git a/src/RynthCore.Engine/UI/Panels/RynthChatPresets.cs b/src/RynthCore.Engine/UI/Panels/RynthChatPresets.cs index 0df795c..da5fb47 100644 --- a/src/RynthCore.Engine/UI/Panels/RynthChatPresets.cs +++ b/src/RynthCore.Engine/UI/Panels/RynthChatPresets.cs @@ -90,6 +90,23 @@ internal static class RynthChatPresets // Optional combat prefixes such as "Critical hit! " / "Sneak Attack! ". private const string HitPrefix = @"^(?:[A-Z][\w ]{2,20}! )*"; + // The new damage presets (melee_dealt ... magic_taken) name their prefixes: "Critical hit! ", + // "Sneak Attack! ", "Recklessness! ". HitPrefix above is left as it was for the older presets. + private const string KnownHitPrefix = @"^(?:(?:Critical [Hh]it|Sneak Attack|Recklessness)!\s+)*"; + + // Outgoing physical (melee / missile): "... for N points of X damage!" + private const string DealtMelee = + KnownHitPrefix + @"You \S+ .+ for \d+ points? of .+ damage"; + // Outgoing war / void magic: "... for N points with SpellName." + private const string DealtMagic = + KnownHitPrefix + @"You \S+ .+ for \d+ points? with "; + // Incoming melee / missile: body-part hits ("... your foot for N points of ..."). + private const string TakenMelee = + KnownHitPrefix + @"(?!You ).+ your [a-z ]+ for \d+ points? of .+ damage"; + // Incoming spell damage: "... you for N points with SpellName." + private const string TakenMagic = + KnownHitPrefix + @"(?!You ).+ you for \d+ points? with "; + private static readonly Preset[] _all = { // ── Combat ──────────────────────────────────────────────────────── @@ -99,6 +116,33 @@ internal static class RynthChatPresets new("combat.defense_evades", "Combat", "You evade attacks", "You evade a monster's attack.", "You evaded Drudge Slinker!", Scope.NotPlayerChat, @"^You evaded "), + // Prefix-tagged and melee / missile / magic damage, each its own switch (the older + // "Damage you deal / take" below keep their meaning). Specific before umbrella: FirstMatch order. + new("combat.recklessness", "Combat", "Recklessness hits", + "Lines prefixed with \"Recklessness!\" (your reckless swings).", + "Recklessness! You slash Drudge Slinker for 54 points of slashing damage!", Scope.NotPlayerChat, + @"^((?:Critical [Hh]it!|Sneak Attack!)\s+)*Recklessness!"), + new("combat.sneak_attack", "Combat", "Sneak Attack hits", + "Lines prefixed with \"Sneak Attack!\" (your sneak swings / shots).", + "Sneak Attack! You slash Drudge Slinker for 54 points of slashing damage!", Scope.NotPlayerChat, + @"^((?:Critical [Hh]it!|Recklessness!)\s+)*Sneak Attack!"), + new("combat.critical", "Combat", "Critical hits", + "Lines prefixed with \"Critical hit!\" / \"Critical Hit!\".", + "Critical hit! You slash Drudge Slinker for 100 points of slashing damage!", Scope.NotPlayerChat, + @"^Critical [Hh]it!"), + new("combat.melee_dealt", "Combat", "Melee / missile damage you deal", + "Your weapon hits: \"You slash … for N points of … damage!\" (missile uses the same form).", + "You slash Drudge Slinker for 54 points of slashing damage!", Scope.NotPlayerChat, DealtMelee), + new("combat.magic_dealt", "Combat", "Magic damage you deal", + "Your war / void hits: \"You … for N points with SpellName.\"", + "You freeze Drudge Slinker for 120 points with Frost Bolt VI.", Scope.NotPlayerChat, DealtMagic), + new("combat.melee_taken", "Combat", "Melee / missile damage you take", + "Monster weapon hits on a body part (\"… grazes your foot for N points of …\").", + "Drudge Slinker grazes your foot for 12 points of slashing damage!", Scope.NotPlayerChat, TakenMelee), + new("combat.magic_taken", "Combat", "Magic damage you take", + "Spell damage on you: \"… you for N points with SpellName.\"", + "Drudge Sorcerer scorches you for 40 points with Flame Bolt III.", Scope.NotPlayerChat, TakenMagic), + new("combat.damage_dealt", "Combat", "Damage you deal", "Your melee, missile and war-spell hits (including critical / sneak attack prefixes).", "You slash Drudge Slinker for 54 points of slashing damage!", Scope.NotPlayerChat, HitPrefix + @"You .+ for \d+ points? of "), @@ -122,6 +166,34 @@ internal static class RynthChatPresets new("combat.monster_deaths", "Combat", "Monster death messages", "Kill flavour text (\"You flatten…\", \"…is reduced to cinders!\").", "Drudge Slinker is reduced to cinders!", Scope.NotPlayerChat, KillPattern), + new("combat.missile_miss", "Combat", "Missile hit the environment", + "\"Your missile attack hit the environment.\" (classic UB ChatFilter).", + "Your missile attack hit the environment.", Scope.NotPlayerChat, + @"^Your missile attack hit the environment\.\s*$"), + new("combat.periodic_damage", "Combat", "Periodic damage ticks", + "\"You receive N points of periodic … damage.\" DoTs on you.", + "You receive 8 points of periodic acid damage.", Scope.NotPlayerChat, + @"^You receive \d+ points of periodic .+damage"), + new("combat.stamina", "Combat", "Stamina restore / spend", + "Lines that restore or spend stamina (kits, consumables, S2H/S2M, Heal Self).", + "You cast Revitalize Self V and restore 40 points of your stamina.", Scope.NotPlayerChat, + @"(?:restore|restores|regain|regains|lose|loses) \d+ points? of (?:your )?stamina\b|and lose \d+ points of stamina"), + new("combat.mana", "Combat", "Mana restore / spend", + "Lines that restore or spend mana (consumables, S2M, mana stones' give line is under Items).", + "You cast Stamina to Mana Self V on yourself and lose 17 points of stamina and also gain 23 points of mana", Scope.NotPlayerChat, + @"(?:restore|restores|regain|regains|gain|gains|lose|loses) \d+ points? of (?:your )?mana\b|and also gain \d+ points of mana"), + new("combat.health", "Combat", "Health restore", + "Lines that restore health points (kits, heals, consumables) — not damage taken.", + "You heal yourself for 80 Health points.", Scope.NotPlayerChat, + @"(?:heal yourself for \d+|restore|restores|regain|regains) \d+ points? of (?:your )?health\b|heal yourself for \d+ Health"), + new("combat.fail_affect_you", "Combat", "Fails to affect you", + "\"… fails to affect you…\" (broader than the NPK-only filter).", + "Bob fails to affect you because he is not a player killer!", Scope.NotPlayerChat, + @" fails to affect you"), + new("combat.you_fail_affect", "Combat", "You fail to affect", + "\"You failed to affect…\" / \"You fail to affect…\" (non-PK and other).", + "You fail to affect Bob because you are not a player killer!", Scope.NotPlayerChat, + @"^You fail(?:ed)? to affect "), // ── Casting ─────────────────────────────────────────────────────── new("cast.mine", "Casting", "Your spell words", @@ -145,6 +217,14 @@ internal static class RynthChatPresets new("cast.expires", "Casting", "Spell expiry", "\"… has expired.\" — rares (Brilliance / Prodigal / Spectral) are kept.", "Strength Self VII has expired.", Scope.NotPlayerChat, @"^(?!.*(?:Brilliance|Prodigal|Spectral)).*\b(?:has|have) expired\."), + new("cast.give_take", "Casting", "Stamina / health / mana transfers", + "Self casts that spend one vital and restore another (S2M, S2H, …).", + "You cast Stamina to Mana Self V on yourself and lose 17 points of stamina and also gain 23 points of mana", Scope.NotPlayerChat, + @"^You cast .+ on yourself and lose \d+ points of .+ and also gain \d+ points of "), + new("cast.heal_self", "Casting", "Your heal / restore casts", + "\"You cast … and restore N points of your …\" (spell heals, not kits).", + "You cast Revitalize Self V and restore 40 points of your stamina.", Scope.NotPlayerChat, + @"^You cast .+ and restore \d+ points of your "), // ── Items & utility ─────────────────────────────────────────────── new("item.heal_ok", "Items", "Healing kit success", @@ -153,6 +233,14 @@ internal static class RynthChatPresets new("item.heal_fail", "Items", "Healing kit failure", "\"You fail to heal yourself.\"", "You fail to heal yourself. ", Scope.NotPlayerChat, @"^You fail to heal yourself\."), + new("item.healed_by_other", "Items", "Healed by another", + "\"X casts Y and restores N points of your …\"", + "Bob casts Heal Other VI and restores 80 points of your health.", Scope.NotPlayerChat, + @"^.+ casts .+ and restores \d+ points of your "), + new("item.consumable", "Items", "Food / potion restores", + "\"The X restores N points of your …\"", + "The Health Tonic restores 50 points of your health.", Scope.NotPlayerChat, + @"^The .+ restores \d+ points of your "), new("item.salvage", "Items", "Salvage results", "\"You obtain … using your knowledge of …\"", "You obtain 12 Steel (ws 7.00) using your knowledge of Weapon Tinkering.", Scope.NotPlayerChat, @"^You obtain .+ using your knowledge of "), @@ -169,6 +257,15 @@ internal static class RynthChatPresets new("item.regen", "Items", "Periodic healing ticks", "\"You receive N points of periodic healing.\"", "You receive 12 points of periodic healing.", Scope.NotPlayerChat, @"^You receive .+ points of periodic healing"), + new("item.aetheria_surge", "Items", "Aetheria surges", + "\"Aetheria surges on…\" (classic UB Misc filter).", + "Aetheria surges on Bob, increasing his damage.", Scope.NotPlayerChat, @"^Aetheria surges on"), + new("item.cloak", "Items", "Cloak procs", + "\"The cloak of…\" cloak cast lines (classic UB Misc filter).", + "The cloak of Bob weaves a protective spell.", Scope.NotPlayerChat, @"^The cloak of"), + new("item.banked_lum", "Items", "Banked luminance", + "\"You've banked N Luminance.\" (classic UB Misc filter).", + "You've banked 1,250 Luminance.", Scope.NotPlayerChat, @"^You've banked [\d,]+ Luminance\.\s*$"), // ── Social & trade ──────────────────────────────────────────────── new("social.bot_spam", "Social", "Trade / buff bot spam", @@ -180,6 +277,16 @@ internal static class RynthChatPresets new("social.kill_task", "Social", "Kill task complete", "\"You have killed N Xs! Your task is complete!\"", "You have killed 50 Drudges! Your task is complete!", Scope.NotPlayerChat, @"^You have killed \d+ .+Your task is complete!\s*$"), + new("social.kill_task_progress", "Social", "Kill task progress", + "\"You have killed N Xs! You must kill M to complete your task.\" (ACECustom / UB-IT).", + "You have killed 12 Drudges! You must kill 50 to complete your task.", Scope.NotPlayerChat, + @"^You have killed \d+ .+! You must kill \d+ to complete your task\.\s*$"), + new("social.too_busy", "Social", "You're too busy", + "\"You're too busy!\" (also Mag StatusTextYoureTooBusy when it lands in chat).", + "You're too busy!", Scope.NotPlayerChat, @"^You're too busy!\s*$"), + new("social.casting_status", "Social", "Casting status text", + "\"Casting …\" overlay lines when they appear in chat (Mag StatusTextCasting).", + "Casting Focus Self VII", Scope.NotPlayerChat, @"^Casting "), new("social.general", "Social", "General channel", "Everything said on General.", "[General] Bob says, \"hi\"", Scope.ChannelsOnly, @"^\[General\]|says on the General channel"), @@ -197,6 +304,10 @@ internal static class RynthChatPresets "[Society] Bob says, \"…\"", Scope.ChannelsOnly, @"^\[(?:Society|Celestial Hand|Eldrytch Web|Radiant Blood)\]|says on the (?:Society|Celestial Hand|Eldrytch Web|Radiant Blood) channel"), // ── NPCs ────────────────────────────────────────────────────────── + new("npc.arbitrator_spam", "NPCs", "Master Arbitrator spam", + "Selected Colosseum spam (title / key / arena instructions); keeps \"Well done!\" / \"Good Luck!\".", + "Master Arbitrator tells you, \"You shall be known…\"", Scope.Any, + @"(?:^Master Arbitrator tells you,.+(?:""You shall be known|""Take this knowledge|""Use the the key)|(?:\[Fellowship\] )?Master Arbitrator says,.+(?:""Your fellowship|""Use one of the|""Don't forget))"), new("npc.arbitrator", "NPCs", "Master Arbitrator (Colosseum)", "All Master Arbitrator speech and the fellowship-lock notice.", "Master Arbitrator tells you, \"You shall be known…\"", Scope.Any, diff --git a/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs b/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs index e5abf9d..a7cf1f6 100644 --- a/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs @@ -334,7 +334,18 @@ internal static class SettingsPanel case SettingKind.Spacer: return Spacer(); case SettingKind.Button: - return ButtonRow(row.Label, row.ButtonText ?? row.Label, () => row.Click?.Invoke(), row.Tooltip); + return ButtonRow(row.Label, row.ButtonText ?? row.Label, () => + { + // A settings edit is pushed like a typed value; the tab is rebuilt so the + // number boxes show the new values. + if (row.Edit != null) + { + row.Edit(state.Data); + Push(state); + state.Rebuild?.Invoke(); + } + row.Click?.Invoke(); + }, row.Tooltip); case SettingKind.TraceCategories: return TraceCategoriesRow(state, row); case SettingKind.Text: diff --git a/src/RynthCore.Engine/UI/ScriptWindows/ScriptWindowRegistry.cs b/src/RynthCore.Engine/UI/ScriptWindows/ScriptWindowRegistry.cs index c91be84..e33b07c 100644 --- a/src/RynthCore.Engine/UI/ScriptWindows/ScriptWindowRegistry.cs +++ b/src/RynthCore.Engine/UI/ScriptWindows/ScriptWindowRegistry.cs @@ -643,6 +643,8 @@ internal static class ScriptWindowRegistry Volatile.Write(ref _barItems, Array.Empty()); Volatile.Write(ref _barButtons, Array.Empty()); } + // Engine reload / shutdown: the Skills embed hides and Oracle's announcement is forgotten. + ImGuiBackend.Panels.OracleSkillsEmbed.Shutdown(); } /// @@ -882,6 +884,10 @@ internal static class ScriptWindowRegistry w.Removed = true; w.SubmittedVisible = false; _barDirty = true; + // Oracle's window went (plugin unloaded or stopped drawing it): its Skills embed hides now, + // not at the next frame, which may never come (reload, shutdown). + if (ImGuiBackend.Panels.OracleSkillsEmbed.IsOraclePanel(w.PanelKey)) + ImGuiBackend.Panels.OracleSkillsEmbed.Clear(); owner.Windows.Remove(w.Key); if (ByPanelKey.TryGetValue(w.PanelKey, out ScriptWindow? cur) && ReferenceEquals(cur, w)) ByPanelKey.Remove(w.PanelKey); diff --git a/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets b/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets index f0a19f3..4808aa9 100644 --- a/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets +++ b/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets @@ -36,7 +36,7 @@ - 86 + 88 <_RynthPluginManifestOn Condition="'$(RynthPluginMinEngineApi)' != '' and '$(RynthPluginManifest)' != 'false'">true diff --git a/tools/BarDeclutterTests/BarDeclutterTests.csproj b/tools/BarDeclutterTests/BarDeclutterTests.csproj new file mode 100644 index 0000000..186d233 --- /dev/null +++ b/tools/BarDeclutterTests/BarDeclutterTests.csproj @@ -0,0 +1,29 @@ + + + + + Exe + net10.0 + enable + enable + true + BarDeclutterTests + + + + + + + + + diff --git a/tools/BarDeclutterTests/Program.cs b/tools/BarDeclutterTests/Program.cs new file mode 100644 index 0000000..06bf208 --- /dev/null +++ b/tools/BarDeclutterTests/Program.cs @@ -0,0 +1,507 @@ +using RynthCore.Engine.ImGuiBackend.Panels; +using RynthCore.Engine.UI; + +namespace BarDeclutterTests; + +// Offline tests for the bar declutter work. See the csproj. +internal static class Program +{ + private static int _fails, _asserts; + private static void Check(bool cond, string msg) + { + _asserts++; + if (!cond) { _fails++; Console.WriteLine($" [FAIL] {msg}"); } + } + private static void Eq(T actual, T expected, string msg) => + Check(EqualityComparer.Default.Equals(actual, expected), $"{msg}: expected '{expected}', got '{actual}'"); + + private static int Main() + { + ShownLatchBasics(); + EmbedShowRedrawsHide(); + EmbedTabSwitches(); + EmbedHideWithoutShow(); + EmbedDoubleClear(); + EmbedWindowClosedAndIdle(); + EmbedRaceAndShutdown(); + EmbedTwoThreads(); + FaceOnShownTwice(); + TabsAvailableRule(); + TitleLayoutGrid(); + TitleLayoutModes(); + TitleLayoutNarrow(); + TitleLayoutBadInput(); + ElideTitle(); + HeaderExtras(); + HeaderVault(); + Console.WriteLine(); + Console.WriteLine(_fails == 0 ? $"PASS ({_asserts} checks)" : $"FAIL ({_fails} of {_asserts} checks failed)"); + return _fails == 0 ? 0 : 1; + } + + // ── The lifecycle ─────────────────────────────────────────────────── + + /// + /// Stands in for SkillsFace: the same ShownLatch wiring (OnShown/OnHidden through a latch that runs a + /// "core" once per edge), with the Progression subscribe / unsubscribe counted instead of UiSource. + /// + private sealed class FakeFace + { + public int Subscribes, Unsubscribes, Outstanding; + private readonly ShownLatch _life; + public FakeFace() => _life = new ShownLatch(() => { Subscribes++; Outstanding++; }, () => { Unsubscribes++; Outstanding--; }); + public void OnShown() => _life.Show(); + public void OnHidden() => _life.Hide(); + } + + private static FakeFace Fresh() + { + OracleSkillsEmbed.Shutdown(); // hides anything left by a previous test, forgets the announcement + var face = new FakeFace(); + OracleSkillsEmbed.Bind(face.OnShown, face.OnHidden); + return face; + } + + /// One frame of ScriptWindowFace.Draw for the Oracle window: embed drawn only while a tab is active. + private static void Frame(long nowMs) + { + OracleSkillsEmbed.Sweep(nowMs); // ImGuiPanelHost.DrawAll + if (OracleSkillsEmbed.ActiveTab >= 0) OracleSkillsEmbed.NoteDrawn(nowMs); // SkillsFace.DrawEmbedded + } + + private static void ShownLatchBasics() + { + Console.WriteLine("ShownLatch"); + int on = 0, off = 0; + var l = new ShownLatch(() => on++, () => off++); + Eq(l.Hide(), false, "hide before any show does nothing"); + Eq(off, 0, "no hidden callback without a show"); + Eq(l.Show(), true, "first show runs"); + Eq(l.Show(), false, "second show is a no-op"); + Eq(l.IsShown, true, "shown"); + Eq(l.Hide(), true, "hide runs"); + Eq(l.Hide(), false, "second hide is a no-op"); + Eq(l.IsShown, false, "hidden"); + Eq((on, off), (1, 1), "one callback each"); + + // A shown callback that throws still leaves the latch on, so the matching hide runs. + int h = 0; + var t = new ShownLatch(() => throw new InvalidOperationException("boom"), () => h++); + try { t.Show(); } catch (InvalidOperationException) { } + Eq(t.IsShown, true, "a throwing show leaves the latch on"); + t.Hide(); + Eq(h, 1, "so the hide still runs once"); + } + + private static void EmbedShowRedrawsHide() + { + Console.WriteLine("Embed: show, N redraws, hide"); + FakeFace f = Fresh(); + OracleSkillsEmbed.SetActiveTab(0); + Eq(f.Subscribes, 0, "setting the tab alone shows nothing (the Oracle window may be closed)"); + long t = 1000; + for (int i = 0; i < 600; i++, t += 16) Frame(t); // ~10 s of 60 fps + Eq(f.Subscribes, 1, "600 redraws: one subscribe"); + Eq(f.Unsubscribes, 0, "600 redraws: no unsubscribe yet"); + Eq(OracleSkillsEmbed.IsShown, true, "shown while drawing"); + // The old code re-ran OnShown every 2 s: 5 more "2 s gaps" must not add subscribes. + for (int i = 0; i < 5; i++) { t += 900; Frame(t); Frame(t + 16); } + Eq(f.Subscribes, 1, "redraws after long gaps (the old re-run trigger): still one subscribe"); + OracleSkillsEmbed.Clear(); + Eq(f.Unsubscribes, 1, "Clear: one unsubscribe"); + Eq(f.Outstanding, 0, "balanced"); + Eq(OracleSkillsEmbed.IsShown, false, "hidden"); + for (int i = 0; i < 50; i++, t += 16) Frame(t); // ActiveTab is -1: nothing draws + Eq((f.Subscribes, f.Unsubscribes), (1, 1), "frames after Clear change nothing"); + + // Shown again later: a second, separate stretch. + OracleSkillsEmbed.SetActiveTab(1); + for (int i = 0; i < 10; i++, t += 16) Frame(t); + OracleSkillsEmbed.Clear(); + Eq((f.Subscribes, f.Unsubscribes), (2, 2), "second stretch: two of each in all"); + } + + private static void EmbedTabSwitches() + { + Console.WriteLine("Embed: skills -> attrs -> progress -> off"); + FakeFace f = Fresh(); + long t = 5000; + OracleSkillsEmbed.SetActiveTab(0); + for (int i = 0; i < 20; i++, t += 16) Frame(t); + OracleSkillsEmbed.SetActiveTab(1); + for (int i = 0; i < 20; i++, t += 16) Frame(t); + OracleSkillsEmbed.SetActiveTab(2); + for (int i = 0; i < 20; i++, t += 16) Frame(t); + Eq(OracleSkillsEmbed.ActiveTab, 2, "progress selected"); + Eq((f.Subscribes, f.Unsubscribes), (1, 0), "switching tabs does not resubscribe or release"); + OracleSkillsEmbed.SetActiveTab(0); + Eq((f.Subscribes, f.Unsubscribes), (1, 0), "back to skills: still the same stretch"); + OracleSkillsEmbed.Clear(); // /rc oracle-skills off + Eq((f.Subscribes, f.Unsubscribes), (1, 1), "off: released once"); + Eq(OracleSkillsEmbed.ActiveTab, -1, "no tab"); + OracleSkillsEmbed.SetActiveTab(7); + Eq(OracleSkillsEmbed.ActiveTab, -1, "an out-of-range tab is off"); + OracleSkillsEmbed.SetActiveTab(-3); + Eq((f.Subscribes, f.Unsubscribes), (1, 1), "out-of-range tabs change nothing else"); + } + + private static void EmbedHideWithoutShow() + { + Console.WriteLine("Embed: hide without show"); + FakeFace f = Fresh(); + OracleSkillsEmbed.Clear(); + OracleSkillsEmbed.Sweep(1_000_000); + f.OnHidden(); + Eq((f.Subscribes, f.Unsubscribes), (0, 0), "nothing was shown: nothing released (no negative refcount)"); + Eq(f.Outstanding, 0, "outstanding is zero"); + } + + private static void EmbedDoubleClear() + { + Console.WriteLine("Embed: double Clear"); + FakeFace f = Fresh(); + OracleSkillsEmbed.SetActiveTab(0); + Frame(100); + OracleSkillsEmbed.Clear(); + OracleSkillsEmbed.Clear(); + OracleSkillsEmbed.Clear(); + Eq((f.Subscribes, f.Unsubscribes), (1, 1), "three Clears: one release"); + f.OnHidden(); + Eq(f.Unsubscribes, 1, "even a stray OnHidden on the face is a no-op"); + } + + private static void EmbedWindowClosedAndIdle() + { + Console.WriteLine("Embed: Oracle window closed / idle sweep"); + FakeFace f = Fresh(); + OracleSkillsEmbed.SetActiveTab(2); + Frame(0); Frame(16); + // ScriptWindowFace.OnHidden / ScriptWindowRegistry.RemoveLocked for the Oracle window: + Check(OracleSkillsEmbed.IsOraclePanel("script:RynthOracle/Oracle"), "the Oracle window's panel key matches"); + Check(!OracleSkillsEmbed.IsOraclePanel("script:RynthSort/Main"), "another script window's key does not"); + if (OracleSkillsEmbed.IsOraclePanel("script:RynthOracle/Oracle")) OracleSkillsEmbed.Clear(); + Eq((f.Subscribes, f.Unsubscribes), (1, 1), "window closed: released once"); + + // Idle: the tab stays set but nothing draws (window collapsed / owner crashed without sending off). + OracleSkillsEmbed.SetActiveTab(0); + Frame(10_000); Frame(10_016); + Eq(f.Subscribes, 2, "shown again"); + OracleSkillsEmbed.Sweep(10_016 + OracleSkillsEmbed.IdleMs); // exactly at the limit: still shown + Eq(f.Unsubscribes, 1, "at the idle limit: not yet released"); + OracleSkillsEmbed.Sweep(10_016 + OracleSkillsEmbed.IdleMs + 5000); + Eq((f.Subscribes, f.Unsubscribes), (2, 2), "past the idle limit: released once"); + OracleSkillsEmbed.Sweep(10_016 + OracleSkillsEmbed.IdleMs + 9000); + Eq(f.Unsubscribes, 2, "sweeping again releases nothing more"); + Frame(30_000); + Eq((f.Subscribes, f.Unsubscribes), (3, 2), "the window drawing again shows it again"); + OracleSkillsEmbed.Shutdown(); + Eq((f.Subscribes, f.Unsubscribes), (3, 3), "engine shutdown releases it"); + } + + private static void EmbedRaceAndShutdown() + { + Console.WriteLine("Embed: draw after Clear, shutdown"); + FakeFace f = Fresh(); + OracleSkillsEmbed.SetActiveTab(0); + Frame(1); + OracleSkillsEmbed.Clear(); + OracleSkillsEmbed.NoteDrawn(2); // a draw that read the tab just before Clear + Eq((f.Subscribes, f.Unsubscribes), (1, 1), "a draw after Clear does not re-show"); + OracleSkillsEmbed.Announce(); + Check(OracleSkillsEmbed.TabsAvailable(true), "announced and registered"); + OracleSkillsEmbed.Shutdown(); + Check(!OracleSkillsEmbed.TabsAvailable(true), "shutdown forgets the announcement"); + } + + private static void EmbedTwoThreads() + { + Console.WriteLine("Embed: Show and Clear from two threads"); + FakeFace f = Fresh(); + OracleSkillsEmbed.SetActiveTab(0); + var drawer = Task.Run(() => { for (int i = 0; i < 20000; i++) OracleSkillsEmbed.NoteDrawn(i); }); + var clearer = Task.Run(() => { for (int i = 0; i < 20000; i++) OracleSkillsEmbed.Clear(); }); + Task.WaitAll(drawer, clearer); + OracleSkillsEmbed.Clear(); + Eq(f.Subscribes, f.Unsubscribes, "every subscribe has its unsubscribe"); + Check(f.Outstanding == 0, "outstanding is zero"); + } + + private static void FaceOnShownTwice() + { + Console.WriteLine("Face: host and embed both asking"); + // The panel host calls OnShown once per open; the embed's latch may also call it. A face whose OnShown is + // idempotent subscribes once however it is asked. + var f = new FakeFace(); + f.OnShown(); f.OnShown(); f.OnShown(); + Eq(f.Subscribes, 1, "OnShown x3: one subscribe"); + f.OnHidden(); f.OnHidden(); + Eq((f.Subscribes, f.Unsubscribes), (1, 1), "OnHidden x2: one unsubscribe"); + } + + private static void TabsAvailableRule() + { + Console.WriteLine("TabsAvailable (Skills bar icon / routing)"); + Fresh(); + Eq(OracleSkillsEmbed.TabsAvailable(false), false, "no Oracle window, never announced: Skills icon stays"); + Eq(OracleSkillsEmbed.TabsAvailable(true), false, "an Oracle window that never announced (older Oracle): Skills icon stays"); + OracleSkillsEmbed.Announce(); + Eq(OracleSkillsEmbed.TabsAvailable(false), false, "announced but its window is gone: Skills icon returns"); + Eq(OracleSkillsEmbed.TabsAvailable(true), true, "window registered and announced: the tabs are there, icon hidden"); + OracleSkillsEmbed.Shutdown(); + } + + // ── The title bar ─────────────────────────────────────────────────── + + private static IEnumerable<(string Name, TitleSlot Slot)> Slots(InventoryTitleLayout l) + { + yield return ("Smaller", l.Smaller); + yield return ("Bigger", l.Bigger); + yield return ("Tools", l.Tools); + yield return ("Modern", l.Modern); + yield return ("Vault", l.Vault); + yield return ("Remote", l.Remote); + yield return ("Sort", l.Sort); + yield return ("Count", l.Count); + yield return ("GInv", l.GInv); + yield return ("More", l.More); + } + + private static void CheckLayout(InventoryTitleLayout l, float barW, float s, bool vault, float titleWant, string tag) + { + var present = Slots(l).Where(x => x.Slot.Present).OrderBy(x => x.Slot.X).ToList(); + foreach (var (name, slot) in present) + { + Check(slot.X >= -0.001f, $"{tag}: {name} starts on the bar (x={slot.X})"); + Check(slot.Right <= barW + 0.001f, $"{tag}: {name} ends on the bar (right={slot.Right}, bar={barW})"); + } + for (int i = 1; i < present.Count; i++) + Check(present[i - 1].Slot.Right <= present[i].Slot.X + 0.001f, + $"{tag}: {present[i - 1].Name} does not overlap {present[i].Name} ({present[i - 1].Slot.Right} vs {present[i].Slot.X})"); + Eq(l.Vault.Present, vault, $"{tag}: Vault present iff the server has it"); + bool extrasShown = l.Mode is TitleExtrasMode.Text or TitleExtrasMode.Icons; + Eq(l.Remote.Present && l.Sort.Present && l.Count.Present && l.GInv.Present, extrasShown, $"{tag}: all four related buttons or none"); + Eq(l.More.Present, l.Mode == TitleExtrasMode.Menu, $"{tag}: the more button iff Menu mode"); + Check(l.TitleLeft >= 0f && l.TitleRight >= l.TitleLeft, $"{tag}: title span is ordered ({l.TitleLeft}..{l.TitleRight})"); + Check(l.TitleRight <= l.LeftmostX + 0.001f, $"{tag}: title ends before the first button ({l.TitleRight} vs {l.LeftmostX})"); + Check(l.TitleWidth > 0f, $"{tag}: title width > 0 ({l.TitleWidth})"); + Check(l.Mode != TitleExtrasMode.None, $"{tag}: the related buttons are reachable from the bar (mode {l.Mode})"); + // The title keeps its minimum (or its whole text when shorter) whenever all four buttons are shown. + float owed = Math.Min(titleWant, InventoryTitleLayout.TitleMinUnits * s); + if (extrasShown) + Check(l.TitleWidth >= owed - 0.001f - InventoryTitleLayout.PadUnits * s, $"{tag}: title keeps its room ({l.TitleWidth} >= {owed})"); + } + + private static void TitleLayoutGrid() + { + Console.WriteLine("Title bar: widths 300/360/480 x scales 1/1.5/2 x Vault on/off"); + foreach (float units in new[] { 300f, 360f, 480f }) + foreach (float s in new[] { 1f, 1.5f, 2f }) + foreach (bool vault in new[] { true, false }) + foreach (float want in new[] { 40f, 135f, 190f }) + { + float barW = (units - 24f) * s; // the panel less the close button + var l = InventoryTitleLayout.Compute(barW, s, vault, want * s); + CheckLayout(l, barW, s, vault, want * s, $"{units}u s{s} vault={vault} title={want}"); + } + // The bar widths a 1.0-2.0 scale gives at the fixed retail panel (300 units x scale), at fractional scales too. + for (float s0 = 1f; s0 <= 2.0001f; s0 += 1f / 32f) + foreach (bool vault in new[] { true, false }) + { + float sc = MathF.Round(32f * s0) / 32f; + float barW = 276f * sc; + var l = InventoryTitleLayout.Compute(barW, sc, vault, 130f * sc); + CheckLayout(l, barW, sc, vault, 130f * sc, $"retail s={sc} vault={vault}"); + } + } + + private static void TitleLayoutModes() + { + Console.WriteLine("Title bar: which style at which width"); + Eq(InventoryTitleLayout.Compute(276f, 1f, true, 130f).Mode, TitleExtrasMode.Menu, "retail width + Vault: one more menu"); + Eq(InventoryTitleLayout.Compute(276f, 1f, false, 130f).Mode, TitleExtrasMode.Icons, "retail width, no Vault: four icons"); + Eq(InventoryTitleLayout.Compute(336f, 1f, true, 130f).Mode, TitleExtrasMode.Icons, "360 wide + Vault: icons"); + Eq(InventoryTitleLayout.Compute(456f, 1f, true, 130f).Mode, TitleExtrasMode.Text, "480 wide + Vault: text buttons"); + Eq(InventoryTitleLayout.Compute(456f * 1.5f, 1.5f, true, 130f * 1.5f).Mode, TitleExtrasMode.Text, "480 wide at 1.5x: text buttons"); + Eq(InventoryTitleLayout.Compute(276f * 1.5f, 1.5f, true, 130f * 1.5f).Mode, TitleExtrasMode.Menu, "retail at 1.5x + Vault: more menu"); + + // The case from the review: 190 px of text buttons used to push Vault to x=-44 at 300 / scale 1. + var r = InventoryTitleLayout.Compute(276f, 1f, true, 130f); + Check(r.Vault.X > 100f && r.Vault.Right <= r.Smaller.X, $"Vault sits just left of the toggles at retail width (x={r.Vault.X})"); + Check(r.TitleWidth >= 100f, $"and the title keeps {r.TitleWidth} px at retail width"); + + // Everything is relative to the bar: scaling the bar scales the positions (whole-pixel rounding aside). + var a = InventoryTitleLayout.Compute(276f, 1f, true, 130f); + var b = InventoryTitleLayout.Compute(552f, 2f, true, 260f); + Check(MathF.Abs(a.Vault.X * 2f - b.Vault.X) < 0.01f, "Vault at 2x is twice the 1x position"); + Check(MathF.Abs(a.More.X * 2f - b.More.X) < 0.01f, "More at 2x is twice the 1x position"); + } + + private static void TitleLayoutNarrow() + { + Console.WriteLine("Title bar: narrower than any real panel"); + for (float barW = 150f; barW <= 700f; barW += 5f) + { + var l = InventoryTitleLayout.Compute(barW, 1f, true, 130f); + var present = Slots(l).Where(x => x.Slot.Present).OrderBy(x => x.Slot.X).ToList(); + Check(l.Vault.Present && l.Vault.X >= 0f && l.Vault.Right <= barW, $"w={barW}: Vault present and on the bar"); + Check(present.All(x => x.Slot.X >= 0f && x.Slot.Right <= barW + 0.001f), $"w={barW}: every button on the bar"); + for (int i = 1; i < present.Count; i++) + Check(present[i - 1].Slot.Right <= present[i].Slot.X + 0.001f, $"w={barW}: {present[i - 1].Name} / {present[i].Name} do not overlap"); + Check(l.TitleWidth >= 0f, $"w={barW}: title width never negative"); + } + // Far too narrow for the toggles: Vault is clamped at the left edge, never negative; no related buttons. + var tiny = InventoryTitleLayout.Compute(60f, 1f, true, 130f); + Check(tiny.Vault.Present && tiny.Vault.X == 0f, "a 60 px bar: Vault pinned at x=0, not negative"); + Eq(tiny.Mode, TitleExtrasMode.None, "a 60 px bar: no related buttons"); + Check(tiny.TitleWidth >= 0f, "a 60 px bar: title width not negative"); + var noVault = InventoryTitleLayout.Compute(60f, 1f, false, 130f); + Check(!noVault.Vault.Present, "no Vault server: no Vault slot"); + } + + private static void TitleLayoutBadInput() + { + Console.WriteLine("Title bar: bad input"); + var l = InventoryTitleLayout.Compute(float.NaN, 0f, true, float.PositiveInfinity); + Check(float.IsFinite(l.Vault.X) && float.IsFinite(l.TitleRight), "NaN bar width, zero scale: finite positions"); + var m = InventoryTitleLayout.Compute(276f, float.NaN, false, -5f); + Check(float.IsFinite(m.Modern.X) && m.Modern.Right <= 276f, "NaN scale reads as 1"); + } + + private static void ElideTitle() + { + Console.WriteLine("Title: elide"); + Func m = t => t.Length * 7f; + string full = "Inventory of Drakkon1"; // 21 chars = 147 px + Eq(InventoryTitleLayout.Elide(full, 200f, m), full, "fits: unchanged"); + Eq(InventoryTitleLayout.Elide(full, 147f, m), full, "fits exactly: unchanged"); + string cut = InventoryTitleLayout.Elide(full, 100f, m); + Check(cut.EndsWith("...") && m(cut) <= 100f && cut.Length > 3, $"cut to fit with an ellipsis: '{cut}'"); + Eq(InventoryTitleLayout.Elide(full, 100f, m), cut, "same input, same output"); + Eq(InventoryTitleLayout.Elide(full, 21f, m), "...", "room for only the ellipsis"); + Eq(InventoryTitleLayout.Elide(full, 20f, m), "", "not even the ellipsis fits: nothing"); + Eq(InventoryTitleLayout.Elide(full, 0f, m), "", "no room: nothing"); + Eq(InventoryTitleLayout.Elide("", 100f, m), "", "empty stays empty"); + for (float w = 21f; w < 147f; w += 7f) + Check(m(InventoryTitleLayout.Elide(full, w, m)) <= w, $"never wider than the room ({w})"); + } + + private static void HeaderExtras() + { + Console.WriteLine("Modern header: icons / menu / none"); + Eq(InventoryTitleLayout.ChooseHeaderExtras(300f, 50f, out bool c1), TitleExtrasMode.Icons, "lots of room: four icons"); + Eq(c1, true, "and the count text"); + Eq(InventoryTitleLayout.ChooseHeaderExtras(100f, 50f, out bool c2), TitleExtrasMode.Menu, "room for the menu button and the count"); + Eq(c2, true, "count kept"); + Eq(InventoryTitleLayout.ChooseHeaderExtras(40f, 50f, out bool c3), TitleExtrasMode.Menu, "room for the menu button only"); + Eq(c3, false, "count text dropped before the menu button"); + Eq(InventoryTitleLayout.ChooseHeaderExtras(10f, 50f, out bool c4), TitleExtrasMode.None, "no room: none"); + Eq(c4, false, "nothing fits"); + Eq(InventoryTitleLayout.ChooseHeaderExtras(-20f, 50f, out bool c5), TitleExtrasMode.None, "negative room: none"); + Eq(c5, false, "no count either"); + Eq(InventoryTitleLayout.ChooseHeaderExtras(float.NaN, 50f, out _), TitleExtrasMode.None, "NaN room: none"); + } + + // ── The Modern header with the Aelrynth Vault button (2026-10-19; idea from Silentkelpie, rynth PR 6) ── + + private static IEnumerable<(string Name, TitleSlot Slot)> HeaderSlots(InventoryHeaderLayout h) + { + yield return ("Close", h.Close); + yield return ("Classic", h.Classic); + yield return ("Vault", h.Vault); + yield return ("Remote", h.Remote); + yield return ("Sort", h.Sort); + yield return ("Count", h.Count); + yield return ("GInv", h.GInv); + yield return ("More", h.More); + } + + private static void HeaderVault() + { + Console.WriteLine("Modern header: the Vault button"); + + // Without a vault the plan is exactly the old one, so the header is unchanged off Aelrynth. + foreach (float free in new[] { -30f, 0f, 10f, 24f, 40f, 90f, 100f, 130f, 300f }) + foreach (float cw in new[] { 0f, 30f, 50f, 80f }) + { + var plan = InventoryTitleLayout.ChooseHeader(free, cw, vault: false); + TitleExtrasMode old = InventoryTitleLayout.ChooseHeaderExtras(free, cw, out bool oldCount); + Check(!plan.Vault && plan.Extras == old && plan.ShowCount == oldCount, $"no vault: same as ChooseHeaderExtras (free {free}, count {cw})"); + } + + // With a vault the Vault takes its 24 px first; the rest shares what is left. + Eq(InventoryTitleLayout.ChooseHeader(300f, 50f, true).Extras, TitleExtrasMode.Icons, "lots of room + vault: four icons"); + Eq(InventoryTitleLayout.ChooseHeader(96f + 60f + 24f - 1f, 50f, true).Extras, TitleExtrasMode.Menu, "one px short of icons + vault: the menu"); + Eq(InventoryTitleLayout.ChooseHeader(96f + 60f + 24f, 50f, true).Extras, TitleExtrasMode.Icons, "icons + count + vault just fit"); + Eq(InventoryTitleLayout.ChooseHeader(24f + 24f + 60f, 50f, true).Extras, TitleExtrasMode.Menu, "vault + menu + count"); + var tight = InventoryTitleLayout.ChooseHeader(24f + 24f, 50f, true); + Check(tight.Vault && tight.Extras == TitleExtrasMode.Menu && !tight.ShowCount, "vault + menu, the count text dropped"); + var tiny = InventoryTitleLayout.ChooseHeader(24f, 50f, true); + Check(tiny.Vault && tiny.Extras == TitleExtrasMode.None && !tiny.ShowCount, "room for the vault only: no menu, no count"); + foreach (float free in new[] { 20f, 0f, -40f, float.NaN, float.NegativeInfinity }) + Check(InventoryTitleLayout.ChooseHeader(free, 50f, true).Vault, $"the Vault is kept whatever the room ({free})"); + + // Every supported width (the panel's minimum is 140 px) and a range of left-hand text widths: + // the Vault is present, inside the header, clear of the other buttons, and nothing drawn right of the + // pyreals overlaps anything else. Without a vault the geometry is the one the header always had. + int checkedLayouts = 0; + for (float w = 140f; w <= 800f; w += 1f) + foreach (float leftEnd in new[] { 80f, 120f, 150f, 200f }) + foreach (float cw in new[] { 0f, 40f, 70f }) + foreach (bool vault in new[] { true, false }) + { + var h = InventoryHeaderLayout.Compute(w, leftEnd, cw, vault); + string tag = $"w {w} leftEnd {leftEnd} count {cw} vault {vault}"; + checkedLayouts++; + var slots = HeaderSlots(h).Where(x => x.Slot.Present).OrderBy(x => x.Slot.X).ToList(); + bool ok = true; + foreach (var (name, slot) in slots) + { + if (slot.X < 0f || slot.Right > w + 0.001f) { ok = false; Console.WriteLine($" [FAIL] {tag}: {name} outside the header ({slot.X}..{slot.Right})"); } + } + for (int i = 1; i < slots.Count; i++) + if (slots[i].Slot.X < slots[i - 1].Slot.Right - 0.001f) + { + ok = false; + Console.WriteLine($" [FAIL] {tag}: {slots[i - 1].Name} and {slots[i].Name} overlap"); + } + Check(ok, $"{tag}: buttons inside the header and not overlapping"); + + Check(h.Plan.Vault == vault && h.Vault.Present == vault, $"{tag}: the Vault button exists exactly when asked for"); + if (vault) + { + Check(h.Vault.Right <= h.Classic.X + 0.001f && h.Vault.X >= 0f, $"{tag}: Vault sits left of the Classic button, inside the header"); + Check(h.Vault.W >= 22f, $"{tag}: Vault keeps its full 22 px size"); + foreach (var (name, slot) in slots) + if (name != "Vault" && name != "Close" && name != "Classic") + Check(slot.Right <= h.Vault.X + 0.001f, $"{tag}: {name} stays left of the Vault"); + } + else + { + Check(h.Classic.X == w - 46 && h.Close.X == w - 22, $"{tag}: Close / Classic where they always were"); + if (h.Plan.Extras == TitleExtrasMode.Icons) Check(h.GInv.X == w - 46 - 24 && h.Remote.X == w - 46 - 96, $"{tag}: the four icons where they always were"); + if (h.Plan.Extras == TitleExtrasMode.Menu) Check(h.More.X == w - 46 - 24, $"{tag}: the menu button where it always was"); + } + // Related buttons / count never reach back over the pyreals when there was room for them. + TitleSlot? leftmost = h.Plan.Extras == TitleExtrasMode.Icons ? h.Remote : h.Plan.Extras == TitleExtrasMode.Menu ? h.More : null; + if (leftmost is { } lm) + Check(lm.X >= leftEnd + 4f - 0.001f, $"{tag}: related buttons start clear of the pyreals text"); + if (h.Plan.ShowCount) + Check(h.CountX + cw <= (leftmost?.X ?? (vault ? h.Vault.X : h.Classic.X)) + 0.001f, $"{tag}: the count text sits left of the buttons"); + } + Check(checkedLayouts > 10000, $"swept the layouts ({checkedLayouts})"); + + // At the retail width (302 px) and the usual left-hand text the Vault is a button, and so are the + // rest that fit: a worked example. + var r = InventoryHeaderLayout.Compute(302f, 150f, 50f, vault: true); + Check(r.Vault.Present && r.Vault.X == 302f - 46 - 24, "302 px: Vault right beside the Classic button"); + Eq(r.Plan.Extras, TitleExtrasMode.Menu, "302 px with a vault: related panels fold into the menu"); + Check(r.More.Present && r.More.Right <= r.Vault.X, "...left of the Vault"); + var wide = InventoryHeaderLayout.Compute(600f, 150f, 50f, vault: true); + Eq(wide.Plan.Extras, TitleExtrasMode.Icons, "600 px with a vault: four icons"); + Check(wide.Vault.X == 600f - 46 - 24 && wide.GInv.X == wide.Vault.X - 24, "...the icons start just left of the Vault"); + + // Garbage in, no crash and the Vault still present. + var bad = InventoryHeaderLayout.Compute(float.NaN, float.NaN, float.NaN, vault: true); + Check(bad.Vault.Present, "NaN sizes: the Vault slot exists (the caller never draws a header this small)"); + } +} diff --git a/tools/ChatCoordTests/ChatCoordTests.csproj b/tools/ChatCoordTests/ChatCoordTests.csproj index fc8ce8f..861da0e 100644 --- a/tools/ChatCoordTests/ChatCoordTests.csproj +++ b/tools/ChatCoordTests/ChatCoordTests.csproj @@ -2,7 +2,7 @@ diff --git a/tools/ChatCoordTests/ChatSpanShim.cs b/tools/ChatCoordTests/ChatSpanShim.cs new file mode 100644 index 0000000..809fafd --- /dev/null +++ b/tools/ChatCoordTests/ChatSpanShim.cs @@ -0,0 +1,5 @@ +// Stand-in for the engine's ChatSpan (UI/Data/ChatRouting.cs, which drags the whole rule engine in): +// ChatCoords.LinkSpans only reads Start, Length and Argb. +namespace RynthCore.Engine.UI.Data; + +internal readonly record struct ChatSpan(int Start, int Length, uint Argb); diff --git a/tools/ChatCoordTests/Program.cs b/tools/ChatCoordTests/Program.cs index 2fad6ca..c2cae42 100644 --- a/tools/ChatCoordTests/Program.cs +++ b/tools/ChatCoordTests/Program.cs @@ -22,6 +22,9 @@ internal static class Program One("Your location is: 0xA9B40019 [84.000 7.100 42.005] 0.0 0.0 0.0 1.0 = 42.1N, 33.6E", 42.1, 33.6, "42.1N, 33.6E"); One("drudges at 42N 33E", 42, 33, "42.0N, 33.0E"); One("0.0N, 101.9W", 0, -101.9, "0.0N, 101.9W"); + // Pasted the way players often type them (lowercase, no space): RynthChat makes these links. + One("82.3n,34.2e", 82.3, 34.2, "82.3N, 34.2E"); + One("Bob says, \"meet at 82.3n, 34.2e\"", 82.3, 34.2, "82.3N, 34.2E"); // Two in one line, in order. var two = ChatCoords.Find("from 42.1N, 33.6E to 21.5S, 1.8W"); @@ -42,10 +45,103 @@ internal static class Program None(""); None(null); + PreCheck(); + LinkSpans(); + Console.WriteLine(_failed == 0 && _checks > 0 ? $"PASS ({_checks} checks)" : $"FAIL ({_failed} of {_checks})"); return _failed == 0 && _checks > 0 ? 0 : 1; } + /// The cheap pre-check ChatFace runs before the regex must never skip a line Find would link. + private static void PreCheck() + { + foreach (string t in new[] { "42.1N, 33.6E", "42N 33E", "33.6E 42.1N", "at 42.1 N, 33.6 E now", "82.3n,34.2e", "0.5S, 101.2W", "x1 n 2e" }) + Check(ChatCoords.MayHaveCoords(t), $"pre-check lets \"{t}\" through"); + foreach (string t in new[] { "", "hello world", "no digits here N E", "N5", "12 N (two spaces)", "forty two north" }) + Check(!ChatCoords.MayHaveCoords(t), $"pre-check skips \"{t}\""); + + // Soundness: over random lines built from coordinate-ish pieces, Find never finds a pair the pre-check skipped. + var rng = new Random(20261019); + string[] pieces = { "42.1", "33.6", "N", "S", "E", "W", "n", "e", " ", ", ", " ", "x", " ", "/", "101.9", "7.5", "5", "120" }; + int found = 0; + for (int k = 0; k < 60000; k++) + { + var sb = new System.Text.StringBuilder(); + for (int n = rng.Next(1, 9); n > 0; n--) sb.Append(pieces[rng.Next(pieces.Length)]); + string line = sb.ToString(); + if (ChatCoords.Find(line).Count > 0) + { + found++; + if (!ChatCoords.MayHaveCoords(line)) Check(false, $"pre-check skipped \"{line}\", which holds a coordinate"); + } + } + Check(found > 100, $"the random lines held coordinates to test with ({found})"); + Check(true, "pre-check never skipped a line with a coordinate"); + } + + private const uint LinkCol = 0xFF5ECFE0; + + /// The coordinate links laid over a rule's highlight spans. + private static void LinkSpans() + { + // No coordinates: the highlights come back as they were. + var plain = new[] { new ChatSpan(2, 3, 0xFF112233), new ChatSpan(8, 2, 0xFF445566) }; + Same(ChatCoords.LinkSpans(plain, new List(), LinkCol), plain, "no coordinates: highlights unchanged"); + Check(ChatCoords.LinkSpans(null, new List(), LinkCol).Length == 0, "no spans, no coordinates: nothing"); + + // A line with only a coordinate (no rule highlight): one link span over it. + string text = "meet at 42.1N, 33.6E soon"; + var coords = ChatCoords.Find(text); + var only = ChatCoords.LinkSpans(null, coords, LinkCol); + Check(only.Length == 1 && only[0].Start == coords[0].Start && only[0].Length == coords[0].Length && only[0].Argb == LinkCol, + "a coordinate alone becomes one link span"); + + // A highlight across the whole line is cut around the coordinate: before, link, after. + var whole = new[] { new ChatSpan(0, text.Length, 0xFFAA0000) }; + var cut = ChatCoords.LinkSpans(whole, coords, LinkCol); + Check(cut.Length == 3, $"a highlight over the coordinate is cut in two around it (got {cut.Length})"); + if (cut.Length == 3) + { + Check(cut[0].Start == 0 && cut[0].Length == coords[0].Start && cut[0].Argb == 0xFFAA0000, "the part before keeps the highlight"); + Check(cut[1].Start == coords[0].Start && cut[1].Length == coords[0].Length && cut[1].Argb == LinkCol, "the coordinate keeps the link colour"); + int end = coords[0].Start + coords[0].Length; + Check(cut[2].Start == end && cut[2].Start + cut[2].Length == text.Length && cut[2].Argb == 0xFFAA0000, "the part after keeps the highlight"); + } + + // A highlight that only covers part of the coordinate loses that part and keeps the rest. + var half = new[] { new ChatSpan(coords[0].Start - 3, 8, 0xFF00AA00) }; // ends inside the coordinate + var halfCut = ChatCoords.LinkSpans(half, coords, LinkCol); + Check(halfCut.Length == 2 && halfCut[0].Argb == 0xFF00AA00 && halfCut[0].Length == 3 && halfCut[1].Argb == LinkCol, + "a highlight ending inside the coordinate is cut at it"); + + // A highlight beside the coordinate (no overlap) is untouched; the result is sorted and never overlaps. + var beside = new[] { new ChatSpan(0, 4, 0xFF0000AA), new ChatSpan(coords[0].Start + coords[0].Length + 1, 4, 0xFF0000BB) }; + var res = ChatCoords.LinkSpans(beside, coords, LinkCol); + Check(res.Length == 3 && res[0].Argb == 0xFF0000AA && res[1].Argb == LinkCol && res[2].Argb == 0xFF0000BB, "highlights beside it stay, in order"); + NoOverlap(res, "beside"); + + // Two coordinates and several highlights: sorted, no overlap, every coordinate present exactly once. + string two = "from 42.1N, 33.6E to 21.5S, 1.8W now"; + var cs = ChatCoords.Find(two); + var hl = new[] { new ChatSpan(0, 9, 0xFF010101), new ChatSpan(10, 20, 0xFF020202) }; + var r2 = ChatCoords.LinkSpans(hl, cs, LinkCol); + NoOverlap(r2, "two coordinates"); + Check(r2.Count(s => s.Argb == LinkCol) == 2, "both coordinates are links"); + foreach (ChatCoord c in cs) + Check(r2.Any(s => s.Start == c.Start && s.Length == c.Length && s.Argb == LinkCol), $"link span for {c.Text}"); + } + + private static void NoOverlap(ChatSpan[] spans, string what) + { + bool ok = true; + for (int i = 1; i < spans.Length; i++) + if (spans[i].Start < spans[i - 1].Start + spans[i - 1].Length) ok = false; + Check(ok, $"{what}: sorted and non-overlapping"); + } + + private static void Same(ChatSpan[] got, ChatSpan[] want, string what) => + Check(got.Length == want.Length && got.Zip(want).All(p => p.First == p.Second), what); + private static void One(string text, double ns, double ew, string formatted) { var found = ChatCoords.Find(text); diff --git a/tools/ChatFilterTests/ChatFilterTests.csproj b/tools/ChatFilterTests/ChatFilterTests.csproj index 2b6669e..e8952a4 100644 --- a/tools/ChatFilterTests/ChatFilterTests.csproj +++ b/tools/ChatFilterTests/ChatFilterTests.csproj @@ -27,6 +27,13 @@ + + + + + + diff --git a/tools/ChatFilterTests/EngineStubs.cs b/tools/ChatFilterTests/EngineStubs.cs new file mode 100644 index 0000000..779ed30 --- /dev/null +++ b/tools/ChatFilterTests/EngineStubs.cs @@ -0,0 +1,24 @@ +// The two engine pieces ChatRouting.cs calls, without the engine (same stand-ins as +// tools/ChatHistoryBench/Stubs.cs): RynthLog.UI and ChatModel's MentionEligible / BumpFiltersVersion. + +namespace RynthCore.Engine.Compatibility +{ + internal static class RynthLog + { + public static int Lines; + public static void UI(string message) { Lines++; } + } +} + +namespace RynthCore.Engine.UI.Data +{ + internal static class ChatModel + { + public static int FilterBumps; + + internal static bool MentionEligible(string channel, int chatType) => + (channel == "Chat" || channel == "Channels") && chatType is not (4 or 9 or 11); + + internal static void BumpFiltersVersion() => FilterBumps++; + } +} diff --git a/tools/ChatFilterTests/Program.cs b/tools/ChatFilterTests/Program.cs index 2650fbf..c04d047 100644 --- a/tools/ChatFilterTests/Program.cs +++ b/tools/ChatFilterTests/Program.cs @@ -48,6 +48,11 @@ internal static class Program WhenParsing(); PresetsCatchAndSpare(); PresetsWellFormed(); + RetailChannels(); + RetailStandardFilters(); + RetailRules(); + RetailSetting(); + SharedFileReload(); LineColorTags(); LineColorKinds(); LineColorDefaultsUnchanged(); @@ -431,6 +436,246 @@ internal static class Program Check(ChatRuleMatching.WhenMatches(null, -1, "Chat", 2), "any"); } + // ── Retail chat verdict (2026-10-19; idea from Silentkelpie, rynth PR 6) ── + // A line the rules or standard filters hide also stays out of AC's own chat window. + // ChatRetailVerdict is the pure part of ChatModel.ShouldHideInRetail. + + private static ChatRouter RetailRouter(params ChatFilterRule[] rules) => + new(rules, mention: null, self: "", countHits: false); + + private static ChatFilterRule Rule(string pattern, ChatRuleAction action, string when = "", string tab = "") + { + var r = new ChatFilterRule { Pattern = pattern, Action = action, Tab = tab }; + r.When = when; + r.Recompile(); + return r; + } + + private static void ResetPresets() + { + foreach (var p in RynthCore.Engine.UI.Panels.RynthChatPresets.All) + { + p.Enabled = false; + p.Tab = ""; + } + } + + private static void RetailChannels() + { + Case("retail verdict: the channel is the one the RynthChat plugin files the line under"); + (string Line, int Type, string Channel)[] cases = + { + ("Bob says, \"hi\"", 2, "Chat"), + ("Bob tells you, \"hi\"", 3, "Chat"), + ("[Trade] Bob says, \"WTS\"", 8, "Channels"), + ("[Trade] Bob says, \"WTS\"", 0x1C, "Channels"), // ILT / ACECustom deliver channel lines as 0x1C + ("[General] Bob says, \"hi\"", 3, "Channels"), // the tag wins over the type + ("[Celestial Hand] Bob says, \"hi\"", 3, "Channels"), + ("[general] Bob says, \"hi\"", 3, "Channels"), // the tag is case-insensitive + ("[Generals] Bob says, \"hi\"", 3, "Chat"), // not a tag + ("You have killed 12 Drudges!", 0, "System"), + ("You evaded Tusker Guard!", 6, "Combat"), + ("Your spell fizzled.", 0x11, "Combat"), + ("[RynthAi] Nav loaded", 0, "Rynth"), + ("[RynthChat] hello", 3, "Rynth"), // plugin output is Rynth whatever type it was written with + ("[rynthai] lower case", 0, "Rynth"), + ("[RynthAi Item] Sword of Bob", 3, "Items"), // item info is checked before the Rynth prefix + ("[RynthAi Item]no space", 3, "Rynth"), // the Items prefix has its trailing space + ("something", 0x7F, "Other"), + }; + foreach (var (line, type, chan) in cases) + Check(ChatRetailVerdict.ChannelFor(line, type) == chan, $"'{line}' type {type} -> {chan} (got {ChatRetailVerdict.ChannelFor(line, type)})"); + Check(ChatRetailVerdict.ChannelFor("", 2) == "Chat" && ChatRetailVerdict.ChannelFor("", 0x7F) == "Other", "an empty line falls back to the type"); + for (int t = 0; t < 40; t++) + Check(ChatRetailVerdict.ChannelForType(t) == ChatRetailVerdict.ChannelFor("plain", t), $"type {t}: no tag, the type decides"); + } + + private static void RetailStandardFilters() + { + Case("retail verdict: ticked standard filters hide their lines, moves and unticked ones don't"); + var presets = RynthCore.Engine.UI.Panels.RynthChatPresets.All; + try + { + ResetPresets(); + ChatRouter none = RetailRouter(); + foreach (var p in presets) + { + int type = p.Where switch + { + RynthCore.Engine.UI.Panels.RynthChatPresets.Scope.CombatOnly => 0x11, + RynthCore.Engine.UI.Panels.RynthChatPresets.Scope.ChannelsOnly => 0x08, + _ => 0x00, + }; + Check(!ChatRetailVerdict.IsHidden(none, p.Example, type), $"{p.Id}: unticked, '{p.Example}' prints"); + p.Enabled = true; // hide + Check(ChatRetailVerdict.IsHidden(none, p.Example, type), $"{p.Id}: ticked, '{p.Example}' stays out of the retail chat"); + p.Tab = "Spam"; // moved to a tab: RynthChat shows it there, AC still prints it + Check(!ChatRetailVerdict.IsHidden(none, p.Example, type), $"{p.Id}: moved to a tab, '{p.Example}' still prints in AC"); + p.Enabled = false; + p.Tab = ""; + } + + // The reported case: Kill task progress. + var kill = RynthCore.Engine.UI.Panels.RynthChatPresets.Get("social.kill_task_progress"); + Check(kill != null, "social.kill_task_progress exists"); + if (kill != null) + { + const string killLine = "You have killed 22556 Fanatical Fiuns! You must kill 100000 to complete your task."; + kill.Enabled = true; + Check(ChatRetailVerdict.IsHidden(none, killLine, 0x00), "the kill-task line from the report is hidden"); + Check(ChatRetailVerdict.IsHidden(none, killLine, 0x1B), "...whatever system-ish type it arrives with"); + Check(!ChatRetailVerdict.IsHidden(none, "You have killed 3 Drudges! Your task is complete!", 0x00), "other kill lines print"); + // Player speech is never taken by a filter held to non-chat channels. + Check(!ChatRetailVerdict.IsHidden(none, "Bob says, \"" + killLine + "\"", 0x02), "a player saying it in Local prints"); + Check(!ChatRetailVerdict.IsHidden(none, "Bob tells you, \"" + killLine + "\"", 0x03), "a player telling it prints"); + } + } + finally { ResetPresets(); } + } + + private static void RetailRules() + { + Case("retail verdict: Hide rules hide, Move / Copy / colour rules and off rules don't"); + try + { + ResetPresets(); + Check(!ChatRetailVerdict.IsHidden(RetailRouter(), "anything", 3), "no rules: nothing hidden"); + Check(!ChatRetailVerdict.IsHidden(RetailRouter(Rule("spam", ChatRuleAction.Hide)), "fine line", 3), "a line the rule doesn't match prints"); + Check(ChatRetailVerdict.IsHidden(RetailRouter(Rule("spam", ChatRuleAction.Hide)), "buy spam now", 3), "a Hide rule hides it"); + Check(ChatRetailVerdict.IsHidden(RetailRouter(Rule("spam", ChatRuleAction.Hide)), "SPAM", 3), "...case-insensitively"); + + var off = Rule("spam", ChatRuleAction.Hide); + off.Enabled = false; + Check(!ChatRetailVerdict.IsHidden(RetailRouter(off), "buy spam now", 3), "a rule that is switched off hides nothing"); + Check(!ChatRetailVerdict.IsHidden(RetailRouter(Rule("spam", ChatRuleAction.Move, tab: "Mail")), "buy spam now", 3), "a Move rule prints in AC"); + Check(!ChatRetailVerdict.IsHidden(RetailRouter(Rule("spam", ChatRuleAction.Copy, tab: "Mail")), "buy spam now", 3), "a Copy rule prints in AC"); + var colour = Rule("spam", ChatRuleAction.Color); + colour.ColorMode = ChatColorMode.Line; + Check(!ChatRetailVerdict.IsHidden(RetailRouter(colour), "buy spam now", 3), "a colour rule prints in AC"); + + // First routing rule decides, as in RynthChat. + Check(!ChatRetailVerdict.IsHidden(RetailRouter(Rule("spam", ChatRuleAction.Move, tab: "Mail"), Rule("spam", ChatRuleAction.Hide)), "spam", 3), + "a Move rule ahead of a Hide rule decides: not hidden"); + Check(ChatRetailVerdict.IsHidden(RetailRouter(Rule("spam", ChatRuleAction.Hide), Rule("spam", ChatRuleAction.Move, tab: "Mail")), "spam", 3), + "a Hide rule ahead of a Move rule decides: hidden"); + + // "When" conditions see the channel RynthChat gives the line. + Check(ChatRetailVerdict.IsHidden(RetailRouter(Rule("Sword", ChatRuleAction.Hide, "chan:Items")), "[RynthAi Item] Sword of Bob", 3), "chan:Items rule hides item info"); + Check(!ChatRetailVerdict.IsHidden(RetailRouter(Rule("Sword", ChatRuleAction.Hide, "chan:Items")), "Bob says, \"Sword\"", 2), "...but not other lines"); + Check(ChatRetailVerdict.IsHidden(RetailRouter(Rule("loaded", ChatRuleAction.Hide, "chan:Rynth")), "[RynthAi] Nav loaded", 0), "chan:Rynth rule hides plugin output"); + Check(ChatRetailVerdict.IsHidden(RetailRouter(Rule("WTS", ChatRuleAction.Hide, "chan:Channels")), "[Trade] Bob says, \"WTS\"", 0x1C), "chan:Channels rule hides a tagged 0x1C channel line"); + Check(ChatRetailVerdict.IsHidden(RetailRouter(Rule("WTS", ChatRuleAction.Hide, "chan:Channels")), "[Trade] Bob says, \"WTS\"", 8), "...and a type 8 one"); + Check(!ChatRetailVerdict.IsHidden(RetailRouter(Rule("WTS", ChatRuleAction.Hide, "chan:Channels")), "Bob tells you, \"WTS\"", 3), "...not a tell"); + Check(ChatRetailVerdict.IsHidden(RetailRouter(Rule("busy", ChatRuleAction.Hide, "type:26")), "You're too busy!", 26), "type:26 rule hides a type 26 line"); + Check(!ChatRetailVerdict.IsHidden(RetailRouter(Rule("busy", ChatRuleAction.Hide, "type:26")), "You're too busy!", 0), "...not another type"); + + // A custom rule decides before the standard filters, as in RynthChat: a Move rule keeps a ticked filter from hiding the line. + var kill = RynthCore.Engine.UI.Panels.RynthChatPresets.Get("social.kill_task_progress")!; + kill.Enabled = true; + const string killLine = "You have killed 12 Drudges! You must kill 50 to complete your task."; + Check(ChatRetailVerdict.IsHidden(RetailRouter(Rule("nothing", ChatRuleAction.Hide)), killLine, 0), "a ticked filter hides when no rule decided first"); + Check(!ChatRetailVerdict.IsHidden(RetailRouter(Rule("killed", ChatRuleAction.Move, tab: "Kills")), killLine, 0), "a Move rule ahead of the ticked filter keeps the line"); + + // The retail router must not double count what RynthChat's own pass counts. + var counted = Rule("spam", ChatRuleAction.Hide); + RetailRouter(counted).Evaluate("spam", "Chat", 3, null); + Check(counted.Hits == 0, "a router built with countHits: false leaves Hits alone"); + } + finally { ResetPresets(); } + } + + private static void RetailSetting() + { + Case("retail verdict: the hideInRetail setting (on unless a file says false)"); + var opts = RynthChatJsonContext.Default.RynthChatSettingsDto; + RynthChatSettingsDto old = JsonSerializer.Deserialize(OldFile, opts)!; + Check(old.HideInRetail == null, "a file from before the setting has no value (ChatModel reads that as on)"); + string saved = JsonSerializer.Serialize(old, opts); + Check(!saved.Contains("hideInRetail", StringComparison.Ordinal), "saving an old file writes no hideInRetail key"); + + old.HideInRetail = false; + string off = JsonSerializer.Serialize(old, opts); + Check(off.Contains("\"hideInRetail\":false", StringComparison.Ordinal), "off is saved as hideInRetail:false"); + Check(JsonSerializer.Deserialize(off, opts)!.HideInRetail == false, "off loads back"); + old.HideInRetail = true; + Check(JsonSerializer.Deserialize(JsonSerializer.Serialize(old, opts), opts)!.HideInRetail == true, "on round-trips"); + Check(JsonSerializer.Deserialize("{\"hideInRetail\":null}", opts)!.HideInRetail == null, "null reads as absent"); + Check(JsonSerializer.Deserialize(off, opts)!.Filters!.Length == 3, "the other fields are untouched"); + } + + // ── Shared settings reload (2026-10-19; idea from Silentkelpie, rynth PR 6) ── + // SharedFileWatch: another client rewrote rynthchat_settings.json -> read it; our own saves don't count. + + private static void SharedFileReload() + { + Case("shared settings: a client re-reads the file when ANOTHER client saved it"); + string dir = Path.Combine(Path.GetTempPath(), "rynth-sharedwatch-" + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(dir); + try + { + string path = Path.Combine(dir, "rynthchat_settings.json"); + DateTime t0 = new(2026, 10, 19, 12, 0, 0, DateTimeKind.Utc); + void Write(string text, int secondsAfterT0) + { + File.WriteAllText(path, text); + File.SetLastWriteTimeUtc(path, t0.AddSeconds(secondsAfterT0)); + } + + // No file yet: nothing to read, no error. + var w = new SharedFileWatch(pollMs: 2000); + Check(w.Changed(10_000, path) == null, "no file: null"); + + // Loaded at start: that timestamp is not a change. + Write("{\"v\":1}", 0); + w.Seen(File.GetLastWriteTimeUtc(path)); + Check(w.Changed(20_000, path) == null, "the file we loaded is not a change"); + + // Another client saves: read once. + Write("{\"v\":2}", 5); + Check(w.Changed(20_500, path) == null, "...but not before the poll interval (2 s) is up"); + Check(w.Changed(22_000, path) == "{\"v\":2}", "another client's save is returned"); + Check(w.Changed(24_000, path) == null, "...once"); + + // Our own save (Saved is called just before the swap) is not a change. + string mine = "{\"v\":3,\"mine\":true}"; + w.Saved(mine); + Write(mine, 10); + Check(w.Changed(26_000, path) == null, "this client's own save is not a change"); + Check(w.Changed(28_000, path) == null, "...and stays quiet"); + + // Another client saves after ours: read. + Write("{\"v\":4}", 15); + Check(w.Changed(30_000, path) == "{\"v\":4}", "another client's later save is returned"); + // It saves the same text as our last save again (a copy of our settings): still ours by text. + Write(mine, 20); + Check(w.Changed(32_000, path) == null, "text identical to our last save is treated as ours"); + + // The same timestamp again (nothing written): not read. + Check(w.Changed(34_000, path) == null, "an unchanged timestamp is not read"); + + // A file that is being swapped (cannot be read): the change is offered again, not lost. + Write("{\"v\":5}", 25); + using (new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None)) + { + bool threw = false; + try { w.Changed(36_000, path); } + catch (IOException) { threw = true; } + Check(threw, "an unreadable file throws (the caller logs it)"); + } + Check(w.Changed(38_000, path) == "{\"v\":5}", "the change that could not be read is returned at the next poll"); + + // The file is removed: nothing, no throw. + File.Delete(path); + Check(w.Changed(40_000, path) == null, "a removed file is null"); + + // A watcher that never saw the file (no file at start) reads the first one it finds. + var late = new SharedFileWatch(pollMs: 2000); + Write("{\"v\":6}", 30); + Check(late.Changed(50_000, path) == "{\"v\":6}", "a file that appears after start is read"); + } + finally { try { Directory.Delete(dir, true); } catch { } } + } + // ── Standard filters ───────────────────────────────────────────────── private static void PresetsCatchAndSpare() diff --git a/tools/CombatSettingsTests/CombatSettingsTests.csproj b/tools/CombatSettingsTests/CombatSettingsTests.csproj new file mode 100644 index 0000000..ef8d545 --- /dev/null +++ b/tools/CombatSettingsTests/CombatSettingsTests.csproj @@ -0,0 +1,32 @@ + + + + + Exe + net10.0-windows + x86 + win-x86 + false + x86 + enable + enable + true + CombatSettingsTests + + + + + + + diff --git a/tools/CombatSettingsTests/Program.cs b/tools/CombatSettingsTests/Program.cs new file mode 100644 index 0000000..23984ae --- /dev/null +++ b/tools/CombatSettingsTests/Program.cs @@ -0,0 +1,182 @@ +using System.Collections; +using System.Reflection; +using System.Text.Json; +using System.Text.Json.Serialization.Metadata; + +namespace CombatSettingsTests +{ + // Reaches RynthCore.Engine's internal settings mirror, schema and Monsters rule by reflection. + // See the csproj. + internal static class Program + { + private static int _fails, _asserts; + private static void Check(bool cond, string msg) + { + _asserts++; + if (!cond) { _fails++; Console.WriteLine($" [FAIL] {msg}"); } + } + + private const string Ns = "RynthCore.Engine.UI.Data."; + private const BindingFlags All = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance; + + // RynthAi's SettingsBridgePayload names, with the type each mirror field must have. + private static readonly (string Name, Type Type, string Default)[] Mirrors = + { + ("VariablePowerMin", typeof(int?), "50"), + ("VariablePowerMax", typeof(int?), "100"), + ("MissileEnvironmentResponse", typeof(int?), "0"), + ("MagicEnvironmentResponse", typeof(int?), "0"), + ("EnvironmentImpactLimit", typeof(int?), "2"), + ("EnvironmentImpactWindowSec", typeof(int?), "20"), + ("EnvironmentApproachMeters", typeof(int?), "6"), + ("EnvironmentMinDistance", typeof(int?), "3"), + ("EnvironmentSkipSec", typeof(int?), "30"), + ("KitePullMeters", typeof(int?), "20"), + ("KiteTagFirst", typeof(bool?), "true"), + }; + + private static int Main() + { + Assembly engine = Assembly.Load("RynthCore.Engine"); + Type settingsType = engine.GetType(Ns + "RynthAiSettings", throwOnError: true)!; + Type ctxType = engine.GetType(Ns + "RynthAiSettingsJsonContext", throwOnError: true)!; + Type schemaType = engine.GetType(Ns + "SettingsSchema", throwOnError: true)!; + + object ctx = ctxType.GetProperty("Default", All)!.GetValue(null)!; + var info = (JsonTypeInfo)ctxType.GetProperty("RynthAiSettings", All)!.GetValue(ctx)!; + object Parse(string json) => JsonSerializer.Deserialize(json, info)!; + + // ── The mirrors ───────────────────────────────────────────────────────────── + object fresh = Activator.CreateInstance(settingsType, nonPublic: true)!; + string freshJson = JsonSerializer.Serialize(fresh, info); + foreach (var (name, type, _) in Mirrors) + { + PropertyInfo? p = settingsType.GetProperty(name, All); + Check(p != null && p.PropertyType == type, $"{name}: a nullable mirror of RynthAi's setting"); + if (p == null) continue; + Check(p.GetValue(fresh) == null, $"{name}: a fresh mirror holds no value (nothing is claimed until RynthAi sends it)"); + Check(p.GetValue(Parse("{\"BoostNavPriority\":true}")) == null, $"{name}: an older RynthAi's payload leaves it absent"); + Check(freshJson.Contains($"\"{name}\":null"), $"{name}: an unset mirror saves null, never a made-up value (RynthAi leaves its own alone)"); + } + string sent = "{\"VariablePowerMin\":40,\"VariablePowerMax\":90,\"MissileEnvironmentResponse\":2,\"MagicEnvironmentResponse\":3," + + "\"EnvironmentImpactLimit\":4,\"EnvironmentImpactWindowSec\":45,\"EnvironmentApproachMeters\":8,\"EnvironmentMinDistance\":5," + + "\"EnvironmentSkipSec\":60,\"KitePullMeters\":33,\"KiteTagFirst\":false}"; + object withValues = Parse(sent); + Check((int?)settingsType.GetProperty("VariablePowerMin", All)!.GetValue(withValues) == 40, "RynthAi's value arrives"); + Check((bool?)settingsType.GetProperty("KiteTagFirst", All)!.GetValue(withValues) == false, "a false bool arrives as false, not null"); + string back = JsonSerializer.Serialize(withValues, info); + foreach (string piece in new[] { "\"VariablePowerMax\":90", "\"MagicEnvironmentResponse\":3", "\"KitePullMeters\":33", "\"KiteTagFirst\":false" }) + Check(back.Contains(piece), $"a save sends back what RynthAi sent ({piece})"); + + // ── The rows ──────────────────────────────────────────────────────────────── + var tabs = new Dictionary>(); + foreach (object t in (IEnumerable)schemaType.GetField("Tabs", All)!.GetValue(null)!) + { + string tabName = (string)t.GetType().GetProperty("Name")!.GetValue(t)!; + tabs[tabName] = ((IEnumerable)t.GetType().GetProperty("Rows")!.GetValue(t)!).Cast().ToList(); + } + Check(tabs.ContainsKey("Melee Combat") && tabs.ContainsKey("Spell Combat"), "the Melee Combat and Spell Combat tabs exist"); + if (!tabs.ContainsKey("Melee Combat") || !tabs.ContainsKey("Spell Combat")) return Finish(); + + static string Label(object r) => (string?)r.GetType().GetProperty("Label")!.GetValue(r) ?? ""; + static string Kind(object r) => r.GetType().GetProperty("Kind")!.GetValue(r)!.ToString()!; + object? Row(string tab, string label, string kind) => tabs[tab].FirstOrDefault(r => Label(r) == label && Kind(r) == kind); + bool Visible(object row, object s) => (bool)row.GetType().GetMethod("IsVisible")!.Invoke(row, new[] { s })!; + double Get(object row, object s) => (double)((Delegate)row.GetType().GetProperty("Get")!.GetValue(row)!).DynamicInvoke(s)!; + void Set(object row, object s, double v) => ((Delegate)row.GetType().GetProperty("Set")!.GetValue(row)!).DynamicInvoke(s, v); + + // (tab, label, kind, default shown, min, max) + var rows = new (string Tab, string Label, string Kind, double Default, double Min, double Max)[] + { + ("Melee Combat", "Variable Min %", "Int", 50, 0, 100), + ("Melee Combat", "Variable Max %", "Int", 100, 0, 100), + ("Melee Combat", "Missile Response", "Combo", 0, 0, 3), + ("Melee Combat", "Hits to trip", "Int", 2, 1, 10), + ("Melee Combat", "Window (s)", "Int", 20, 5, 120), + ("Melee Combat", "Move closer by (m)", "Int", 6, 1, 30), + ("Melee Combat", "Closest (m)", "Int", 3, 1, 30), + ("Melee Combat", "Skip target (s)", "Int", 30, 5, 300), + ("Melee Combat", "Pull Distance (m)", "Int", 20, 3, 100), + ("Melee Combat", "Tag Before Fleeing", "Bool", 1, 0, 1), + ("Spell Combat", "Magic Response", "Combo", 0, 0, 3), + }; + object older = Parse("{\"BoostNavPriority\":true}"); // what an older RynthAi sends + object newer = Parse("{\"VariablePowerMin\":50,\"VariablePowerMax\":100,\"MissileEnvironmentResponse\":0,\"MagicEnvironmentResponse\":0," + + "\"EnvironmentImpactLimit\":2,\"EnvironmentImpactWindowSec\":20,\"EnvironmentApproachMeters\":6,\"EnvironmentMinDistance\":3," + + "\"EnvironmentSkipSec\":30,\"KitePullMeters\":20,\"KiteTagFirst\":true}"); // the plugin's own defaults + foreach (var (tab, label, kind, def, min, max) in rows) + { + object? row = Row(tab, label, kind); + Check(row != null, $"{tab} / {label}: a {kind} row"); + if (row == null) continue; + Check(!Visible(row, older), $"{label}: hidden for an older RynthAi (it never sent the value)"); + Check(!Visible(row, fresh), $"{label}: hidden before RynthAi has sent anything"); + Check(Visible(row, newer), $"{label}: shown once RynthAi sends it"); + Check(Get(row, newer) == def, $"{label}: shows the plugin's default ({def}) as sent"); + Check(Get(row, older) == def, $"{label}: reads the default for an unset mirror, without throwing"); + if (kind != "Bool") Check((double)row.GetType().GetProperty("Min")!.GetValue(row)! == min && (double)row.GetType().GetProperty("Max")!.GetValue(row)! == max, $"{label}: range {min}..{max}"); + } + + // Section headers and spacers of these groups follow the same gate (no empty headers on an older RynthAi). + foreach (string sec in new[] { "Variable Power (monster rules)", "Hitting the Environment", "Pull Away (Kite)" }) + foreach (string tab in new[] { "Melee Combat", "Spell Combat" }) + { + object? header = Row(tab, sec, "Section"); + if (header == null) continue; + Check(!Visible(header, older), $"{tab} / {sec}: the header is hidden for an older RynthAi"); + Check(Visible(header, newer), $"{tab} / {sec}: the header shows for a newer one"); + } + Check(Row("Melee Combat", "Pull Away (Kite)", "Section") != null && Row("Melee Combat", "Hitting the Environment", "Section") != null + && Row("Melee Combat", "Variable Power (monster rules)", "Section") != null && Row("Spell Combat", "Hitting the Environment", "Section") != null, "all four section headers exist"); + + // The combos list RynthAi's EnvironmentResponse in its order. + object missile = Row("Melee Combat", "Missile Response", "Combo")!; + var items = (string[])missile.GetType().GetProperty("Items")!.GetValue(missile)!; + Check(items.SequenceEqual(new[] { "Off", "Move closer", "New target", "Move closer, then new target" }), "Missile Response: Off, Move closer, New target, Move closer then new target (RynthAi's order)"); + + // A row edits only its own property; the rest rides along. + object edit = Parse("{\"BoostNavPriority\":true," + sent.TrimStart('{')); + Set(Row("Melee Combat", "Pull Distance (m)", "Int")!, edit, 55); + Set(Row("Melee Combat", "Tag Before Fleeing", "Bool")!, edit, 1); + Set(Row("Spell Combat", "Magic Response", "Combo")!, edit, 1); + string after = JsonSerializer.Serialize(edit, info); + Check(after.Contains("\"KitePullMeters\":55") && after.Contains("\"KiteTagFirst\":true") && after.Contains("\"MagicEnvironmentResponse\":1"), "the edits land on their own properties"); + Check(after.Contains("\"BoostNavPriority\":true") && after.Contains("\"EnvironmentSkipSec\":60") && after.Contains("\"MissileEnvironmentResponse\":2"), "the other settings ride along unchanged"); + + // The rows an older RynthAi lacks don't change what a plain save sends. + Set(Row("Melee Combat", "Pull Distance (m)", "Int")!, older, 30); // can't happen in the UI (hidden); must not throw + Check(true, "setting a hidden row doesn't throw"); + + // ── The monster rule: Power and Kite ──────────────────────────────────────── + Type damage = engine.GetType(Ns + "DamageCommands", throwOnError: true)!; + var powers = (string[])damage.GetField("AttackPowerModes", All)!.GetValue(null)!; + var kites = (string[])damage.GetField("KiteModes", All)!.GetValue(null)!; + Check(powers.SequenceEqual(new[] { "Default", "High", "Reckless", "Variable", "Reckless + Variable" }), "Power choices are spelled as RynthAi's AttackPowerModes"); + Check(kites.SequenceEqual(new[] { "Default", "Off", "PullAway" }), "Kite choices are spelled as RynthAi's KiteModes"); + + Type monsters = engine.GetType("RynthCore.Engine.UI.Panels.MonstersPanel", throwOnError: true)!; + Type rule = monsters.GetNestedType("Rule", All)!; + object r1 = Activator.CreateInstance(rule, nonPublic: true)!; + Check((string)rule.GetProperty("AttackPower")!.GetValue(r1)! == "Default", "a new rule's Power is Default (follows the DEFAULT line)"); + Check((string)rule.GetProperty("Kite")!.GetValue(r1)! == "Default", "a new rule's Kite is Default (Off on the DEFAULT line)"); + MethodInfo equal = monsters.GetMethod("RulesEqual", All)!; + Type listType = typeof(List<>).MakeGenericType(rule); + IList Lst(params object[] xs) { var l = (IList)Activator.CreateInstance(listType)!; foreach (object x in xs) l.Add(x); return l; } + object r2 = Activator.CreateInstance(rule, nonPublic: true)!; + Check((bool)equal.Invoke(null, new object[] { Lst(r1), Lst(r2) })!, "two default rules are equal"); + rule.GetProperty("Kite")!.SetValue(r2, "PullAway"); + Check(!(bool)equal.Invoke(null, new object[] { Lst(r1), Lst(r2) })!, "a changed Kite is a change (it is saved)"); + object r3 = Activator.CreateInstance(rule, nonPublic: true)!; + rule.GetProperty("AttackPower")!.SetValue(r3, "Variable"); + Check(!(bool)equal.Invoke(null, new object[] { Lst(r1), Lst(r3) })!, "a changed Power is a change (it is saved)"); + + return Finish(); + } + + private static int Finish() + { + Console.WriteLine(_fails == 0 ? $"All {_asserts} checks passed." : $"{_fails} of {_asserts} checks FAILED."); + return _fails == 0 ? 0 : 1; + } + } +} diff --git a/tools/EngineRobustnessTests/AutoIdDrainTests.cs b/tools/EngineRobustnessTests/AutoIdDrainTests.cs index 9b74a64..2f61ab5 100644 --- a/tools/EngineRobustnessTests/AutoIdDrainTests.cs +++ b/tools/EngineRobustnessTests/AutoIdDrainTests.cs @@ -82,6 +82,41 @@ internal static partial class Program DrainBounds(); DrainCombatHoldsInventory(); DrainSweepRetriesAfterOverflow(); + DrainReachesItemsBehindTheEvaluationBudget(); + } + + // Review fix 2026-10-18: more than MaxEvaluatedPerTick items waiting (here the pack waits through + // combat) used to leave the newest ones, at the end of the list, unlooked-at for as long as the + // earlier ones kept waiting. The drain now resumes where it stopped. + private static void DrainReachesItemsBehindTheEvaluationBudget() + { + _case = "drain round robin"; + const uint Chest = 0x80000B00, Loot = 0x80000B01; + var w = new FakeWorld { Now = 1_000_000, Warm = true }; + var d = new AutoIdDrain(w); + int pack = AutoIdDrain.MaxEvaluatedPerTick + 88; + for (uint i = 1; i <= pack; i++) { w.Snapshot[0x8000D000 + i] = (Me, 0); d.Offer(0x8000D000 + i, w.Now - 10_000); } + w.Snapshot[Loot] = (Chest, 0); d.Offer(Loot, w.Now - 10_000); // newest: last in the list + AutoIdDrain.Context Fight() => new() + { + Now = w.Now, Mode = AutoIdMode.Limited, PlayerId = Me, OpenContainer = Chest, OpenedAtMs = w.Now - 5_000, + SettleUntilMs = 0, LoginCompleteAtMs = 1, CombatBusy = true, + }; + d.Tick(Fight(), 0); + Check(d.PendingCount == pack + 1, $"first tick: the pack waits, the chest item is behind the budget (pending {d.PendingCount})"); + Check(!w.Sent.Any(s => s.Id == Loot), "first tick: the chest item was not reached yet"); + for (int k = 0; k < 4; k++) { w.Now += 100; d.Tick(Fight(), 0); } + Check(w.Sent.Any(s => s.Id == Loot), "within a few ticks the chest item is reached and sent although the pack keeps waiting"); + Check(!w.Sent.Any(s => (s.Id & 0xFFFFF000) == 0x8000D000), "while the pack, in combat, sent nothing"); + Check(d.PendingCount == pack, $"and the waiting pack is all still pending (pending {d.PendingCount})"); + // Every pack item is looked at in turn: end the fight and they all go out. + AutoIdDrain.Context Calm() => new() + { + Now = w.Now, Mode = AutoIdMode.Limited, PlayerId = Me, OpenContainer = 0, OpenedAtMs = 0, + SettleUntilMs = 0, LoginCompleteAtMs = 1, CombatBusy = false, + }; + for (int k = 0; k < 4000 && d.PendingCount > 0; k++) { w.Now += 100; d.Tick(Calm(), 0); } + Check(d.PendingCount == 0, $"after combat the whole backlog drains (pending {d.PendingCount})"); } // The pack is created at login, before the snapshot is warm; it must still go out. diff --git a/tools/EngineRobustnessTests/EngineRobustnessTests.csproj b/tools/EngineRobustnessTests/EngineRobustnessTests.csproj index d2af213..614c390 100644 --- a/tools/EngineRobustnessTests/EngineRobustnessTests.csproj +++ b/tools/EngineRobustnessTests/EngineRobustnessTests.csproj @@ -20,6 +20,7 @@ AutoIdDrain.cs the AutoId backlog against a fake world: login sweep, cold snapshot, refused sends kept, bounds IdRequester.cs the engine-send marker that tags every engine 0xC8 + DumpBudget.cs the full OOM dump needs free space and a cap on dumps across clients PumpGuards.cs TickAll's own steps are caught (logged once, then counted); the hang report names the plugin call the pump is inside Run: dotnet run -c Release (exit 0 = pass, 1 = fail) @@ -48,6 +49,7 @@ + diff --git a/tools/EngineRobustnessTests/Program.cs b/tools/EngineRobustnessTests/Program.cs index 6e08030..4bc1b52 100644 --- a/tools/EngineRobustnessTests/Program.cs +++ b/tools/EngineRobustnessTests/Program.cs @@ -37,6 +37,10 @@ internal static partial class Program TransitionDiagonalAndBorderWalksNeverHold(); TransitionTwoLandblockJumpHolds(); TransitionDrainHoldThenStopsSurvive(); + TransitionValveOpensAfterMaxHold(); + TransitionValveStuckPortalAndReset(); + TransitionGateDisabledNeverHolds(); + TransitionValveIgnoresShortTransitions(); AddressSpaceFold(); @@ -266,6 +270,104 @@ internal static partial class Program Check(!s.InTransition(9000 + WorldTransitionState.SettleMs), "window ends"); } + // The safety valve (review 2026-10-18): a character that keeps reading dead (Health 0 after a + // revive) must not freeze every queued action for good. + private static void TransitionValveOpensAfterMaxHold() + { + _case = "valve dead forever"; + var s = Started(); + long t = 2000; + var e = s.Sample(t, true, false, 0x00AE); + Check((e & WorldTransitionState.Edge.Died) != 0 && !s.Overridden, "dead: gate held, valve shut"); + Check(s.Decide(t, 1500, false) == WorldTransitionState.Verdict.Hold, "an action queued before is held"); + int overrideEdges = 0; + long openedAt = 0; + for (t += 1000; t <= 2000 + WorldTransitionState.MaxHoldMs + 10_000; t += 1000) + { + e = s.Sample(t, true, false, 0x00AE); // still reading dead + if ((e & WorldTransitionState.Edge.GateOverride) != 0) { overrideEdges++; openedAt = t; } + if (t < 2000 + WorldTransitionState.MaxHoldMs) + Check(s.InTransition(t) && !s.Overridden, $"held before the bound (t={t})"); + } + Check(overrideEdges == 1, $"exactly one override edge, got {overrideEdges}"); + Check(openedAt == 2000 + WorldTransitionState.MaxHoldMs, $"opens at the bound, got {openedAt - 2000} ms"); + Check(s.Overridden && s.Overrides == 1, "valve open, counted once"); + long now = t; + Check(!s.InTransition(now), "open: nothing is in transition any more"); + Check(s.RawInTransition(now), "(the raw state still says dead)"); + Check(s.Decide(now, now - 10, false) == WorldTransitionState.Verdict.Run, "new work runs"); + Check(s.Decide(now, 1500, false) == WorldTransitionState.Verdict.Drop, "work queued during the hold is dropped as stale, like after any transition"); + Check(s.Decide(now, 1500, true) == WorldTransitionState.Verdict.Run, "a stop queued during the hold still runs"); + // The character does come back later: the raw transition ends, and the valve re-arms. + s.Sample(now + 1000, false, false, 0x00AE); + Check(s.Overridden, "revived, but the settle window is still running: still open"); + s.Sample(now + 1000 + WorldTransitionState.SettleMs, false, false, 0x00AE); + Check(!s.Overridden && !s.RawInTransition(now + 1000 + WorldTransitionState.SettleMs), "settled: valve re-armed"); + var d = s.Sample(now + 20_000, true, false, 0x00AE); + Check((d & WorldTransitionState.Edge.Died) != 0 && s.InTransition(now + 20_000), "the next death holds again"); + Check(s.HeldForMs(now + 20_000) == 0, "held-for restarts from the new transition"); + } + + private static void TransitionValveStuckPortalAndReset() + { + _case = "valve stuck portal"; + var s = Started(); + s.Sample(2000, false, true, 0x00AE); + long t = 2000; + bool opened = false; + for (; t < 2000 + WorldTransitionState.MaxHoldMs + 5000; t += 500) + if ((s.Sample(t, false, true, 0x00AE) & WorldTransitionState.Edge.GateOverride) != 0) opened = true; + Check(opened && !s.InTransition(t) && s.Overrides == 1, "a portal flag that never clears opens the gate once"); + // Exiting the portal ends it. + s.Sample(t, false, false, 0x00AE); + s.Sample(t + WorldTransitionState.SettleMs + 1, false, false, 0x00AE); + Check(!s.Overridden, "re-armed after the transition ends"); + } + + private static void TransitionGateDisabledNeverHolds() + { + _case = "gate disabled"; + var s = Started(); + s.Enabled = false; + s.Sample(2000, true, false, 0x00AE); + Check(s.RawInTransition(2000) && !s.InTransition(2000), "dead, gate off: not in transition"); + Check(!s.CheckHolding(2000) && s.LastBlockedMs == 0, "nothing held, nothing recorded"); + Check(s.Decide(2000, 1900, false) == WorldTransitionState.Verdict.Run, "work runs through a death"); + Check(s.Decide(2000, 1900, true) == WorldTransitionState.Verdict.Run, "and stops too"); + long late = 2000 + WorldTransitionState.MaxHoldMs + 1000; + s.Sample(late, true, false, 0x00AE); + Check(s.Overrides == 1, "the valve counter still counts (only information while the gate is off)"); + s.Enabled = true; + s.Sample(late + 1000, true, false, 0x00AE); + Check(!s.InTransition(late + 1000), "turned on again while the valve is open: stays open until the transition ends"); + } + + private static void TransitionValveIgnoresShortTransitions() + { + _case = "valve short transitions"; + var s = Started(); + long t = 2000; + // 40 deaths/portals in a row, each well under the bound, each followed by a quiet spell. + for (int i = 0; i < 40; i++) + { + s.Sample(t, true, false, 0x00AE); + t += 20_000; + s.Sample(t, false, true, 0x00AE); + t += 20_000; + s.Sample(t, false, false, 0x00AE); + t += WorldTransitionState.SettleMs + 1000; + s.Sample(t, false, false, 0x00AE); + t += 10_000; + } + Check(s.Overrides == 0, $"transitions that end on their own never trip it, got {s.Overrides}"); + // A death straight into a portal without a gap is ONE continuous transition. + var u = Started(); + u.Sample(2000, true, false, 0x00AE); + u.Sample(2000 + 60_000, false, true, 0x00AE); + var edges = u.Sample(2000 + 125_000, false, true, 0x00AE); + Check((edges & WorldTransitionState.Edge.GateOverride) != 0, "dead then portaling without a gap: one transition, valve opens at the bound"); + } + private static void TransitionLandblockJumpWithoutPortalHolds() { _case = "transition jump"; diff --git a/tools/EngineRobustnessTests/RingAndGateTests.cs b/tools/EngineRobustnessTests/RingAndGateTests.cs index 080d96c..81391f7 100644 --- a/tools/EngineRobustnessTests/RingAndGateTests.cs +++ b/tools/EngineRobustnessTests/RingAndGateTests.cs @@ -21,6 +21,8 @@ internal static partial class Program RequestIdNeverMergesIntoAHeldEntry(); ReleasedDataKeptSoRecreateSkips(); + ReleasedDataStaleOnLongAbsenceIsDroppedAtRecreate(); + DumpBudgetRules(); ReleasedDataExpiresAndServerDeleteEvicts(); TeleportMessageStartsTheWindow(); @@ -267,13 +269,84 @@ internal static partial class Program // Client release (BeingDeleted): AppraisalHooks.OnClientRelease if (!keep.OnRelease(50, t + 60_000)) cache.Remove(50); elig.OnClientRelease(50); - // Re-created 5 minutes later: AutoIdService.Enqueue (MarkLive, then the decision) - keep.Forget(50); - var d = elig.OnCreate(50, t + 5 * 60_000, cache.Contains(50)); - Check(d == AutoIdEligibility.CreateDecision.SkipRecent, $"re-created within 10 min with the data kept: skipped ({d})"); + // Re-created 30 s later (out of view and back): AutoIdService.Enqueue (MarkLive, then the decision) + if (keep.TakeLive(50, t + 90_000)) cache.Remove(50); + var d = elig.OnCreate(50, t + 90_000, cache.Contains(50)); + Check(d == AutoIdEligibility.CreateDecision.SkipRecent, $"re-created soon after the release with the data kept: skipped ({d})"); Check(elig.SkippedRecentTotal == 1, $"SkippedRecentCount moves (got {elig.SkippedRecentTotal})"); } + /// + /// Review fix 2026-10-18: data kept since a release ReleasedObjectRetention.StaleAfterMs ago or + /// more is dropped when the object is re-created (the client sent no updates meanwhile, so a + /// stack count could be minutes old), and the re-create is appraised again. + /// + private static void ReleasedDataStaleOnLongAbsenceIsDroppedAtRecreate() + { + _case = "release stale"; + var cache = new HashSet(); + var keep = new ReleasedObjectRetention(); + var elig = new AutoIdEligibility(); + long t = 1000; + elig.OnCreate(60, t, cache.Contains(60)); + elig.OnSent(60, t + 100); + cache.Add(60); + if (!keep.OnRelease(60, t + 1000)) cache.Remove(60); + elig.OnClientRelease(60); + Check(keep.IsReleased(60), "released: kept"); + + // 5 minutes later it comes back. + long back = t + 1000 + 5 * 60_000; + bool stale = keep.TakeLive(60, back); + Check(stale, "re-created 5 min after the release: its kept data is stale"); + if (stale) cache.Remove(60); // AppraisalHooks.MarkLive evicts it + Check(!keep.IsReleased(60), "and it is current again"); + var d = elig.OnCreate(60, back, cache.Contains(60)); + Check(d == AutoIdEligibility.CreateDecision.Appraise, $"the re-create is a candidate again ({d})"); + + // Exactly at the bound, and just under it. + var k2 = new ReleasedObjectRetention(); + k2.OnRelease(1, 10_000); k2.OnRelease(2, 10_000); + Check(!k2.TakeLive(1, 10_000 + ReleasedObjectRetention.StaleAfterMs - 1), "just under StaleAfterMs: kept"); + Check(k2.TakeLive(2, 10_000 + ReleasedObjectRetention.StaleAfterMs), "at StaleAfterMs: stale"); + Check(!k2.TakeLive(3, 99_999), "never released: not stale"); + Check(!k2.TakeLive(2, 99_999_999), "and a second create finds nothing to expire"); + } + + /// DumpBudget: the full OUT OF MEMORY dump needs room on the volume and a cap across clients. + private static void DumpBudgetRules() + { + _case = "dump budget"; + const long GB = 1024L * 1024 * 1024, MB = 1024L * 1024; + long est = DumpBudget.EstimateFullDumpBytes(3 * GB); + Check(est == 3 * GB + DumpBudget.FullDumpOverheadBytes, "the estimate is the private bytes plus the overhead"); + Check(DumpBudget.EstimateFullDumpBytes(0) == DumpBudget.FallbackProcessBytes + DumpBudget.FullDumpOverheadBytes, + "unknown size: the 32-bit maximum"); + + Check(DumpBudget.Evaluate(100 * GB, est, 0, 0) == DumpVerdict.Full, "plenty of room, no other dumps: full"); + Check(DumpBudget.Evaluate(-1, est, 0, 0) == DumpVerdict.LowDisk, "free space unknown: not full"); + Check(DumpBudget.Evaluate(est + DumpBudget.MinFreeAfterFullDump - 1, est, 0, 0) == DumpVerdict.LowDisk, + "one byte short of leaving the margin free: low disk"); + Check(DumpBudget.Evaluate(est + DumpBudget.MinFreeAfterFullDump, est, 0, 0) == DumpVerdict.Full, "exactly the margin: full"); + Check(DumpBudget.Evaluate(2 * GB, est, 0, 0) == DumpVerdict.LowDisk, "a nearly full disk: small dump instead"); + + // N clients hitting the OOM box together: placeholders count, so only a few get a full dump. + int full = 0; + int count = 0; + long bytes = 0; + for (int client = 0; client < 10; client++) + { + if (DumpBudget.Evaluate(500 * GB, est, count, bytes) == DumpVerdict.Full) { full++; count++; bytes += 0; /* a placeholder is empty */ } + } + Check(full == DumpBudget.MaxFullDumpsAllPids, $"10 clients at once: {DumpBudget.MaxFullDumpsAllPids} full dumps at most, got {full}"); + Check(DumpBudget.Evaluate(500 * GB, est, 2, 12 * GB) == DumpVerdict.TooManyBytes, "two dumps already at 12 GB: the bytes cap"); + Check(DumpBudget.Evaluate(500 * GB, est, DumpBudget.MaxFullDumpsAllPids, 1 * MB) == DumpVerdict.TooManyDumps, "the count cap"); + Check(DumpBudget.Evaluate(1 * GB, est, DumpBudget.MaxFullDumpsAllPids, 0) == DumpVerdict.LowDisk, "low disk is reported first"); + + Check(DumpBudget.SmallDumpAllowed(DumpBudget.SmallDumpMinFree) && !DumpBudget.SmallDumpAllowed(DumpBudget.SmallDumpMinFree - 1) + && !DumpBudget.SmallDumpAllowed(-1), "the small dump needs its own margin, and not an unknown disk"); + } + private static void ReleasedDataExpiresAndServerDeleteEvicts() { _case = "release expiry"; diff --git a/tools/EngineSettingsTests/EngineSettingsTests.csproj b/tools/EngineSettingsTests/EngineSettingsTests.csproj index afc8f70..4df08fd 100644 --- a/tools/EngineSettingsTests/EngineSettingsTests.csproj +++ b/tools/EngineSettingsTests/EngineSettingsTests.csproj @@ -23,10 +23,14 @@ + + + + diff --git a/tools/EngineSettingsTests/Program.cs b/tools/EngineSettingsTests/Program.cs index 7449ca4..f217dfe 100644 --- a/tools/EngineSettingsTests/Program.cs +++ b/tools/EngineSettingsTests/Program.cs @@ -3,6 +3,7 @@ using System.Text; using System.Text.Json; using System.Text.RegularExpressions; using RynthCore.Engine.Plugins; +using static RynthCore.Engine.UI.AcWindowChromePolicy; namespace RynthCore.Engine { @@ -47,12 +48,23 @@ namespace EngineSettingsTests Run(nameof(OwnedKeysMatchEngineSettings), OwnedKeysMatchEngineSettings); Run(nameof(SaveKeepsLauncherKeys), SaveKeepsLauncherKeys); Run(nameof(SaveRoundTripsOwnedKeys), SaveRoundTripsOwnedKeys); + Run(nameof(MergeChangedKeysOnly), MergeChangedKeysOnly); + Run(nameof(StaleClientDoesNotOverwriteOtherClientsKeys), StaleClientDoesNotOverwriteOtherClientsKeys); + Run(nameof(EverySetterWritesOnlyItsOwnKey), EverySetterWritesOnlyItsOwnKey); + Run(nameof(NoSaveWithoutAKey), NoSaveWithoutAKey); Run(nameof(AutoIdModeRoundTrips), AutoIdModeRoundTrips); Run(nameof(SaveWithoutFileWritesOwnedKeys), SaveWithoutFileWritesOwnedKeys); Run(nameof(SaveLeavesMalformedFileAlone), SaveLeavesMalformedFileAlone); Run(nameof(MaxHotReloadsReadAndKept), MaxHotReloadsReadAndKept); Run(nameof(CloseOnServerDisconnectDefaultOnAndSaved), CloseOnServerDisconnectDefaultOnAndSaved); + Run(nameof(TransitionGateDefaultOnAndSaved), TransitionGateDefaultOnAndSaved); + Run(nameof(HoldReloadInWorldOptInAndSaved), HoldReloadInWorldOptInAndSaved); Run(nameof(IltServerNamesEdit), IltServerNamesEdit); + Run(nameof(DisplaySettingsDefaultsAndSaved), DisplaySettingsDefaultsAndSaved); + Run(nameof(BorderlessDecisions), BorderlessDecisions); + Run(nameof(PlacementDecisions), PlacementDecisions); + Run(nameof(PlacementFilesArePerClient), PlacementFilesArePerClient); + Run(nameof(PlacementFileRoundTrips), PlacementFileRoundTrips); } finally { @@ -83,8 +95,37 @@ namespace EngineSettingsTests case "hook-off": EngineSettings.SetUiHookEnabled(args[1], false); break; case "add-plugin": EngineSettings.AddPluginPath(args[1]); break; case "imgui-off": EngineSettings.EnableImGuiBackend = false; break; + case "insertrel-on": EngineSettings.InsertReleasesUi = true; break; + case "remove-plugin": EngineSettings.RemovePluginPath(int.Parse(args[1])); break; + case "stale": + // A stale client: it has read the file (EnsureLoaded), another client then edits + // the file (args[1] = a JSON object merged over it), and only then does this client + // change one setting (args[2..] = a child command) and save. + { + _ = EngineSettings.TransitionGate; + string file = Environment.GetEnvironmentVariable("RYNTHCORE_ENGINE_SETTINGS")!; + var theirs = System.Text.Json.Nodes.JsonNode.Parse(File.ReadAllText(file))!.AsObject(); + foreach (var kv in System.Text.Json.Nodes.JsonNode.Parse(args[1])!.AsObject().ToList()) + { + theirs.Remove(kv.Key); + theirs[kv.Key] = kv.Value?.DeepClone(); + } + File.WriteAllText(file, theirs.ToJsonString()); + return Child(args.Skip(2).ToArray()); + } case "dcclose-off": EngineSettings.CloseOnServerDisconnect = false; break; case "dcclose-on": EngineSettings.CloseOnServerDisconnect = true; break; + case "tgate-off": EngineSettings.TransitionGate = false; break; + case "tgate-on": EngineSettings.TransitionGate = true; break; + case "borderless-on": EngineSettings.BorderlessWindowed = true; break; + case "borderless-off": EngineSettings.BorderlessWindowed = false; break; + case "layout-on": EngineSettings.RememberWindowLayout = true; break; + case "layout-off": EngineSettings.RememberWindowLayout = false; break; + case "acpos-on": EngineSettings.RememberAcWindowPosition = true; break; + case "acpos-off": EngineSettings.RememberAcWindowPosition = false; break; + case "hold-on": EngineSettings.HoldReloadInWorld = true; break; + case "hold-off": EngineSettings.HoldReloadInWorld = false; break; + case "hold-minutes": EngineSettings.HoldReloadInWorldMaxMinutes = int.Parse(args[1]); break; case "autoid": if (!RynthCore.Engine.Compatibility.AutoIdPolicy.TryParseMode(args[1], out var aim)) throw new ArgumentException(args[1]); EngineSettings.AutoIdMode = aim; @@ -100,6 +141,12 @@ namespace EngineSettingsTests Console.WriteLine("ServerMessageStream=" + EngineSettings.ServerMessageStream); Console.WriteLine("MaxHotReloads=" + EngineSettings.MaxHotReloads); Console.WriteLine("CloseOnServerDisconnect=" + EngineSettings.CloseOnServerDisconnect); + Console.WriteLine("TransitionGate=" + EngineSettings.TransitionGate); + Console.WriteLine("BorderlessWindowed=" + EngineSettings.BorderlessWindowed); + Console.WriteLine("RememberWindowLayout=" + EngineSettings.RememberWindowLayout); + Console.WriteLine("RememberAcWindowPosition=" + EngineSettings.RememberAcWindowPosition); + Console.WriteLine("HoldReloadInWorld=" + EngineSettings.HoldReloadInWorld); + Console.WriteLine("HoldReloadInWorldMaxMinutes=" + EngineSettings.HoldReloadInWorldMaxMinutes); Console.WriteLine("IltServerNames=" + (EngineSettings.IltServerNames is { } n ? string.Join("|", n) : "(none)")); break; default: throw new ArgumentException(args[0]); @@ -185,14 +232,17 @@ namespace EngineSettingsTests Eq(after.GetProperty("SomeNumber").GetRawText(), "1.50", "a number keeps its exact text"); Eq(after.GetProperty("Unicode").GetString(), "Dereth \u00e9 \u2014", "non-ASCII text intact"); - // The engine's own keys: written from memory as before. + // The engine's own keys: only the one changed (DisabledUiHooks) is written; every other + // key keeps exactly what the file had (another client's change to those must not be + // overwritten with this client's stale copy). Eq(string.Join(",", after.GetProperty("DisabledUiHooks").EnumerateArray().Select(e => e.GetString())), "StartTooltip", "DisabledUiHooks written"); Eq(Raw(after.GetProperty("PluginPaths")), Raw(before.GetProperty("PluginPaths")), "PluginPaths kept"); - Eq(after.GetProperty("EnableImGuiShell").GetBoolean(), false, "EnableImGuiShell kept (read, written back)"); + Eq(after.GetProperty("EnableImGuiShell").GetBoolean(), false, "EnableImGuiShell kept"); Eq(after.GetProperty("DecalBridge").GetString(), "On", "DecalBridge On kept"); - Check(!after.TryGetProperty("DecalInGameImGui", out _), "DecalInGameImGui at its default is left out, as before"); + foreach (JsonProperty p in before.EnumerateObject()) + Check(after.TryGetProperty(p.Name, out JsonElement kept) && JsonElement.DeepEquals(kept, p.Value), $"unchanged key {p.Name} keeps the file's value"); foreach (string key in new[] { "EnablePlugins", "EnableDatShareHook", "EnableAvaloniaOverlay", "EnableD3D9Hook", "EnableEngine", "EngineHookCount", "EnableHangMinidump", "PreventIdleLogoff" }) - Check(after.TryGetProperty(key, out _), $"owned key {key} written as before"); + Check(after.TryGetProperty(key, out _) == before.TryGetProperty(key, out _), $"owned key {key} not added or dropped by an unrelated save"); // No key twice. var names = after.EnumerateObject().Select(p => p.Name).ToList(); @@ -226,6 +276,175 @@ namespace EngineSettingsTests Check(ReadJson(path).TryGetProperty("EnableDcompOverlay", out _), "launcher key still there"); } + // EngineSettingsFile.Merge with changedKeys: only the changed keys come from the engine, a changed + // key at its default (left out of ownedJson) is removed, everything else keeps the file's value. + private static void MergeChangedKeysOnly() + { + var keys = new HashSet(StringComparer.Ordinal) { "A", "B", "C", "D" }; + string existing = """{ "A": 1, "B": 2, "C": 3, "D": 4, "Launcher": { "x": 1 }, "Mystery": [1, 2] }"""; + + byte[]? merged = EngineSettingsFile.Merge(existing, Owned("""{ "A": 10, "B": 20, "C": 30 }"""), keys, out string? err, new[] { "B" }); + Check(merged != null && err == null, "merged"); + JsonElement r = JsonDocument.Parse(merged!).RootElement; + Eq(r.GetProperty("B").GetInt32(), 20, "the changed key B is taken from the engine"); + Eq(r.GetProperty("A").GetInt32(), 1, "A (owned, unchanged) keeps the file's value"); + Eq(r.GetProperty("C").GetInt32(), 3, "C (owned, unchanged) keeps the file's value"); + Eq(r.GetProperty("D").GetInt32(), 4, "D (owned, not written by the engine, unchanged) is kept, not dropped"); + Eq(Raw(r.GetProperty("Launcher")), """{"x":1}""", "an unowned key is kept"); + Eq(Raw(r.GetProperty("Mystery")), "[1,2]", "an unknown key is kept"); + Eq(r.EnumerateObject().Count(), 6, "no key lost or duplicated"); + + // A changed key the engine left out (back at its default) is removed. + merged = EngineSettingsFile.Merge(existing, Owned("""{ "A": 10 }"""), keys, out _, new[] { "D" }); + r = JsonDocument.Parse(merged!).RootElement; + Check(!r.TryGetProperty("D", out _), "a changed key at its default is removed"); + Eq(r.GetProperty("A").GetInt32(), 1, "...and A still keeps the file's value"); + + // A changed key the file doesn't have yet is added. + merged = EngineSettingsFile.Merge("""{ "A": 1 }""", Owned("""{ "A": 10, "B": 20 }"""), keys, out _, new[] { "B" }); + r = JsonDocument.Parse(merged!).RootElement; + Eq(r.GetProperty("B").GetInt32(), 20, "a changed key not in the file is added"); + Eq(r.GetProperty("A").GetInt32(), 1, "A untouched"); + + // No file (or an empty one): nothing to keep, everything the engine writes goes in. + foreach (string? none in new[] { null, "", " " }) + { + merged = EngineSettingsFile.Merge(none, Owned("""{ "A": 10, "B": 20 }"""), keys, out _, new[] { "B" }); + Eq(Raw(JsonDocument.Parse(merged!).RootElement), """{"A":10,"B":20}""", $"'{none}': the whole settings are written when there is no file"); + } + + // No changedKeys (null): the old behaviour, every owned key rewritten from the engine. + merged = EngineSettingsFile.Merge(existing, Owned("""{ "A": 10, "B": 20 }"""), keys, out _); + r = JsonDocument.Parse(merged!).RootElement; + Eq(r.GetProperty("A").GetInt32(), 10, "without changedKeys A is rewritten"); + Check(!r.TryGetProperty("C", out _), "without changedKeys an owned key the engine left out is dropped"); + + // An unreadable file is still refused with changedKeys. + byte[]? refused = EngineSettingsFile.Merge("{ \"A\": ", Owned("""{ "A": 1 }"""), keys, out string? bad, new[] { "A" }); + Check(refused == null && !string.IsNullOrEmpty(bad), "an unreadable file is refused"); + } + + // The 2026-10-16 bug: a client that never touched a setting wrote its stale copy over another + // client's change. "stale" = the child has loaded the file, another client edits it, then the child + // saves a different setting. + private static void StaleClientDoesNotOverwriteOtherClientsKeys() + { + string dir = NewDir("stale"); + string path = Path.Combine(dir, "engine.json"); + File.WriteAllText(path, LauncherFile); + + // The other client turned several settings away from the default (this client holds the defaults). + const string other = """ + { "TransitionGate": false, "BorderlessWindowed": true, "RememberWindowLayout": false, + "RememberAcWindowPosition": true, "HoldReloadInWorld": true, "HoldReloadInWorldMaxMinutes": 45, + "CloseOnServerDisconnect": false, "EnableImGuiBackend": false, "InsertReleasesUi": true, + "AutoIdMode": "All", "EnableImGuiShell": true, "IltServerNames": [ "Other" ], + "FromNewerBuild": { "k": [ 1, 2 ] } } + """; + var (exit, output) = RunChild(path, "stale", other, "hook-off", "StartTooltip"); + Eq(exit, 0, "stale child exit code (" + output.Trim() + ")"); + JsonElement after = ReadJson(path); + using JsonDocument theirsDoc = JsonDocument.Parse(other); + foreach (JsonProperty p in theirsDoc.RootElement.EnumerateObject()) + Check(after.TryGetProperty(p.Name, out JsonElement v) && JsonElement.DeepEquals(v, p.Value), $"the other client's {p.Name} survives this client's save"); + + // The key this client changed is written. + Eq(string.Join(",", after.GetProperty("DisabledUiHooks").EnumerateArray().Select(e => e.GetString())), "StartTooltip", "this client's own change is written"); + // The launcher's / unknown keys are still there. + Check(after.TryGetProperty("LauncherWindow", out _) && after.TryGetProperty("EnableDcompOverlay", out _), "launcher keys kept"); + + // A stale client changing a key back to its default removes just that key. + (exit, output) = RunChild(path, "stale", """{ "HoldReloadInWorld": false }""", "tgate-on"); + Eq(exit, 0, "second stale child exit code (" + output.Trim() + ")"); + after = ReadJson(path); + Check(!after.TryGetProperty("TransitionGate", out _), "TransitionGate changed back to its default is dropped"); + Eq(after.GetProperty("HoldReloadInWorld").GetBoolean(), false, "...and the other client's later HoldReloadInWorld=false is not reset"); + Eq(after.GetProperty("BorderlessWindowed").GetBoolean(), true, "...nor BorderlessWindowed"); + + // Both clients change the same key: the later save is the one on disk (nothing to merge). + (exit, output) = RunChild(path, "stale", """{ "HoldReloadInWorldMaxMinutes": 60 }""", "hold-minutes", "90"); + Eq(exit, 0, "same-key child exit code (" + output.Trim() + ")"); + Eq(ReadJson(path).GetProperty("HoldReloadInWorldMaxMinutes").GetInt32(), 90, "the same key changed in both: the later save wins"); + + Eq(DumpValue(RunChild(path, "dump").Out, "BorderlessWindowed"), "True", "a later start reads the other client's value"); + var keys = ReadJson(path).EnumerateObject().Select(p => p.Name).ToList(); + Eq(keys.Count, keys.Distinct(StringComparer.Ordinal).Count(), "no duplicate keys"); + NoTempFilesLeft(dir); + } + + // Each public setter's Save("Key") must name the key it changed: a wrong or missing name would + // silently not persist. For every setter: a file with a non-default value for the other keys, + // the setter run, and only that one key may differ afterwards. + private static void EverySetterWritesOnlyItsOwnKey() + { + string dir = NewDir("setters"); + string path = Path.Combine(dir, "engine.json"); + string plugin = Path.Combine(dir, "RynthCore.Plugin.RynthNav.dll"); + // Sentinels away from every default, so a key written from memory shows up as a difference. + string seed = LauncherFile.Replace("\"LoggingLevel\"", """ + "EnablePlugins": false, "EnableDatShareHook": false, "EnableAvaloniaOverlay": false, "EnableD3D9Hook": false, + "EnableEngine": false, "EngineHookCount": 7, "EnableHangMinidump": false, "PreventIdleLogoff": false, + "DecalStandDown": false, "ServerMessageStream": false, "FlightRecorder": false, + "EnableLargeAddressAlignmentFix": false, "MaxHotReloads": 7, "ReportEndpoint": "http://x.invalid/", + "EnablePluginOverlayWindows": false, "LoadAllServerPlugins": true, "IltHosts": [ "h.invalid" ], + "DisabledUiHooks": [ "Seed" ], "HoldReloadInWorldMaxMinutes": 33, "LoggingLevel" + """); + + // (child args, the engine.json key that setter owns, expected raw JSON afterwards or null = just "changed") + var cases = new (string[] Args, string Key, string? Raw)[] + { + (new[] { "imgui-off" }, "EnableImGuiBackend", "false"), + (new[] { "dcclose-off" }, "CloseOnServerDisconnect", "false"), + (new[] { "hook-off", "StartTooltip" }, "DisabledUiHooks", "[\"Seed\",\"StartTooltip\"]"), + (new[] { "insertrel-on" }, "InsertReleasesUi", "true"), + (new[] { "borderless-on" }, "BorderlessWindowed", "true"), + (new[] { "layout-off" }, "RememberWindowLayout", "false"), + (new[] { "acpos-on" }, "RememberAcWindowPosition", "true"), + (new[] { "hold-on" }, "HoldReloadInWorld", "true"), + (new[] { "hold-minutes", "90" }, "HoldReloadInWorldMaxMinutes", "90"), + (new[] { "ilt-add", "Frosthaven" }, "IltServerNames", null), + (new[] { "autoid", "all" }, "AutoIdMode", "\"All\""), + (new[] { "tgate-off" }, "TransitionGate", "false"), + (new[] { "add-plugin", plugin }, "PluginPaths", null), + (new[] { "remove-plugin", "0" }, "PluginPaths", null), + }; + foreach (var (args, key, raw) in cases) + { + File.WriteAllText(path, seed); + JsonElement before = ReadJson(path); + var (exit, output) = RunChild(path, args); + Eq(exit, 0, $"{args[0]}: exit code ({output.Trim()})"); + JsonElement after = ReadJson(path); + Check(after.TryGetProperty(key, out JsonElement v), $"{args[0]}: {key} written"); + if (raw != null && after.TryGetProperty(key, out v)) + Eq(Raw(v), raw, $"{args[0]}: {key} value"); + if (after.TryGetProperty(key, out v) && before.TryGetProperty(key, out JsonElement was)) + Check(!JsonElement.DeepEquals(v, was), $"{args[0]}: {key} actually changed"); + foreach (JsonProperty p in before.EnumerateObject()) + if (p.Name != key) + Check(after.TryGetProperty(p.Name, out JsonElement kept) && JsonElement.DeepEquals(kept, p.Value), $"{args[0]}: other key {p.Name} keeps the file's value"); + foreach (JsonProperty p in after.EnumerateObject()) + if (p.Name != key) + Check(before.TryGetProperty(p.Name, out _), $"{args[0]}: no other key ({p.Name}) added"); + } + } + + // Source guard: the only argument-less Save() call is the one inside Save(string key). A new + // setter written as plain Save() would write nothing under the changed-keys rule. + private static void NoSaveWithoutAKey() + { + string source = File.ReadAllText(FindUp(Path.Combine("src", "RynthCore.Engine", "Plugins", "EngineSettings.cs"))); + int bare = Regex.Matches(source, @"^\s*Save\(\);", RegexOptions.Multiline).Count; + Eq(bare, 1, "EngineSettings.cs: Save() with no key is called only from Save(string key)"); + int keyed = 0; + foreach (Match m in Regex.Matches(source, @"^\s*Save\(""(\w+)""\);", RegexOptions.Multiline)) + { + keyed++; + Check(EngineSettings.OwnedKeys.Contains(m.Groups[1].Value), $"Save(\"{m.Groups[1].Value}\") names an owned key"); + } + Check(keyed >= 14, $"found the keyed Save calls ({keyed})"); + } + private static void AutoIdModeRoundTrips() { string dir = NewDir("autoid"); @@ -363,6 +582,257 @@ namespace EngineSettingsTests } } + // engine.json TransitionGate (2026-10-18): default on, only a hand-set false is written, other saves keep + // it, a value that is not a boolean is ignored. + private static void TransitionGateDefaultOnAndSaved() + { + string dir = NewDir("tgate"); + string path = Path.Combine(dir, "engine.json"); + + File.WriteAllText(path, LauncherFile); + Eq(DumpValue(RunChild(path, "dump").Out, "TransitionGate"), "True", "missing: on"); + Eq(RunChild(path, "hook-off", "StartTooltip").Exit, 0, "save with the default"); + Check(!ReadJson(path).TryGetProperty("TransitionGate", out _), "the default isn't written to the file"); + + var (exit, output) = RunChild(path, "tgate-off"); + Eq(exit, 0, "turn off (" + output.Trim() + ")"); + Eq(ReadJson(path).GetProperty("TransitionGate").GetRawText(), "false", "off is saved"); + Check(ReadJson(path).TryGetProperty("LauncherWindow", out _), "launcher keys kept"); + Eq(DumpValue(RunChild(path, "dump").Out, "TransitionGate"), "False", "off read back at the next start"); + Eq(RunChild(path, "hook-off", "CheckTooltip").Exit, 0, "another save"); + Eq(ReadJson(path).GetProperty("TransitionGate").GetRawText(), "false", "off survives other saves"); + + Eq(RunChild(path, "tgate-on").Exit, 0, "turn on"); + Check(!ReadJson(path).TryGetProperty("TransitionGate", out _), "on again: dropped from the file"); + + foreach (string bad in new[] { "\"no\"", "0", "null" }) + { + File.WriteAllText(path, LauncherFile.Replace("\"LoggingLevel\"", $"\"TransitionGate\": {bad}, \"LoggingLevel\"")); + Eq(DumpValue(RunChild(path, "dump").Out, "TransitionGate"), "True", $"{bad}: ignored, on"); + } + } + + // Settings > Display (2026-10-18): BorderlessWindowed off and RememberAcWindowPosition off by default, + // RememberWindowLayout on (panels have always been remembered). Only the non-default is written; + // other saves keep it; a value that is not a boolean is ignored. + private static void DisplaySettingsDefaultsAndSaved() + { + string dir = NewDir("display"); + string path = Path.Combine(dir, "engine.json"); + File.WriteAllText(path, LauncherFile); + + string dump = RunChild(path, "dump").Out; + Eq(DumpValue(dump, "BorderlessWindowed"), "False", "borderless defaults off"); + Eq(DumpValue(dump, "RememberWindowLayout"), "True", "panel remembering defaults on (unchanged behaviour)"); + Eq(DumpValue(dump, "RememberAcWindowPosition"), "False", "game window position is opt-in"); + + Eq(RunChild(path, "hook-off", "StartTooltip").Exit, 0, "save with the defaults"); + foreach (string key in new[] { "BorderlessWindowed", "RememberWindowLayout", "RememberAcWindowPosition" }) + Check(!ReadJson(path).TryGetProperty(key, out _), key + ": the default isn't written to the file"); + + (string cmd, string key, string raw, string value)[] cases = + { + ("borderless-on", "BorderlessWindowed", "true", "True"), + ("layout-off", "RememberWindowLayout", "false", "False"), + ("acpos-on", "RememberAcWindowPosition", "true", "True"), + }; + foreach (var (cmd, key, raw, value) in cases) + { + var (exit, output) = RunChild(path, cmd); + Eq(exit, 0, cmd + " (" + output.Trim() + ")"); + Eq(ReadJson(path).GetProperty(key).GetRawText(), raw, key + " is saved"); + Check(ReadJson(path).TryGetProperty("LauncherWindow", out _), key + ": launcher keys kept"); + Eq(DumpValue(RunChild(path, "dump").Out, key), value, key + " read back at the next start"); + } + Eq(RunChild(path, "hook-off", "CheckTooltip").Exit, 0, "another save"); + foreach (var (_, key, raw, _) in cases) + Eq(ReadJson(path).GetProperty(key).GetRawText(), raw, key + " survives other saves"); + + Eq(RunChild(path, "borderless-off").Exit, 0, "borderless back off"); + Eq(RunChild(path, "layout-on").Exit, 0, "layout back on"); + Eq(RunChild(path, "acpos-off").Exit, 0, "position back off"); + foreach (var (_, key, _, _) in cases) + Check(!ReadJson(path).TryGetProperty(key, out _), key + ": back at the default, dropped from the file"); + + foreach (string key in new[] { "BorderlessWindowed", "RememberWindowLayout", "RememberAcWindowPosition" }) + foreach (string bad in new[] { "\"no\"", "0", "null" }) + { + File.WriteAllText(path, LauncherFile.Replace("\"LoggingLevel\"", $"\"{key}\": {bad}, \"LoggingLevel\"")); + string d = RunChild(path, "dump").Out; + Eq(DumpValue(d, "BorderlessWindowed"), "False", $"{key}={bad}: borderless stays off"); + Eq(DumpValue(d, "RememberWindowLayout"), "True", $"{key}={bad}: layout stays on"); + Eq(DumpValue(d, "RememberAcWindowPosition"), "False", $"{key}={bad}: position stays off"); + } + } + + // ── AcWindowChromePolicy: borderless windowed ─────────────────────── + + private const int Windowed = 0x14CF0000 | WsCaption | WsThickFrame | WsSysMenu | WsMinimizeBox | WsMaximizeBox; + private const int Popup = unchecked((int)0x90000000); // WS_POPUP | WS_VISIBLE: no chrome at all + + private static void BorderlessDecisions() + { + // Setting off, a chrome-less window, no marker: it is not ours - no change at all. + foreach (bool fullscreenLooking in new[] { false, true }) + { + var d = DecideBorderless(want: false, marker: 0, style: Popup, looksExclusiveFullscreen: fullscreenLooking); + Eq(d.Action, ChromeAction.None, $"off + chrome-less + no marker (fullscreen-looking={fullscreenLooking}): no change"); + } + // Setting off, a window with chrome, no marker: nothing either. + Eq(DecideBorderless(false, 0, Windowed, false).Action, ChromeAction.None, "off + chrome + no marker: no change"); + + // Setting off, our marker, chrome still gone: restore, even when the window fills the monitor. + foreach (bool fullscreenLooking in new[] { false, true }) + { + int stripped = Windowed & ~BorderChromeMask; + var d = DecideBorderless(false, marker: Windowed, style: stripped, looksExclusiveFullscreen: fullscreenLooking); + Eq(d.Action, ChromeAction.Restore, $"off + our marker + stripped (fullscreen-looking={fullscreenLooking}): restore"); + Eq(d.NewStyle & BorderChromeMask, Windowed & BorderChromeMask, "all the chrome bits come back"); + Eq(d.NewStyle & ~BorderChromeMask, stripped & ~BorderChromeMask, "the other style bits stay as they are now"); + } + // Our marker, but someone already gave the chrome back (or the marker is junk): only drop it. + Eq(DecideBorderless(false, Windowed, Windowed, false).Action, ChromeAction.ClearMarker, "off + marker + chrome back: marker dropped"); + Eq(DecideBorderless(false, Popup, Popup, false).Action, ChromeAction.ClearMarker, "off + marker without a caption: dropped, not restored"); + + // Setting on: strip once and set the marker. + var strip = DecideBorderless(true, 0, Windowed, false); + Eq(strip.Action, ChromeAction.Strip, "on + chrome + no marker: strip"); + Eq(strip.NewStyle & BorderChromeMask, 0, "the chrome bits are gone"); + Eq(strip.NewMarker, Windowed, "the marker holds the style from before"); + Check(strip.NewMarker != 0, "the marker is never 0 (0 means 'not ours')"); + // ...and the next tick, with the marker and no chrome: nothing more to do. + Eq(DecideBorderless(true, strip.NewMarker, strip.NewStyle, false).Action, ChromeAction.None, "on + marker + stripped: nothing more"); + // Chrome that is not ours and not there (external tool, fullscreen): leave it, no marker. + Eq(DecideBorderless(true, 0, Popup, false).Action, ChromeAction.None, "on + already chrome-less, no marker: leave it"); + Eq(DecideBorderless(true, 0, Popup, true).Action, ChromeAction.None, "on + exclusive fullscreen, no marker: leave it"); + // The game put the chrome back after we stripped: strip again. + Eq(DecideBorderless(true, Windowed, Windowed, false).Action, ChromeAction.Strip, "on + marker + chrome came back: strip again"); + // Flagged as fullscreen-looking without our marker: left alone. + Eq(DecideBorderless(true, 0, Windowed, true).Action, ChromeAction.None, "on + no marker + flagged fullscreen: left alone"); + } + + // ── AcWindowChromePolicy: window position ─────────────────────────── + + private static void PlacementDecisions() + { + var main = new Rect(0, 0, 1920, 1080); + var second = new Rect(1920, 0, 3840, 1080); + var one = new[] { main }; + var two = new[] { main, second }; + + Eq(EvaluatePlacement(true, false, new Rect(100, 100, 1100, 800), one), PlacementVerdict.Ok, "on-screen rect is fine"); + Eq(EvaluatePlacement(false, false, new Rect(100, 100, 1100, 800), one), PlacementVerdict.OptedOut, "opted out: never"); + Eq(EvaluatePlacement(true, true, new Rect(100, 100, 1100, 800), one), PlacementVerdict.ExclusiveFullscreen, "exclusive fullscreen: skipped"); + + // Off-screen: a monitor that is gone, or a title bar above the top edge. + Eq(EvaluatePlacement(true, false, new Rect(2000, 100, 3000, 800), one), PlacementVerdict.OffScreen, "saved on the second monitor, which is gone: ignored"); + Eq(EvaluatePlacement(true, false, new Rect(2000, 100, 3000, 800), two), PlacementVerdict.Ok, "...but fine while that monitor exists"); + Eq(EvaluatePlacement(true, false, new Rect(-5000, -5000, -4000, -4300), two), PlacementVerdict.OffScreen, "far off every monitor: ignored"); + Eq(EvaluatePlacement(true, false, new Rect(100, -900, 1100, 200), one), PlacementVerdict.OffScreen, "title bar above the screen: ignored"); + Eq(EvaluatePlacement(true, false, new Rect(-32000, -32000, -31840, -31972), two), PlacementVerdict.TooSmall, "a minimised window's rect is refused"); + + // Sanity limits. + Eq(EvaluatePlacement(true, false, new Rect(0, 0, MinWidth - 1, 600), one), PlacementVerdict.TooSmall, "narrower than the minimum"); + Eq(EvaluatePlacement(true, false, new Rect(0, 0, 800, MinHeight - 1), one), PlacementVerdict.TooSmall, "shorter than the minimum"); + Eq(EvaluatePlacement(true, false, new Rect(0, 0, MinWidth, MinHeight), one), PlacementVerdict.Ok, "exactly the minimum is fine"); + Eq(EvaluatePlacement(true, false, new Rect(0, 0, MaxExtent + 1, 600), one), PlacementVerdict.TooLarge, "absurdly wide"); + + // Writes only when changed. + var r = new Rect(10, 20, 810, 620); + Check(ShouldWritePlacement(PlacementVerdict.Ok, r, null), "first rect is written"); + Check(!ShouldWritePlacement(PlacementVerdict.Ok, r, r), "unchanged rect: no write"); + Check(ShouldWritePlacement(PlacementVerdict.Ok, r with { Right = 900 }, r), "changed rect: written"); + Check(!ShouldWritePlacement(PlacementVerdict.OffScreen, r, null), "a refused rect is never written"); + } + + private static void PlacementFilesArePerClient() + { + Eq(ClientKey("DreamWeave", "Drakkon"), "DreamWeave/Drakkon", "key = server/character"); + Eq(ClientKey("", "Drakkon"), "Drakkon", "no server: character alone"); + Eq(ClientKey("DreamWeave", ""), (string?)null, "no character: no key"); + Eq(ClientKey(null, null), (string?)null, "nothing known: no key"); + + string a = PlacementFileName("DreamWeave/Drakkon"); + string b = PlacementFileName("DreamWeave/Drakkon1"); + string c = PlacementFileName("Aelrynth/Lucy McJuicy"); + Check(a != b && a != c && b != c, "different clients get different files"); + Eq(PlacementFileName("dreamweave/drakkon"), a, "stable (and case-insensitive) for one client"); + Eq(PlacementFileName(null), SharedFileName, "no key: the shared file"); + Eq(PlacementFileName(" "), SharedFileName, "blank key: the shared file"); + Check(a != SharedFileName && a.StartsWith("ac_window.") && a.EndsWith(".txt"), "per-client name shape: " + a); + foreach (string name in new[] { a, b, c, PlacementFileName("we/ird:na*me?<>|\"x"), PlacementFileName(new string('x', 500)) }) + { + Check(name.IndexOfAny(Path.GetInvalidFileNameChars()) < 0, "valid file name: " + name); + Check(name.Length < 90, "short file name: " + name.Length); + } + // Names that sanitise to the same letters still differ (the hash). + Check(PlacementFileName("S/a b") != PlacementFileName("S/a_b"), "'a b' and 'a_b' stay apart"); + + // The key is only usable after login; the shared file only after a long wait without one. + Check(!TryResolveKey("S", "", 1000, 90000, out _), "no character yet, just started: not ready"); + Check(TryResolveKey("S", "", 91000, 90000, out string? fallback) && fallback == null, "no character after the wait: shared file"); + Check(TryResolveKey("S", "Char", 0, 90000, out string? k) && k == "S/Char", "character known: its key at once"); + } + + private static void PlacementFileRoundTrips() + { + var r = new Rect(-1280, 40, -280, 840); + Check(TryParsePlacement(FormatPlacement(r).Split('\n'), out Rect back), "own output parses"); + Eq(back, r, "round trip (negative coordinates, secondary monitor)"); + Check(!TryParsePlacement(new[] { "left=1", "top=2", "width=0", "height=5" }, out _), "zero width: refused"); + Check(!TryParsePlacement(new[] { "width=500", "height=500" }, out _), "no position: refused"); + Check(!TryParsePlacement(new[] { "garbage", "left=x", "" }, out _), "garbage: refused"); + Check(TryParsePlacement(new[] { "# c", "LEFT = 5", "Top=6", "width=300", "height=200", "extra=1" }, out Rect loose) && loose == new Rect(5, 6, 305, 206), + "case, spaces, comments and unknown keys are tolerated"); + } + + // engine.json HoldReloadInWorld (2026-10-18, opt-in from SilentKelpie's PR 6): default off, only a true + // is written, other saves keep it, a non-boolean is ignored. HoldReloadInWorldMaxMinutes: default 10, + // clamped to 1-240, only a non-default value is written, a non-number is ignored. + private static void HoldReloadInWorldOptInAndSaved() + { + string dir = NewDir("holdreload"); + string path = Path.Combine(dir, "engine.json"); + + File.WriteAllText(path, LauncherFile); + string dump = RunChild(path, "dump").Out; + Eq(DumpValue(dump, "HoldReloadInWorld"), "False", "missing: off"); + Eq(DumpValue(dump, "HoldReloadInWorldMaxMinutes"), "10", "missing: 10 minutes"); + Eq(RunChild(path, "hook-off", "StartTooltip").Exit, 0, "save with the defaults"); + Check(!ReadJson(path).TryGetProperty("HoldReloadInWorld", out _), "off isn't written to the file"); + Check(!ReadJson(path).TryGetProperty("HoldReloadInWorldMaxMinutes", out _), "10 isn't written to the file"); + + var (exit, output) = RunChild(path, "hold-on"); + Eq(exit, 0, "turn on (" + output.Trim() + ")"); + Eq(ReadJson(path).GetProperty("HoldReloadInWorld").GetRawText(), "true", "on is saved"); + Check(ReadJson(path).TryGetProperty("LauncherWindow", out _), "launcher keys kept"); + Eq(DumpValue(RunChild(path, "dump").Out, "HoldReloadInWorld"), "True", "on read back at the next start"); + Eq(RunChild(path, "hook-off", "CheckTooltip").Exit, 0, "another save"); + Eq(ReadJson(path).GetProperty("HoldReloadInWorld").GetRawText(), "true", "on survives other saves"); + + Eq(RunChild(path, "hold-minutes", "30").Exit, 0, "set 30 minutes"); + Eq(ReadJson(path).GetProperty("HoldReloadInWorldMaxMinutes").GetRawText(), "30", "30 is saved"); + Eq(DumpValue(RunChild(path, "dump").Out, "HoldReloadInWorldMaxMinutes"), "30", "30 read back"); + Eq(RunChild(path, "hold-minutes", "10").Exit, 0, "back to 10"); + Check(!ReadJson(path).TryGetProperty("HoldReloadInWorldMaxMinutes", out _), "10 again: dropped from the file"); + + Eq(RunChild(path, "hold-off").Exit, 0, "turn off"); + Check(!ReadJson(path).TryGetProperty("HoldReloadInWorld", out _), "off again: dropped from the file"); + + foreach (string bad in new[] { "\"yes\"", "1", "null" }) + { + File.WriteAllText(path, LauncherFile.Replace("\"LoggingLevel\"", $"\"HoldReloadInWorld\": {bad}, \"LoggingLevel\"")); + Eq(DumpValue(RunChild(path, "dump").Out, "HoldReloadInWorld"), "False", $"{bad}: ignored, off"); + } + + // Hand-set minutes: in range is kept, out of range is clamped to 1-240, junk is the default. + foreach (var (json, expected) in new[] { ("1", "1"), ("240", "240"), ("0", "1"), ("-5", "1"), ("241", "240"), ("100000", "240"), ("45", "45"), ("\"x\"", "10"), ("12.5", "10"), ("null", "10") }) + { + File.WriteAllText(path, LauncherFile.Replace("\"LoggingLevel\"", $"\"HoldReloadInWorldMaxMinutes\": {json}, \"LoggingLevel\"")); + Eq(DumpValue(RunChild(path, "dump").Out, "HoldReloadInWorldMaxMinutes"), expected, $"{json}: read as {expected}"); + } + } + // /rc server names ilt add|remove (2026.10.5.46): the first edit starts from the defaults, // the edit is saved with the launcher's keys kept, and repeats, unknown, empty and overlong // patterns change nothing. diff --git a/tools/EnlCalculatorTests/EnlCalculatorTests.csproj b/tools/EnlCalculatorTests/EnlCalculatorTests.csproj new file mode 100644 index 0000000..6fe184a --- /dev/null +++ b/tools/EnlCalculatorTests/EnlCalculatorTests.csproj @@ -0,0 +1,28 @@ + + + + + Exe + net10.0 + enable + enable + true + EnlCalculatorTests + + true + + + + + + + + + diff --git a/tools/EnlCalculatorTests/Program.cs b/tools/EnlCalculatorTests/Program.cs new file mode 100644 index 0000000..1b71828 --- /dev/null +++ b/tools/EnlCalculatorTests/Program.cs @@ -0,0 +1,269 @@ +using System.Text; +using RynthCore.Engine.UI.Data; + +namespace EnlCalculatorTests; + +// Offline tests for the Enl calculator's data. See the csproj. +internal static class Program +{ + private static int _fails, _asserts; + private static void Check(bool cond, string msg) + { + _asserts++; + if (!cond) { _fails++; Console.WriteLine($" [FAIL] {msg}"); } + } + private static void Eq(T actual, T expected, string msg) => + Check(EqualityComparer.Default.Equals(actual, expected), $"{msg}: expected '{expected}', got '{actual}'"); + + private static int Main() + { + FullSample(); + OlderIltWithoutCalculator(); + NoEnlObjectAndBadPayloads(); + NullAndMistypedContainers(); + PartialAndMalformedChainRows(); + PartialAndMalformedLevelAndMaterialRows(); + UnknownFieldsAreIgnored(); + RowCap(); + ViewLimits(); + Console.WriteLine(); + Console.WriteLine(_fails == 0 ? $"PASS ({_asserts} checks)" : $"FAIL ({_fails} of {_asserts} checks failed)"); + return _fails == 0 ? 0 : 1; + } + + // What RynthILT's AppendEnlCalculatorJson emits (IltProgression.cs, RynthSuite integration/pr-fixes-2026-10-18), + // inside AppendEnlJson's "enl" object, for a character at enlightenment 298 planning to 303: + // levels 299-303 (EnlStepCost: medallions to 300, sigils from 301, Compact lum), materials from the totals, + // the 8 chain rows (only when sigils are needed), chainNote, ecoins, ecoinsLum. Property order as emitted. + private const string Sample = """ + {"available":true,"world":"InfiniteLeaftide", + "aug":{"off":false,"status":"loaded 2026-10-18 09:12","lumPerCoin":0,"rows":[],"total":"","short":"","banked":"Banked luminance: 650.00B"}, + "enl":{"off":false,"header":"Enlightenment 298 Level 275 Unassigned XP 1.20T", + "next":"Next (299): 294 Enlightenment Medallions (have 300) + 299.00B lum","enl":298,"target":303, + "plan":["589 Enlightenment Medallions","891 Enlightenment Sigils","2.41T luminance (banked 650.00B)"], + "coinsPerToken":0,"tokensShort":"", + "levels":[ + {"t":299,"item":"Medallions","count":294,"lum":"299.00B","ok":true}, + {"t":300,"item":"Medallions","count":295,"lum":"300.00B","ok":false}, + {"t":301,"item":"Sigils","count":296,"lum":"602.00B","ok":false}, + {"t":302,"item":"Sigils","count":297,"lum":"604.00B","ok":false}, + {"t":303,"item":"Sigils","count":298,"lum":"606.00B","ok":false}], + "materials":[ + {"label":"Luminance","need":"1.76T","have":"650.00B","ok":false}, + {"label":"Medallions","need":"289","have":"300","ok":false}, + {"label":"Sigils","need":"891","have":"0","ok":false}], + "chain":[ + {"label":"Ascension Coins","need":891,"have":40,"ok":false,"craft":true}, + {"label":"Lifeblood Elixirs","need":891,"have":0,"ok":false,"craft":true}, + {"label":"Lifebloom Resins","need":1782,"have":12,"ok":false,"craft":true}, + {"label":"E-coins","need":1234567,"have":1500,"ok":false,"craft":false}, + {"label":"Ancient Yalani Trinkets","need":0,"have":3,"ok":true,"craft":false}, + {"label":"Necrolytic Extracts","need":891,"have":0,"ok":false,"craft":false}, + {"label":"Life Splitters","need":0,"have":0,"ok":true,"craft":false}, + {"label":"Plants","need":1782,"have":9,"ok":false,"craft":false}], + "chainNote":"Sigil = Lifeblood Elixir + Ascension Coin. 891 to craft; Need = crafts left (in-between items) or mats to get (raw items).", + "ecoins":"E-coins needed: 1,234,567 have 1,500 (bank + pack) Ascension Coins use 851", + "ecoinsLum":"Lum to buy e-coins: ~12.35T", + "blockers":["Need 2.41T banked luminance."], + "serverChecks":"Server also checks: not in a dungeon, free pack slots (40 free), all luminance augs (past 10), society master (past 30).", + "auto":false,"armed":false,"spendFirst":true,"checkEvery":60,"status":"idle"}} + """; + + /// The sample with the enl object's body replaced (everything else of the payload stays). + private static string WithEnl(string enlBody) => + "{\"available\":true,\"world\":\"W\",\"aug\":{\"off\":false,\"status\":\"ok\",\"banked\":\"B\"},\"enl\":{" + enlBody + "}}"; + + private static EnlPlanner Enl(string enlBody) => ProgressionSource.ParseJson(WithEnl(enlBody)).Enl; + + // ── The full payload ──────────────────────────────────────────────── + + private static void FullSample() + { + ProgressionInfo info = ProgressionSource.ParseJson(Sample); + Check(info.Available, "full: available"); + Eq(info.World, "InfiniteLeaftide", "full: world"); + Eq(info.Aug.Banked, "Banked luminance: 650.00B", "full: the Augmentation planner still parses"); + EnlPlanner e = info.Enl; + Eq(e.Level, 298, "full: enl level"); Eq(e.Target, 303, "full: target"); + Eq(e.Plan.Length, 3, "full: plan lines"); Eq(e.Blockers.Length, 1, "full: blockers"); + Eq(e.CheckEvery, 60, "full: checkEvery"); Check(e.SpendFirst, "full: spendFirst"); Eq(e.Status, "idle", "full: status"); + Check(e.HasCalculator, "full: HasCalculator"); + + Eq(e.Levels.Length, 5, "full: level rows"); + Eq(e.Levels[0].Level, 299, "level 0: t"); Eq(e.Levels[0].Item, "Medallions", "level 0: item"); + Eq(e.Levels[0].Count, 294, "level 0: count"); Eq(e.Levels[0].Lum, "299.00B", "level 0: lum"); Check(e.Levels[0].Ok, "level 0: ok"); + Check(!e.Levels[1].Ok, "level 1: not ok"); Eq(e.Levels[2].Item, "Sigils", "level 2: item"); Eq(e.Levels[4].Level, 303, "level 4: t"); + Eq(e.Levels[0].LevelText, "299", "level 0: LevelText"); Eq(e.Levels[2].CountText, "296", "level 2: CountText"); + Check(ReferenceEquals(e.Levels[0].LevelText, e.Levels[0].LevelText), "level text is formatted once"); + + Eq(e.Materials.Length, 3, "full: material rows"); + Eq(e.Materials[0].Label, "Luminance", "material 0: label"); Eq(e.Materials[0].Need, "1.76T", "material 0: need"); + Eq(e.Materials[0].Have, "650.00B", "material 0: have"); Check(!e.Materials[0].Ok, "material 0: not ok"); + Eq(e.Materials[2].Label, "Sigils", "material 2: label"); Eq(e.Materials[2].Have, "0", "material 2: have"); + + Eq(e.Chain.Length, 8, "full: chain rows"); + Eq(e.Chain[0].Label, "Ascension Coins", "chain 0: label"); Eq(e.Chain[0].Need, 891L, "chain 0: need"); + Eq(e.Chain[0].Have, 40L, "chain 0: have"); Check(e.Chain[0].Craft, "chain 0: craft"); Check(!e.Chain[0].Ok, "chain 0: not ok"); + Eq(e.Chain[3].Label, "E-coins", "chain 3: label"); Eq(e.Chain[3].Need, 1234567L, "chain 3: need > a short"); + Check(!e.Chain[3].Craft, "chain 3: not craft"); Eq(e.Chain[3].NeedText, "1,234,567", "chain 3: NeedText"); Eq(e.Chain[3].HaveText, "1,500", "chain 3: HaveText"); + Eq(e.Chain[0].DisplayLabel, "Ascension Coins (craft)", "chain 0: craft rows are tagged"); Eq(e.Chain[3].DisplayLabel, "E-coins", "chain 3: raw rows are not"); + Check(e.Chain[4].Ok && !e.Chain[4].Craft, "chain 4: ok raw row"); Eq(e.Chain[7].Label, "Plants", "chain 7: label"); + Check(e.ChainNote.StartsWith("Sigil = Lifeblood Elixir", StringComparison.Ordinal), "full: chainNote"); + Check(e.Ecoins.Contains("1,234,567", StringComparison.Ordinal), "full: ecoins"); + Eq(e.EcoinsLum, "Lum to buy e-coins: ~12.35T", "full: ecoinsLum"); + } + + // ── Graceful absence ──────────────────────────────────────────────── + + private static void OlderIltWithoutCalculator() + { + // An ILT from before the calculator: the enl object has the planner fields only. + EnlPlanner e = Enl("\"off\":false,\"header\":\"H\",\"next\":\"N\",\"enl\":10,\"target\":15,\"plan\":[\"5 Enlightenment Tokens\"]," + + "\"coinsPerToken\":0,\"tokensShort\":\"\",\"blockers\":[],\"serverChecks\":\"S\",\"auto\":false,\"armed\":false," + + "\"spendFirst\":false,\"checkEvery\":60,\"status\":\"\""); + Eq(e.Levels.Length, 0, "older ILT: no levels"); Eq(e.Materials.Length, 0, "older ILT: no materials"); Eq(e.Chain.Length, 0, "older ILT: no chain"); + Eq(e.ChainNote, "", "older ILT: chainNote"); Eq(e.Ecoins, "", "older ILT: ecoins"); Eq(e.EcoinsLum, "", "older ILT: ecoinsLum"); + Check(!e.HasCalculator, "older ILT: no calculator"); + Eq(e.Header, "H", "older ILT: the planner itself still reads"); Eq(e.Plan.Length, 1, "older ILT: plan"); + + EnlPlanner empty = Enl(""); + Check(!empty.HasCalculator && empty.Levels.Length == 0 && empty.Chain.Length == 0 && empty.Materials.Length == 0, "empty enl object: nothing"); + } + + private static void NoEnlObjectAndBadPayloads() + { + ProgressionInfo noEnl = ProgressionSource.ParseJson("{\"available\":true,\"world\":\"W\"}"); + Check(noEnl.Available && !noEnl.Enl.HasCalculator, "no enl object: default planner, nothing to draw"); + + foreach (string bad in new[] { "{}", "", " ", "not json", "{\"available\":", "[1,2,3]", "null", "{\"enl\":5}", "{\"available\":\"yes\"}" }) + { + ProgressionInfo info = null!; + try { info = ProgressionSource.ParseJson(bad); } + catch (Exception ex) { Check(false, $"bad payload '{bad}' threw {ex.GetType().Name}"); continue; } + Check(info != null && !info.Available && !info.Enl.HasCalculator, $"bad payload '{bad}': empty snapshot, tab hidden"); + } + Check(!ProgressionSource.ParseJson(null).Available, "null payload: empty snapshot"); + } + + private static void NullAndMistypedContainers() + { + // null / scalar / object where an array belongs: empty array, and the sibling fields still read. + foreach (string bad in new[] { "null", "\"oops\"", "12", "true", "{\"t\":1}", "{}", "[]" }) + { + ProgressionInfo info = ProgressionSource.ParseJson(WithEnl( + $"\"header\":\"H\",\"levels\":{bad},\"materials\":{bad},\"chain\":{bad},\"chainNote\":\"note\",\"enl\":7")); + Check(info.Available, $"containers = {bad}: snapshot stays available"); + Eq(info.Enl.Levels.Length + info.Enl.Materials.Length + info.Enl.Chain.Length, 0, $"containers = {bad}: empty arrays"); + Eq(info.Enl.Header, "H", $"containers = {bad}: header before"); Eq(info.Enl.ChainNote, "note", $"containers = {bad}: chainNote after"); + Eq(info.Enl.Level, 7, $"containers = {bad}: enl after"); Eq(info.Aug.Status, "ok", $"containers = {bad}: Augmentation planner untouched"); + } + + // JSON null into a string: the UI reads .Length, so ParseJson turns it into "". + EnlPlanner e = Enl("\"chainNote\":null,\"ecoins\":null,\"ecoinsLum\":null,\"levels\":[{\"t\":1,\"ok\":true}]"); + Eq(e.ChainNote, "", "null chainNote"); Eq(e.Ecoins, "", "null ecoins"); Eq(e.EcoinsLum, "", "null ecoinsLum"); + Eq(e.Levels.Length, 1, "null strings: rows still read"); + } + + // ── Partial and malformed rows ────────────────────────────────────── + + private static void PartialAndMalformedChainRows() + { + EnlPlanner e = Enl("\"header\":\"H\",\"chain\":[" + + "{\"label\":\"Only label\"}," // 0: partial + + "{}," // 1: empty object + + "{\"label\":\"Str nums\",\"need\":\"12\",\"have\":\"1,000\",\"ok\":true}," // 2: numbers as strings + + "{\"label\":\"Bad nums\",\"need\":\"abc\",\"have\":{\"x\":[1,2]},\"ok\":\"yes\",\"craft\":1}," // 3: wrong types + + "42,\"text\",null,[1,2],true," // not objects: skipped + + "{\"label\":null,\"need\":null,\"have\":1.0e3,\"ok\":null,\"craft\":true}," // 7: nulls, a float + + "{\"label\":\"Huge\",\"need\":1e30,\"have\":-1e30}," // 8: out of range + + "{\"label\":\"Last\",\"need\":5,\"have\":2,\"ok\":false,\"craft\":true}" // 9: still read after all that + + "],\"chainNote\":\"after\",\"enl\":3"); + Eq(e.Header, "H", "chain: header before"); Eq(e.ChainNote, "after", "chain: chainNote after the rows"); Eq(e.Level, 3, "chain: enl after the rows"); + Eq(e.Chain.Length, 7, "chain: 7 object rows kept, 5 non-objects skipped"); + EnlChainRow r = e.Chain[0]; + Eq(r.Label, "Only label", "partial: label"); Eq(r.Need, 0L, "partial: need default"); Eq(r.Have, 0L, "partial: have default"); + Check(!r.Ok && !r.Craft, "partial: flags default false"); + r = e.Chain[1]; + Eq(r.Label, "", "empty row: label"); Eq(r.NeedText, "0", "empty row: need text"); + r = e.Chain[2]; + Eq(r.Need, 12L, "string number: need"); Eq(r.Have, 1000L, "string number with a separator: have"); Check(r.Ok, "string number row: ok"); + r = e.Chain[3]; + Eq(r.Label, "Bad nums", "wrong types: label"); Eq(r.Need, 0L, "wrong types: need"); Eq(r.Have, 0L, "wrong types: have"); + Check(!r.Ok && !r.Craft, "wrong types: flags default"); + r = e.Chain[4]; + Eq(r.Label, "", "nulls: label"); Eq(r.Need, 0L, "nulls: need"); Eq(r.Have, 1000L, "float have"); Check(r.Craft, "nulls: craft still read"); + r = e.Chain[5]; + Eq(r.Label, "Huge", "range: label"); Eq(r.Need, long.MaxValue, "range: need clamps"); Eq(r.Have, long.MinValue, "range: have clamps"); + r = e.Chain[6]; + Eq(r.Label, "Last", "last row: label"); Eq(r.Need, 5L, "last row: need"); Eq(r.Have, 2L, "last row: have"); + Check(!r.Ok && r.Craft, "last row: flags"); + } + + private static void PartialAndMalformedLevelAndMaterialRows() + { + EnlPlanner e = Enl("\"levels\":[{\"t\":300},{\"t\":\"301\",\"item\":5,\"count\":2.0,\"lum\":null,\"ok\":\"true\"}," + + "{\"t\":302,\"item\":\"Sigils\",\"count\":99999999999,\"lum\":\"1.00B\",\"ok\":true},{\"item\":{\"deep\":[1]},\"lum\":[]},3,null]," + + "\"materials\":[{\"label\":\"Tokens\"},{\"label\":\"Crests\",\"need\":7,\"have\":null,\"ok\":true},\"x\",{\"need\":{}}],\"enl\":1"); + Eq(e.Level, 1, "rows: enl after the arrays"); + Eq(e.Levels.Length, 4, "levels: 4 object rows"); + Eq(e.Levels[0].Level, 300, "level partial: t"); Eq(e.Levels[0].Item, "-", "level partial: item default"); Eq(e.Levels[0].Lum, "-", "level partial: lum default"); + Eq(e.Levels[0].CountText, "-", "level partial: no count shows '-'"); Check(!e.Levels[0].Ok, "level partial: not ok"); + Eq(e.Levels[1].Level, 301, "level strings: t"); Eq(e.Levels[1].Item, "5", "level number item reads as text"); Eq(e.Levels[1].Count, 2, "level float count"); + Eq(e.Levels[1].Lum, "-", "level null lum keeps '-'"); Check(!e.Levels[1].Ok, "level string 'true' is not a bool"); + Eq(e.Levels[2].Count, int.MaxValue, "level huge count clamps"); Check(e.Levels[2].Ok, "level ok"); + Eq(e.Levels[3].Level, 0, "level without t"); Eq(e.Levels[3].Item, "-", "level with object item"); Eq(e.Levels[3].Lum, "-", "level with array lum"); + Eq(e.Materials.Length, 3, "materials: 3 object rows"); + Eq(e.Materials[0].Label, "Tokens", "material partial: label"); Eq(e.Materials[0].Need, "0", "material partial: need"); Eq(e.Materials[0].Have, "0", "material partial: have"); + Eq(e.Materials[1].Need, "7", "material numeric need reads as text"); Eq(e.Materials[1].Have, "0", "material null have"); Check(e.Materials[1].Ok, "material ok"); + Eq(e.Materials[2].Label, "", "material object need: label empty"); Eq(e.Materials[2].Need, "0", "material object need: default"); + Check(e.HasCalculator, "partial rows still count as calculator data"); + } + + private static void UnknownFieldsAreIgnored() + { + ProgressionInfo info = ProgressionSource.ParseJson(""" + {"future":{"a":[1,{"b":2}]},"available":true,"world":"W","aug":{"off":false,"status":"s","newAugField":[1,2,3]}, + "enl":{"header":"H","newTop":{"x":1},"levels":[{"extra":[{"deep":true}],"t":9,"item":"Crests","count":1,"lum":"1.32T","ok":true,"more":{"k":"v"}}], + "materials":[{"label":"Crests","tier":3,"need":"4","have":"5","ok":true,"hint":null}], + "chain":[{"label":"Plants","note":"x","need":3,"have":1,"ok":false,"craft":false,"icon":{"wcid":1}}], + "chainNote":"n","ecoins":"e","ecoinsLum":"l","zzz":[[]],"enl":300,"target":310},"tail":"yes"} + """); + Check(info.Available, "unknown: available"); Eq(info.Aug.Status, "s", "unknown: aug"); + EnlPlanner e = info.Enl; + Eq(e.Header, "H", "unknown: header"); Eq(e.Level, 300, "unknown: enl after unknown fields"); Eq(e.Target, 310, "unknown: target"); + Eq(e.Levels.Length, 1, "unknown: levels"); Eq(e.Levels[0].Level, 9, "unknown: level t after an unknown array"); Eq(e.Levels[0].Item, "Crests", "unknown: level item"); + Eq(e.Levels[0].Lum, "1.32T", "unknown: level lum"); Check(e.Levels[0].Ok, "unknown: level ok (after an unknown object)"); + Eq(e.Materials.Length, 1, "unknown: materials"); Eq(e.Materials[0].Need, "4", "unknown: material need"); Eq(e.Materials[0].Have, "5", "unknown: material have"); + Eq(e.Chain.Length, 1, "unknown: chain"); Eq(e.Chain[0].Label, "Plants", "unknown: chain label"); Eq(e.Chain[0].Need, 3L, "unknown: chain need"); Eq(e.Chain[0].Have, 1L, "unknown: chain have"); + Eq(e.ChainNote, "n", "unknown: chainNote"); Eq(e.Ecoins, "e", "unknown: ecoins"); Eq(e.EcoinsLum, "l", "unknown: ecoinsLum"); + + // Case matters (the producer's names are exact): a differently cased name is an unknown field. + EnlPlanner cased = Enl("\"levels\":[{\"T\":5,\"Item\":\"X\",\"t\":6}]"); + Eq(cased.Levels[0].Level, 6, "case: only the exact name counts"); Eq(cased.Levels[0].Item, "-", "case: Item is unknown"); + } + + private static void RowCap() + { + var sb = new StringBuilder("\"levels\":["); + for (int i = 0; i < 250; i++) sb.Append(i > 0 ? "," : "").Append("{\"t\":").Append(i + 1).Append(",\"item\":\"Tokens\",\"count\":1,\"lum\":\"-\",\"ok\":true}"); + sb.Append("],\"enl\":4"); + EnlPlanner e = Enl(sb.ToString()); + Eq(e.Levels.Length, 200, "250 rows: the parse keeps the first 200"); + Eq(e.Levels[0].Level, 1, "cap: first row"); Eq(e.Levels[199].Level, 200, "cap: last kept row"); Eq(e.Level, 4, "cap: field after the array"); + + // The producer's own range, 100 level rows, comes through whole. + var hundred = new StringBuilder("\"levels\":["); + for (int i = 0; i < 100; i++) hundred.Append(i > 0 ? "," : "").Append("{\"t\":").Append(i + 299).Append('}'); + hundred.Append(']'); + Eq(Enl(hundred.ToString()).Levels.Length, 100, "100 rows (the producer's cap) all kept"); + } + + private static void ViewLimits() + { + Eq(EnlCalculatorView.VisibleLevels(0, false), 0, "view: none"); Eq(EnlCalculatorView.VisibleLevels(-3, true), 0, "view: negative"); + Eq(EnlCalculatorView.VisibleLevels(5, false), 5, "view: few rows all shown"); Eq(EnlCalculatorView.VisibleLevels(100, false), EnlCalculatorView.PreviewLevels, "view: preview limit"); + Eq(EnlCalculatorView.VisibleLevels(100, true), 100, "view: show all"); Eq(EnlCalculatorView.VisibleLevels(500, true), EnlCalculatorView.MaxLevels, "view: hard cap"); + Check(!EnlCalculatorView.CanExpand(EnlCalculatorView.PreviewLevels), "view: no toggle at the preview size"); + Check(EnlCalculatorView.CanExpand(EnlCalculatorView.PreviewLevels + 1), "view: toggle above the preview size"); + } +} diff --git a/tools/EnlCalculatorTests/Stubs.cs b/tools/EnlCalculatorTests/Stubs.cs new file mode 100644 index 0000000..8218af1 --- /dev/null +++ b/tools/EnlCalculatorTests/Stubs.cs @@ -0,0 +1,13 @@ +// The engine file ProgressionData.cs has these two dependencies; stand-ins keep the test free of the engine. +namespace RynthCore.Engine.Plugins +{ + internal static class EnlTestAnchor { } // ProgressionData.cs has "using RynthCore.Engine.Plugins;" +} + +namespace RynthCore.Engine.UI.Data +{ + internal static class PluginExportBinder + { + public static IntPtr Resolve(string pluginNamePart, string exportName) => IntPtr.Zero; + } +} diff --git a/tools/LauncherSettingsTests/LauncherSettingsTests.csproj b/tools/LauncherSettingsTests/LauncherSettingsTests.csproj index 0877752..41d9981 100644 --- a/tools/LauncherSettingsTests/LauncherSettingsTests.csproj +++ b/tools/LauncherSettingsTests/LauncherSettingsTests.csproj @@ -29,6 +29,7 @@ + diff --git a/tools/LauncherSettingsTests/Program.cs b/tools/LauncherSettingsTests/Program.cs index 104b00f..6f0ede3 100644 --- a/tools/LauncherSettingsTests/Program.cs +++ b/tools/LauncherSettingsTests/Program.cs @@ -292,6 +292,37 @@ internal static class Program CheckNoPlainText("LEAK-CHECK-PW"); }); + Scenario("known servers: picking one fills the profile, saved profiles find theirs", root, () => + { + var all = KnownServerCatalog.All; + Check(all.Count == 17, $"17 known servers (16 + ILT), got {all.Count}"); + Check(all.Select(s => s.Id).Distinct(StringComparer.OrdinalIgnoreCase).Count() == all.Count, "ids unique"); + Check(all.Select(s => s.Host).Distinct(StringComparer.OrdinalIgnoreCase).Count() == all.Count, "hosts unique"); + Check(all.All(s => s.Port is > 0 and < 65536 && s.PluginName.StartsWith("Rynth", StringComparison.Ordinal)), + "every entry has a port and a Rynth plugin"); + Check(all.Select(s => s.Name).SequenceEqual(all.Select(s => s.Name).OrderBy(n => n, StringComparer.OrdinalIgnoreCase)), + "listed by name"); + + KnownServer? reef = KnownServerCatalog.FindById("REEFCULL"); + Check(reef?.Emulator == AcEmulatorKind.Gdle, "Reefcull is GDLE (id lookup ignores case)"); + Check(KnownServerCatalog.FindById("portalstorm")?.Port == 9020, "PortalStorm uses 9020"); + + var p = new LaunchServerProfile { Id = "keep", Alias = "Main", RodatEnabled = true, Host = "x", Port = 1 }; + KnownServerCatalog.ApplyTo(KnownServerCatalog.FindById("ilt")!, p); + Check(p.Name == "Infinite Leaftide" && p.ConnectionString == "game.infiniteleaftide.online:9000" && p.Emulator == AcEmulatorKind.Ace, + "ILT fills name, host, port, emulator: " + p.ConnectionString); + Check(p.Id == "keep" && p.Alias == "Main" && p.RodatEnabled, "id, alias and Rodat kept"); + + Check(KnownServerCatalog.FindByHost("PLAY.COLDEVE.AC.")?.Id == "coldeve", "exact host (case, trailing dot)"); + Check(KnownServerCatalog.FindByHost("infiniteleaftide.online")?.Id == "ilt", "ILT's parent domain finds ILT"); + Check(KnownServerCatalog.FindByHost("aelrynth.com")?.Id == "aelrynth", "Aelrynth"); + Check(KnownServerCatalog.FindByHost("other.ddns.net") == null, "a shared dynamic-DNS domain matches nothing"); + Check(KnownServerCatalog.FindByHost("harvestbud.gdleac.com") == null, "Reefcull's shared host domain isn't Reefcull"); + Check(KnownServerCatalog.FindByHost("172.111.230.12") == null, "an IP matches only itself"); + Check(KnownServerCatalog.FindByHost("172.111.230.127")?.Id == "frostace", "FrostACE by IP"); + Check(KnownServerCatalog.FindByHost("") == null && KnownServerCatalog.FindByHost(null) == null, "empty host"); + }); + // ── First Login dialog rules (a new server: no password, no characters yet) ── Scenario("first login on a new server", root, () => { diff --git a/tools/LootAddWireTests/LootAddWireTests.csproj b/tools/LootAddWireTests/LootAddWireTests.csproj new file mode 100644 index 0000000..728c77e --- /dev/null +++ b/tools/LootAddWireTests/LootAddWireTests.csproj @@ -0,0 +1,28 @@ + + + + + Exe + net10.0-windows + x86 + win-x86 + false + x86 + enable + enable + true + LootAddWireTests + + + + + + + diff --git a/tools/LootAddWireTests/Program.cs b/tools/LootAddWireTests/Program.cs new file mode 100644 index 0000000..c5b9c98 --- /dev/null +++ b/tools/LootAddWireTests/Program.cs @@ -0,0 +1,96 @@ +using System.Reflection; +using System.Text.Json; +using System.Text.Json.Serialization.Metadata; + +namespace LootAddWireTests +{ + // The engine half of the "Add to loot profile" attribute checklist, against what RynthAi's + // LootEditWire (RynthSuite Shared/RynthCore.LootSdk/Editing) writes and reads. The JSON literals + // below are LootEditJsonContext's output / input (PascalCase, case-insensitive on read). + internal static class Program + { + private static int _fails, _asserts; + private static void Check(bool cond, string msg) + { + _asserts++; + if (!cond) { _fails++; Console.WriteLine($" [FAIL] {msg}"); } + } + + private const string Ns = "RynthCore.Engine.UI.Data."; + private const BindingFlags All = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance; + + private static int Main() + { + Assembly engine = Assembly.Load("RynthCore.Engine"); + Type ctxType = engine.GetType(Ns + "LootEditJsonContext", throwOnError: true)!; + object ctx = ctxType.GetProperty("Default", All)!.GetValue(null)!; + var stateInfo = (JsonTypeInfo)ctxType.GetProperty("LootEditStateDto", All)!.GetValue(ctx)!; + var cmdInfo = (JsonTypeInfo)ctxType.GetProperty("LootEditCmd", All)!.GetValue(ctx)!; + + Type stateType = engine.GetType(Ns + "LootEditStateDto", throwOnError: true)!; + Type draftType = engine.GetType(Ns + "LootEditItemDraftDto", throwOnError: true)!; + Type rowType = engine.GetType(Ns + "LootEditItemAttributeDto", throwOnError: true)!; + Type cmdType = engine.GetType(Ns + "LootEditCmd", throwOnError: true)!; + Type reqType = engine.GetType(Ns + "LootEditItemRequestDto", throwOnError: true)!; + Type choiceType = engine.GetType(Ns + "LootEditItemChoiceDto", throwOnError: true)!; + Type opsType = engine.GetType(Ns + "LootAttrOps", throwOnError: true)!; + + // ── RynthAi -> engine: a draft with the checklist ─────────────────────────── + const string draftJson = + "{\"ItemDraft\":{\"Seq\":7,\"ItemId\":2147483648,\"ItemName\":\"Gold Sword\",\"AttributesSupported\":true," + + "\"Attributes\":[" + + "{\"Id\":\"L:131\",\"Group\":\"Item\",\"Label\":\"Material\",\"ItemValue\":\"Gold\",\"Value\":\"Gold\",\"Op\":1,\"Ops\":[1,3],\"Editable\":false,\"On\":true,\"Tip\":\"t\"}," + + "{\"Id\":\"spell:Major Strength\",\"Group\":\"Spells\",\"Label\":\"Major Strength\",\"ItemValue\":\"Major\",\"Value\":\"Major\",\"Op\":11,\"Ops\":[10,11,12],\"Editable\":false,\"On\":false,\"Tip\":\"\"}," + + "{\"Id\":\"L:5\",\"Group\":\"Item\",\"Label\":\"Burden\",\"ItemValue\":\"8\",\"Value\":\"9\",\"Op\":2,\"Ops\":[0,1,2],\"Editable\":true,\"On\":true,\"Tip\":\"\"}]}}"; + object state = JsonSerializer.Deserialize(draftJson, stateInfo)!; + object draft = stateType.GetProperty("ItemDraft", All)!.GetValue(state)!; + Check((bool)draftType.GetProperty("AttributesSupported", All)!.GetValue(draft)!, "AttributesSupported is read"); + var rows = ((System.Collections.IEnumerable)draftType.GetProperty("Attributes", All)!.GetValue(draft)!).Cast().ToList(); + Check(rows.Count == 3, "three rows read"); + object spell = rows.First(r => (string)rowType.GetProperty("Id")!.GetValue(r)! == "spell:Major Strength"); + Check((int)rowType.GetProperty("Op")!.GetValue(spell)! == 11 && ((List)rowType.GetProperty("Ops")!.GetValue(spell)!).SequenceEqual(new[] { 10, 11, 12 }), "a spell row: op and the ops it offers"); + Check(!(bool)rowType.GetProperty("On")!.GetValue(spell)!, "a spell row is unticked"); + object burden = rows.First(r => (string)rowType.GetProperty("Id")!.GetValue(r)! == "L:5"); + Check((bool)rowType.GetProperty("Editable")!.GetValue(burden)! && (string)rowType.GetProperty("Value")!.GetValue(burden)! == "9" && (string)rowType.GetProperty("ItemValue")!.GetValue(burden)! == "8", "a numeric row: editable, the rule's value and the item's"); + + // The op codes the popup labels are the SDK's LootItemAttributeOp. + MethodInfo label = opsType.GetMethod("Label", All)!; + string L(int op) => (string)label.Invoke(null, new object[] { op })!; + Check(L(0) == ">=" && L(1) == "=" && L(2) == "<=" && L(3) == "not", "numeric / named ops label as >= = <= not"); + Check(L(10) == "exact" && L(11) == "or better" && L(12) == "any tier", "spell ops label as exact / or better / any tier"); + + // ── An older RynthAi: no checklist -> the popup keeps its T11 box ─────────── + object older = JsonSerializer.Deserialize("{\"ItemDraft\":{\"Seq\":3,\"ItemName\":\"Gold Sword\",\"IncludeT11\":true,\"IsT11\":true}}", stateInfo)!; + object olderDraft = stateType.GetProperty("ItemDraft", All)!.GetValue(older)!; + Check(!(bool)draftType.GetProperty("AttributesSupported", All)!.GetValue(olderDraft)!, "an older RynthAi: AttributesSupported is false (the T11 box shows)"); + Check(((System.Collections.ICollection)draftType.GetProperty("Attributes", All)!.GetValue(olderDraft)!).Count == 0, "and there are no rows"); + Check((bool)draftType.GetProperty("IncludeT11", All)!.GetValue(olderDraft)!, "its T11 answer is still read"); + + // ── Engine -> RynthAi: the ask ─────────────────────────────────────────────── + object choice = Activator.CreateInstance(choiceType, nonPublic: true)!; + choiceType.GetProperty("Id")!.SetValue(choice, "L:5"); + choiceType.GetProperty("On")!.SetValue(choice, true); + choiceType.GetProperty("Op")!.SetValue(choice, 2); + choiceType.GetProperty("Value")!.SetValue(choice, "9"); + object req = Activator.CreateInstance(reqType, nonPublic: true)!; + reqType.GetProperty("ItemId")!.SetValue(req, 0x80000001u); + var list = (System.Collections.IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(choiceType))!; + list.Add(choice); + reqType.GetProperty("Choices")!.SetValue(req, list); + object cmd = Activator.CreateInstance(cmdType, nonPublic: true)!; + cmdType.GetProperty("Op")!.SetValue(cmd, "item_preview"); + cmdType.GetProperty("Item")!.SetValue(cmd, req); + string cj = JsonSerializer.Serialize(cmd, cmdInfo); + Check(cj.Contains("\"Choices\":[{\"Id\":\"L:5\",\"On\":true,\"Op\":2,\"Value\":\"9\"}]"), "choices are written as RynthAi's LootEditItemChoice reads them: " + cj); + + // Until the player changes a row the ask carries none: RynthAi's own defaults (and notes) apply. + object bare = Activator.CreateInstance(reqType, nonPublic: true)!; + Check(reqType.GetProperty("Choices")!.GetValue(bare) == null, "a fresh ask has no choices"); + cmdType.GetProperty("Item")!.SetValue(cmd, bare); + Check(JsonSerializer.Serialize(cmd, cmdInfo).Contains("\"Choices\":null"), "which is written as null (an older RynthAi ignores the field)"); + + Console.WriteLine(_fails == 0 ? $"All {_asserts} checks passed." : $"{_fails} of {_asserts} checks FAILED."); + return _fails == 0 ? 0 : 1; + } + } +} diff --git a/tools/PluginManifestTests/Program.cs b/tools/PluginManifestTests/Program.cs index b16d0b8..7e743b2 100644 --- a/tools/PluginManifestTests/Program.cs +++ b/tools/PluginManifestTests/Program.cs @@ -592,10 +592,10 @@ internal static class Program Eq(RynthCore.PluginSdk.TrainingInfoFlags.Busy, RynthCore.Engine.Plugins.TrainingInfoFlags.Busy, "info flag bits"); Eq(RynthCore.PluginSdk.TrainingEntryFlags.Trainable, RynthCore.Engine.Plugins.TrainingEntryFlags.Trainable, "entry flag bits"); // The three v79 slots follow v78's, then v80's two and v81's GetMergeStackResultFn (v82-v85 follow). - var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).SkipLast(7).TakeLast(6).ToArray(); + var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).SkipLast(8).TakeLast(6).ToArray(); Check(names.SequenceEqual(new[] { "GetTrainingInfoFn", "RaiseFn", "TrainSkillFn", "GetContainerOrderFn", "PutItemInContainerFn", "GetMergeStackResultFn" }), "v79, v80 then v81 slots last: " + string.Join(",", names)); - var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SkipLast(7).TakeLast(6).ToArray(); + var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SkipLast(8).TakeLast(6).ToArray(); Check(sdkNames.SequenceEqual(names), "SDK v79, v80 and v81 slots in the same order"); } @@ -607,17 +607,19 @@ internal static class Program var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).ToArray(); var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).ToArray(); // v81's GetMergeStackResultFn follows v80's two slots. - Check(names.SkipLast(8).TakeLast(2).SequenceEqual(new[] { "GetContainerOrderFn", "PutItemInContainerFn" }), "v80 slots before v81's to v85's: " + string.Join(",", names.SkipLast(8).TakeLast(2))); - Check(sdkNames.SkipLast(8).TakeLast(2).SequenceEqual(names.SkipLast(8).TakeLast(2)), "SDK v80 slots in the same order"); - Check(names.SkipLast(6).Last() == "SalvageDirectFn", "v82 slot before v83's"); + Check(names.SkipLast(9).TakeLast(2).SequenceEqual(new[] { "GetContainerOrderFn", "PutItemInContainerFn" }), "v80 slots before v81's to v85's: " + string.Join(",", names.SkipLast(9).TakeLast(2))); + Check(sdkNames.SkipLast(9).TakeLast(2).SequenceEqual(names.SkipLast(9).TakeLast(2)), "SDK v80 slots in the same order"); + Check(names.SkipLast(7).Last() == "SalvageDirectFn", "v82 slot before v83's"); // v83: GetObjectServerAge and RemoveClientObject (ghost creatures), then v84's slot. - Check(names.SkipLast(4).TakeLast(2).SequenceEqual(new[] { "GetObjectServerAgeFn", "RemoveClientObjectFn" }), "v83 slots before v84's: " + string.Join(",", names.SkipLast(4).TakeLast(2))); + Check(names.SkipLast(5).TakeLast(2).SequenceEqual(new[] { "GetObjectServerAgeFn", "RemoveClientObjectFn" }), "v83 slots before v84's: " + string.Join(",", names.SkipLast(5).TakeLast(2))); // v84: GetObjectProperties (every property of an object, /ub propertydump), then v85's two. - Check(names.SkipLast(3).Last() == "GetObjectPropertiesFn", "v84 slot before v85's: " + names.SkipLast(3).Last()); + Check(names.SkipLast(4).Last() == "GetObjectPropertiesFn", "v84 slot before v85's: " + names.SkipLast(4).Last()); // v85: ArmConfirmation and GetLastConfirmation (the server's yes/no prompts), then v86's slot. - Check(names.SkipLast(1).TakeLast(2).SequenceEqual(new[] { "ArmConfirmationFn", "GetLastConfirmationFn" }), "v85 slots before v86's: " + string.Join(",", names.SkipLast(1).TakeLast(2))); - // v86: GetServerStateJson ends the table (which server this is, for every plugin). - Check(names.Last() == "GetServerStateJsonFn", "v86 slot last: " + names.Last()); + Check(names.SkipLast(2).TakeLast(2).SequenceEqual(new[] { "ArmConfirmationFn", "GetLastConfirmationFn" }), "v85 slots before v86's: " + string.Join(",", names.SkipLast(2).TakeLast(2))); + // v86: GetServerStateJson (which server this is, for every plugin), then v87's slot. + Check(names.SkipLast(1).Last() == "GetServerStateJsonFn", "v86 slot before v87's: " + names.SkipLast(1).Last()); + // v87: GetWieldedItems ends the table (what the player wields, from the server's messages). + Check(names.Last() == "GetWieldedItemsFn", "v87 slot last: " + names.Last()); Check(typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SequenceEqual(typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name)), "SDK table has the engine's slots in the same order"); Eq(Marshal.SizeOf(), Marshal.SizeOf(), "SDK table size = engine table size"); Eq((int)Marshal.OffsetOf("PutItemInContainerFn"), @@ -640,6 +642,8 @@ internal static class Program (int)Marshal.OffsetOf("GetLastConfirmationFn"), "GetLastConfirmationFn offset"); Eq((int)Marshal.OffsetOf("GetServerStateJsonFn"), (int)Marshal.OffsetOf("GetServerStateJsonFn"), "GetServerStateJsonFn offset"); + Eq((int)Marshal.OffsetOf("GetWieldedItemsFn"), + (int)Marshal.OffsetOf("GetWieldedItemsFn"), "GetWieldedItemsFn offset"); } private sealed class ProbePlugin : RynthCore.PluginCore.RynthPluginBase { } diff --git a/tools/ReloadInWorldGateTests/Program.cs b/tools/ReloadInWorldGateTests/Program.cs new file mode 100644 index 0000000..78cea88 --- /dev/null +++ b/tools/ReloadInWorldGateTests/Program.cs @@ -0,0 +1,274 @@ +using RynthCore.Engine; + +namespace ReloadInWorldGateTests; + +/// +/// Offline checks for ReloadInWorldGate (the opt-in hold of an automatic hot reload while the +/// player is in the world). See the csproj comment for the cases. +/// +internal static class Program +{ + private static int _checks, _failed; + private static string _case = ""; + + private static readonly TimeSpan Ten = TimeSpan.FromMinutes(10); + private static readonly DateTime T0 = new(2026, 10, 18, 9, 0, 0, DateTimeKind.Utc); + + private static int Main() + { + ShouldHoldRules(); + DefaultOffNeverHolds(); + ClearWhenNotHolding(); + WaitsUntilLeftWorld(); + ManualReloadBypassesTheHold(); + ManualReloadMidWaitReleases(); + SettingSwitchedOffMidWaitReleases(); + TimeoutGivesUpAndLogsOnce(); + TimeoutIsNotLateByAPoll(); + LeavingAtTheBoundIsStillCleared(); + ThrowingHoldNeverWedges(); + ThrowingHoldMidWaitReleases(); + MaxMinutesClamp(); + + Console.WriteLine($"{_checks} check(s), {_failed} failed."); + return _failed == 0 ? 0 : 1; + } + + private static void Check(bool ok, string what) + { + _checks++; + if (ok) return; + _failed++; + Console.WriteLine($"[FAIL] {_case}: {what}"); + } + + private static void ShouldHoldRules() + { + _case = "ShouldHold"; + Check(ReloadInWorldGate.ShouldHold(byHand: false, holdEnabled: true, inWorld: true), "automatic + in world + hold on: hold"); + Check(!ReloadInWorldGate.ShouldHold(byHand: true, holdEnabled: true, inWorld: true), "by hand + in world + hold on: never held"); + Check(!ReloadInWorldGate.ShouldHold(byHand: false, holdEnabled: true, inWorld: false), "out of world: never hold"); + Check(!ReloadInWorldGate.ShouldHold(byHand: true, holdEnabled: true, inWorld: false), "by hand + out of world: never hold"); + } + + // The default (HoldReloadInWorld off) must never hold, whatever the world state or the origin. + private static void DefaultOffNeverHolds() + { + _case = "default off"; + foreach (bool byHand in new[] { false, true }) + foreach (bool inWorld in new[] { false, true }) + Check(!ReloadInWorldGate.ShouldHold(byHand, holdEnabled: false, inWorld), $"hold off, byHand={byHand}, inWorld={inWorld}: never hold"); + + // The query EntryPoint hands to Run is ShouldHold(..., holdEnabled: false, ...): Run returns at once. + var logs = new List(); + int sleeps = 0; + var outcome = ReloadInWorldGate.Run( + stillHold: () => ReloadInWorldGate.ShouldHold(false, holdEnabled: false, inWorld: true), + log: logs.Add, + notify: _ => throw new InvalidOperationException("must not notify"), + maxWait: Ten, + waited: out TimeSpan waited, + sleep: _ => sleeps++); + Check(outcome == ReloadInWorldGate.Outcome.Clear, $"Clear (got {outcome})"); + Check(waited == TimeSpan.Zero && sleeps == 0, "no wait, no sleep"); + Check(logs.Count == 0, "no new log line"); + } + + private static void ClearWhenNotHolding() + { + _case = "clear"; + var logs = new List(); + var outcome = ReloadInWorldGate.Run( + stillHold: () => false, + log: logs.Add, + notify: null, + maxWait: Ten, + waited: out TimeSpan waited, + clock: () => T0, + sleep: _ => { }); + Check(outcome == ReloadInWorldGate.Outcome.Clear, $"Clear (got {outcome})"); + Check(waited == TimeSpan.Zero, "no wait"); + Check(logs.Count == 0, "nothing logged"); + } + + private static void WaitsUntilLeftWorld() + { + _case = "wait then clear"; + var now = T0; + int polls = 0; + var logs = new List(); + var notes = new List(); + var outcome = ReloadInWorldGate.Run( + stillHold: () => ++polls <= 5, // hold for 5 polls, then clear + log: logs.Add, + notify: notes.Add, + maxWait: Ten, + waited: out TimeSpan waited, + clock: () => now, + sleep: t => now += t, + poll: TimeSpan.FromSeconds(2), + logEvery: TimeSpan.FromSeconds(30)); + Check(outcome == ReloadInWorldGate.Outcome.ClearedAfterWait, $"ClearedAfterWait (got {outcome})"); + Check(Math.Abs(waited.TotalSeconds - 10) < 0.01, $"waited 10 s (got {waited.TotalSeconds})"); + Check(logs.Count >= 2 && logs[0].Contains("player is in the world", StringComparison.Ordinal), + $"first log names the world: {logs.FirstOrDefault()}"); + Check(logs[^1].Contains("hold released", StringComparison.Ordinal), $"last log: {logs[^1]}"); + Check(!logs.Any(l => l.Contains("reloading anyway", StringComparison.Ordinal)), "no give-up line when the player left"); + Check(notes.Count == 1 && notes[0].Contains("in the world", StringComparison.Ordinal), "chat notify once"); + } + + // A reload asked for by hand is never held: modelled the way EntryPoint wires it (the hold query is + // ShouldHold(byHand, ...)), so the gate returns Clear without a wait. + private static void ManualReloadBypassesTheHold() + { + _case = "manual bypass"; + int sleeps = 0; + var outcome = ReloadInWorldGate.Run( + stillHold: () => ReloadInWorldGate.ShouldHold(byHand: true, holdEnabled: true, inWorld: true), + log: _ => { }, + notify: null, + maxWait: Ten, + waited: out TimeSpan waited, + sleep: _ => sleeps++); + Check(outcome == ReloadInWorldGate.Outcome.Clear, $"Clear (got {outcome})"); + Check(waited == TimeSpan.Zero && sleeps == 0, "no wait"); + } + + // An automatic reload is being held, then the player presses RL / ERl: the next poll releases it. + private static void ManualReloadMidWaitReleases() + { + _case = "manual mid-wait"; + var now = T0; + bool byHand = false; + var logs = new List(); + var outcome = ReloadInWorldGate.Run( + stillHold: () => ReloadInWorldGate.ShouldHold(byHand, holdEnabled: true, inWorld: true), + log: logs.Add, + notify: null, + maxWait: Ten, + waited: out TimeSpan waited, + clock: () => now, + sleep: t => { now += t; if (now - T0 >= TimeSpan.FromSeconds(60)) byHand = true; }); + Check(outcome == ReloadInWorldGate.Outcome.ClearedAfterWait, $"ClearedAfterWait (got {outcome})"); + Check(Math.Abs(waited.TotalSeconds - 60) < 0.01, $"released at the poll after the press, 60 s (got {waited.TotalSeconds})"); + Check(!logs.Any(l => l.Contains("reloading anyway", StringComparison.Ordinal)), "not a give-up"); + } + + private static void SettingSwitchedOffMidWaitReleases() + { + _case = "setting off mid-wait"; + var now = T0; + bool enabled = true; + var outcome = ReloadInWorldGate.Run( + stillHold: () => ReloadInWorldGate.ShouldHold(false, holdEnabled: enabled, inWorld: true), + log: _ => { }, + notify: null, + maxWait: Ten, + waited: out TimeSpan waited, + clock: () => now, + sleep: t => { now += t; if (now - T0 >= TimeSpan.FromSeconds(6)) enabled = false; }); + Check(outcome == ReloadInWorldGate.Outcome.ClearedAfterWait, $"ClearedAfterWait (got {outcome})"); + Check(Math.Abs(waited.TotalSeconds - 6) < 0.01, $"released after 6 s (got {waited.TotalSeconds})"); + } + + private static void TimeoutGivesUpAndLogsOnce() + { + _case = "timeout"; + var now = T0; + int polls = 0; + var logs = new List(); + var outcome = ReloadInWorldGate.Run( + stillHold: () => { polls++; return true; }, // never leaves the world + log: logs.Add, + notify: null, + maxWait: TimeSpan.FromMinutes(3), + waited: out TimeSpan waited, + clock: () => now, + sleep: t => now += t, + poll: TimeSpan.FromSeconds(2), + logEvery: TimeSpan.FromSeconds(30)); + Check(outcome == ReloadInWorldGate.Outcome.TimedOut, $"TimedOut (got {outcome})"); + Check(Math.Abs(waited.TotalMinutes - 3) < 0.001, $"waited exactly the bound, 3 min (got {waited.TotalMinutes})"); + int gaveUp = logs.Count(l => l.Contains("reloading anyway", StringComparison.Ordinal)); + Check(gaveUp == 1, $"the give-up is logged once (got {gaveUp})"); + Check(logs[^1].Contains("held 3 min, reloading anyway", StringComparison.Ordinal), $"last log: {logs[^1]}"); + Check(logs.Count(l => l.Contains("still in the world", StringComparison.Ordinal)) >= 3, "periodic 'still in the world' lines while waiting"); + Check(polls < 200, $"bounded number of polls (got {polls})"); + } + + // The bound is not a poll late: with a 1 min bound and a 7 s poll the last sleep is shortened. + private static void TimeoutIsNotLateByAPoll() + { + _case = "timeout on time"; + var now = T0; + var outcome = ReloadInWorldGate.Run( + stillHold: () => true, + log: _ => { }, + notify: null, + maxWait: TimeSpan.FromMinutes(1), + waited: out TimeSpan waited, + clock: () => now, + sleep: t => now += t, + poll: TimeSpan.FromSeconds(7)); + Check(outcome == ReloadInWorldGate.Outcome.TimedOut, $"TimedOut (got {outcome})"); + Check(Math.Abs(waited.TotalSeconds - 60) < 0.001, $"gave up at 60 s, not 63 (got {waited.TotalSeconds})"); + } + + // Leaving the world and the bound landing on the same poll: leaving wins (the reload is not "anyway"). + private static void LeavingAtTheBoundIsStillCleared() + { + _case = "leaves at the bound"; + var now = T0; + var outcome = ReloadInWorldGate.Run( + stillHold: () => now - T0 < TimeSpan.FromMinutes(1), + log: _ => { }, + notify: null, + maxWait: TimeSpan.FromMinutes(1), + waited: out TimeSpan waited, + clock: () => now, + sleep: t => now += t, + poll: TimeSpan.FromSeconds(2)); + Check(outcome == ReloadInWorldGate.Outcome.ClearedAfterWait, $"ClearedAfterWait (got {outcome})"); + } + + private static void ThrowingHoldNeverWedges() + { + _case = "throwing stillHold"; + var outcome = ReloadInWorldGate.Run( + stillHold: () => throw new InvalidOperationException("boom"), + log: _ => { }, + notify: null, + maxWait: Ten, + waited: out TimeSpan waited, + clock: () => DateTime.UtcNow, + sleep: _ => { }); + Check(outcome == ReloadInWorldGate.Outcome.Clear, "throwing query fails open to Clear"); + Check(waited == TimeSpan.Zero, "no wait on throw"); + } + + private static void ThrowingHoldMidWaitReleases() + { + _case = "throwing mid-wait"; + var now = T0; + int calls = 0; + var outcome = ReloadInWorldGate.Run( + stillHold: () => ++calls <= 3 ? true : throw new InvalidOperationException("boom"), + log: _ => { }, + notify: null, + maxWait: Ten, + waited: out TimeSpan waited, + clock: () => now, + sleep: t => now += t); + Check(outcome == ReloadInWorldGate.Outcome.ClearedAfterWait, $"fails open to ClearedAfterWait (got {outcome})"); + } + + private static void MaxMinutesClamp() + { + _case = "max minutes"; + Check(ReloadInWorldGate.DefaultMaxMinutes == 10, "default 10"); + Check(ReloadInWorldGate.ClampMaxMinutes(10) == 10, "10 stays"); + Check(ReloadInWorldGate.ClampMaxMinutes(1) == 1 && ReloadInWorldGate.ClampMaxMinutes(240) == 240, "1 and 240 are valid"); + Check(ReloadInWorldGate.ClampMaxMinutes(0) == 1 && ReloadInWorldGate.ClampMaxMinutes(-3) == 1, "below 1 clamps to 1"); + Check(ReloadInWorldGate.ClampMaxMinutes(241) == 240 && ReloadInWorldGate.ClampMaxMinutes(int.MaxValue) == 240, "above 240 clamps to 240"); + } +} diff --git a/tools/ReloadInWorldGateTests/ReloadInWorldGateTests.csproj b/tools/ReloadInWorldGateTests/ReloadInWorldGateTests.csproj new file mode 100644 index 0000000..d1d2b69 --- /dev/null +++ b/tools/ReloadInWorldGateTests/ReloadInWorldGateTests.csproj @@ -0,0 +1,25 @@ + + + + + Exe + net10.0 + enable + enable + true + ReloadInWorldGateTests + + + + + + + diff --git a/tools/VaultedSettingTests/Program.cs b/tools/VaultedSettingTests/Program.cs new file mode 100644 index 0000000..4bfb171 --- /dev/null +++ b/tools/VaultedSettingTests/Program.cs @@ -0,0 +1,99 @@ +using System.Collections; +using System.Reflection; +using System.Text.Json; +using System.Text.Json.Serialization.Metadata; + +namespace VaultedSettingTests +{ + // Reaches RynthCore.Engine's internal settings mirror by reflection. See the csproj. + internal static class Program + { + private static int _fails, _asserts; + private static void Check(bool cond, string msg) + { + _asserts++; + if (!cond) { _fails++; Console.WriteLine($" [FAIL] {msg}"); } + } + + private const string Ns = "RynthCore.Engine.UI.Data."; + private const BindingFlags All = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance; + + private static int Main() + { + Assembly engine = Assembly.Load("RynthCore.Engine"); + Type settingsType = engine.GetType(Ns + "RynthAiSettings", throwOnError: true)!; + Type ctxType = engine.GetType(Ns + "RynthAiSettingsJsonContext", throwOnError: true)!; + Type schemaType = engine.GetType(Ns + "SettingsSchema", throwOnError: true)!; + PropertyInfo? prop = settingsType.GetProperty("EnableVaultedDungeons", All); + Check(prop != null && prop.PropertyType == typeof(bool?), "the mirror has a nullable EnableVaultedDungeons (RynthAi's payload name)"); + if (prop == null) return Finish(); + + object ctx = ctxType.GetProperty("Default", All)!.GetValue(null)!; + var info = (JsonTypeInfo)ctxType.GetProperty("RynthAiSettings", All)!.GetValue(ctx)!; + object Parse(string json) => JsonSerializer.Deserialize(json, info)!; + + // What a payload carries: nothing from an older RynthAi, the value from a newer one. + object fresh = Activator.CreateInstance(settingsType, nonPublic: true)!; + Check(prop.GetValue(fresh) == null, "a fresh mirror holds no value (nothing is claimed until RynthAi sends it)"); + Check(prop.GetValue(Parse("{\"BoostNavPriority\":true}")) == null, "an older RynthAi's payload: absent (null)"); + Check((bool?)prop.GetValue(Parse("{\"EnableVaultedDungeons\":false}")) == false, "RynthAi sends false"); + Check((bool?)prop.GetValue(Parse("{\"EnableVaultedDungeons\":true}")) == true, "RynthAi sends true"); + Check((bool?)prop.GetValue(Parse("{\"enablevaulteddungeons\":true}")) == true, "the key is matched ignoring case, like the rest"); + + // A save sends exactly what the mirror holds: unset stays null (RynthAi leaves its switch alone). + Check(JsonSerializer.Serialize(fresh, info).Contains("\"EnableVaultedDungeons\":null"), "an unset mirror saves null, never a made-up false"); + Check(JsonSerializer.Serialize(Parse("{\"EnableVaultedDungeons\":true}"), info).Contains("\"EnableVaultedDungeons\":true"), "an On mirror saves true"); + + // The schema row. + object? nav = null; + foreach (object t in (IEnumerable)schemaType.GetField("Tabs", All)!.GetValue(null)!) + if ((string)t.GetType().GetProperty("Name")!.GetValue(t)! == "Navigation") nav = t; + Check(nav != null, "a Navigation tab"); + if (nav == null) return Finish(); + + string label = (string)schemaType.GetField("VaultedDungeonsLabel", All)!.GetValue(null)!; + Check(label == "Vaulted Dungeons", "the row is called Vaulted Dungeons"); + var matches = new List(); + foreach (object r in (IEnumerable)nav.GetType().GetProperty("Rows")!.GetValue(nav)!) + if ((string?)r.GetType().GetProperty("Label")!.GetValue(r) == label) matches.Add(r); + Check(matches.Count == 1, "exactly one Vaulted Dungeons row, under Navigation"); + if (matches.Count != 1) return Finish(); + + object row = matches[0]; + Type rt = row.GetType(); + Check(rt.GetProperty("Kind")!.GetValue(row)!.ToString() == "Bool", "a checkbox"); + var get = (Delegate)rt.GetProperty("Get")!.GetValue(row)!; + var set = (Delegate)rt.GetProperty("Set")!.GetValue(row)!; + MethodInfo visible = rt.GetMethod("IsVisible")!; + string tip = (string?)rt.GetProperty("Tooltip")!.GetValue(row) ?? ""; + Check(tip.Contains("Off by default") && tip.Contains("Infinite Leaftide"), "the tooltip says it is the master switch, off by default, ILT only"); + Check(tip.Contains("do NOT"), "and warns that pet/fellow kills don't restart the Kill Client timer"); + + object unset = Activator.CreateInstance(settingsType, nonPublic: true)!; + Check(!(bool)visible.Invoke(row, new[] { unset })!, "hidden while RynthAi hasn't sent the value (an older RynthAi)"); + Check((double)get.DynamicInvoke(unset)! == 0, "an unset mirror reads Off"); + + object off = Parse("{\"EnableVaultedDungeons\":false}"); + Check((bool)visible.Invoke(row, new[] { off })!, "shown once RynthAi sends it"); + Check((double)get.DynamicInvoke(off)! == 0, "reads Off by default"); + set.DynamicInvoke(off, 1.0); + Check((bool?)prop.GetValue(off) == true, "ticking it sets EnableVaultedDungeons to true"); + Check((double)get.DynamicInvoke(off)! == 1, "and it reads On"); + set.DynamicInvoke(off, 0.0); + Check((bool?)prop.GetValue(off) == false, "unticking sets false (not null)"); + + // Ticking it changes nothing else in the payload. + object before = Parse("{\"BoostNavPriority\":true,\"EnableVaultedDungeons\":false}"); + set.DynamicInvoke(before, 1.0); + string after = JsonSerializer.Serialize(before, info); + Check(after.Contains("\"BoostNavPriority\":true") && after.Contains("\"EnableVaultedDungeons\":true"), "the other settings ride along unchanged"); + return Finish(); + } + + private static int Finish() + { + Console.WriteLine(_fails == 0 ? $"All {_asserts} checks passed." : $"{_fails} of {_asserts} checks FAILED."); + return _fails == 0 ? 0 : 1; + } + } +} diff --git a/tools/VaultedSettingTests/VaultedSettingTests.csproj b/tools/VaultedSettingTests/VaultedSettingTests.csproj new file mode 100644 index 0000000..6c5d528 --- /dev/null +++ b/tools/VaultedSettingTests/VaultedSettingTests.csproj @@ -0,0 +1,31 @@ + + + + + Exe + net10.0-windows + x86 + win-x86 + false + x86 + enable + enable + true + VaultedSettingTests + + + + + + +