From e3222805cb6d7f7ce404919a9ce63304fa545f1c Mon Sep 17 00:00:00 2001 From: BlankenshipG Date: Wed, 14 Oct 2026 00:51:23 -0400 Subject: [PATCH] feat: SK engine work through 2026-10-13 on 2026.10.13.3 Plugin API v86 after rynth's v84 GetObjectProperties: v85 confirmation answers (ArmConfirmation, GetLastConfirmation), v86 GetServerStateJson. - One plugin per server, server verdicts, per-character overrides and a server picker; skipped server plugins are listed and load when forced On. - Mini Remote sections and the sections rail; Session Stats; Char menu Fellowship and quests; known-server picker in the launcher. - Items damage-type colors, one Progression Attributes section, environment-hit throttle and per-monster attack power settings. - Security review fixes (SafeImGui, chat-origin checks, StatusAgent 1.0.1). See Changelog/2026-10-14-sk-engine-work-through-10-13.md. --- ...2026-10-14-sk-engine-work-through-10-13.md | 80 +++ docs/ACCLIENT_HOOK_INVENTORY.md | 91 +++ .../RynthCore.App.Avalonia.csproj | 1 + .../ServerProfileDialog.axaml | 7 +- .../ServerProfileDialog.axaml.cs | 45 ++ src/RynthCore.App/KnownServerCatalog.cs | 159 +++++ .../Compatibility/ChatCallbackHooks.cs | 7 +- .../Compatibility/ClientHelperHooks.cs | 3 + .../Compatibility/ClientObjectHooks.cs | 3 +- .../Compatibility/ConfirmationResponder.cs | 203 +++++++ .../Compatibility/EngineStatusMetrics.cs | 75 ++- src/RynthCore.Engine/Compatibility/IltInfo.cs | 53 +- .../Compatibility/RynthCoreChatCommands.cs | 229 +++++++- .../Compatibility/ServerInfo.cs | 49 +- .../Compatibility/SessionRates.cs | 160 ++++++ .../Compatibility/SmartBoxHooks.cs | 10 + src/RynthCore.Engine/EntryPoint.cs | 53 +- src/RynthCore.Engine/Hooking/MinHook.cs | 15 +- .../ImGui/EngineFrameController.cs | 4 + src/RynthCore.Engine/ImGui/ImGuiBar.cs | 13 +- src/RynthCore.Engine/ImGui/ImGuiFontTest.cs | 4 +- src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs | 150 ++++- .../ImGui/MonsterHud/MonsterHudSettingsUi.cs | 4 +- .../ImGui/MonsterHud/PlayerPlate.cs | 2 +- .../ImGui/Panels/BountiesFace.cs | 4 +- .../ImGui/Panels/CharactersFace.cs | 10 +- src/RynthCore.Engine/ImGui/Panels/ChatFace.cs | 8 +- .../ImGui/Panels/ChatFiltersFace.cs | 8 +- .../ImGui/Panels/DamageDetailFace.cs | 45 +- .../ImGui/Panels/DamageFace.cs | 36 +- .../ImGui/Panels/DamageTypeColors.cs | 32 ++ .../ImGui/Panels/DashboardDrawers.cs | 4 +- .../ImGui/Panels/DungeonMapFace.cs | 2 +- .../ImGui/Panels/HotkeysSettingsUi.cs | 14 +- .../ImGui/Panels/InventoryFace.AttrFilter.cs | 6 +- .../ImGui/Panels/InventoryFace.Classic.cs | 8 +- .../ImGui/Panels/InventoryFace.MultiSelect.cs | 6 +- .../ImGui/Panels/InventoryFace.cs | 6 +- .../ImGui/Panels/ItemCountFace.cs | 4 +- .../ImGui/Panels/ItemsFace.cs | 17 +- .../ImGui/Panels/LootAddDialog.cs | 12 +- .../ImGui/Panels/LootEditorFace.cs | 28 +- src/RynthCore.Engine/ImGui/Panels/LuaFace.cs | 18 +- .../ImGui/Panels/MetaFace.Editor.cs | 14 +- .../ImGui/Panels/MetaFace.List.cs | 22 +- .../ImGui/Panels/MetaFace.Schedule.cs | 16 +- src/RynthCore.Engine/ImGui/Panels/MetaFace.cs | 8 +- .../ImGui/Panels/MiniRemoteFace.Sections.cs | 542 ++++++++++++++++++ .../ImGui/Panels/MiniRemoteFace.cs | 102 +++- src/RynthCore.Engine/ImGui/Panels/NavFace.cs | 6 +- src/RynthCore.Engine/ImGui/Panels/P1Faces.cs | 6 +- .../ImGui/Panels/RadarFace.cs | 6 +- .../ImGui/Panels/RangesSlideOut.cs | 12 +- .../ImGui/Panels/ReportFace.cs | 2 +- .../ImGui/Panels/RynthAiFace.Drawers.cs | 14 +- .../ImGui/Panels/RynthAiFace.cs | 114 ++-- .../ImGui/Panels/RynthNavArrowFace.cs | 12 +- .../ImGui/Panels/RynthNavFace.cs | 34 +- .../ImGui/Panels/SenseFace.cs | 2 +- .../ImGui/Panels/ServerPickSettingsUi.cs | 126 ++++ .../ImGui/Panels/SettingsFace.cs | 11 +- .../ImGui/Panels/SkillsFace.Progression.cs | 203 ++++--- .../ImGui/Panels/SkillsFace.cs | 18 +- .../ImGui/Panels/VisionFace.cs | 4 +- src/RynthCore.Engine/ImGui/RynthCoreShell.cs | 84 +-- src/RynthCore.Engine/ImGui/SafeImGui.cs | 44 ++ src/RynthCore.Engine/Net/AelrynthVaultWire.cs | 26 +- src/RynthCore.Engine/Net/ChatOrigin.cs | 54 ++ .../Plugins/EngineSettings.cs | 54 +- src/RynthCore.Engine/Plugins/LoadedPlugin.cs | 8 + .../Plugins/PluginContract.cs | 31 + .../Plugins/PluginContractVersion.cs | 5 +- src/RynthCore.Engine/Plugins/PluginLoader.cs | 1 + .../Plugins/PluginManager.ServerPlugins.cs | 153 +++++ src/RynthCore.Engine/Plugins/PluginManager.cs | 276 ++++++--- .../Plugins/PluginManifestGate.cs | 69 ++- src/RynthCore.Engine/RynthLog.cs | 11 + src/RynthCore.Engine/UI/Data/DamageData.cs | 14 +- src/RynthCore.Engine/UI/Data/SettingsData.cs | 62 +- .../UI/Panels/MonstersPanel.cs | 5 + .../UI/Panels/RynthAiPanel.cs | 18 +- .../UI/Panels/SettingsPanel.cs | 14 + .../UI/ScriptWindows/ScriptWindowRegistry.cs | 32 ++ .../UI/Sections/NotLoadedServers.cs | 48 ++ .../UI/Sections/SectionCatalog.cs | 226 ++++++++ .../UI/Sections/SectionManifest.cs | 253 ++++++++ .../UI/Sections/SectionRegistry.cs | 277 +++++++++ .../UI/Sections/ServerForce.cs | 134 +++++ .../UI/Sections/ServerForceStore.cs | 160 ++++++ .../UI/Sections/ServerSelection.cs | 131 +++++ .../UI/Sections/ServerSelectionStore.cs | 53 ++ .../UI/Sections/ServerStateJson.cs | 89 +++ src/RynthCore.Engine/UI/ServerMenus.cs | 340 ++++++----- .../Manifest/RynthPluginManifest.cs | 126 ++++ src/RynthCore.PluginSdk/RynthCoreApiNative.cs | 5 + src/RynthCore.PluginSdk/RynthCoreHost.cs | 89 +++ .../build/RynthCore.PluginSdk.targets | 50 +- src/RynthCore.StatusAgent/AgentConfig.cs | 5 +- .../LocalStatusServer.cs | 69 ++- src/RynthCore.StatusAgent/Program.cs | 13 + .../RynthCore.StatusAgent.csproj | 3 +- src/RynthCore.StatusAgent/ServeGuard.cs | 155 +++++ .../EngineSettingsTests.csproj | 3 + tools/EngineSettingsTests/Program.cs | 30 + .../LauncherSettingsTests.csproj | 1 + tools/LauncherSettingsTests/Program.cs | 31 + tools/NetMessageTests/NetMessageTests.csproj | 1 + tools/NetMessageTests/VaultWireTests.cs | 12 + tools/PluginManifestTests/Program.cs | 160 +++++- tools/SectionsTests/Program.cs | 515 +++++++++++++++++ tools/SectionsTests/SectionsTests.csproj | 37 ++ tools/StatusAgentTests/Program.cs | 48 ++ .../StatusAgentTests/StatusAgentTests.csproj | 1 + 113 files changed, 6218 insertions(+), 770 deletions(-) create mode 100644 Changelog/2026-10-14-sk-engine-work-through-10-13.md create mode 100644 docs/ACCLIENT_HOOK_INVENTORY.md create mode 100644 src/RynthCore.App/KnownServerCatalog.cs create mode 100644 src/RynthCore.Engine/Compatibility/ConfirmationResponder.cs create mode 100644 src/RynthCore.Engine/Compatibility/SessionRates.cs create mode 100644 src/RynthCore.Engine/ImGui/Panels/DamageTypeColors.cs create mode 100644 src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.Sections.cs create mode 100644 src/RynthCore.Engine/ImGui/Panels/ServerPickSettingsUi.cs create mode 100644 src/RynthCore.Engine/ImGui/SafeImGui.cs create mode 100644 src/RynthCore.Engine/Net/ChatOrigin.cs create mode 100644 src/RynthCore.Engine/Plugins/PluginManager.ServerPlugins.cs create mode 100644 src/RynthCore.Engine/UI/Sections/NotLoadedServers.cs create mode 100644 src/RynthCore.Engine/UI/Sections/SectionCatalog.cs create mode 100644 src/RynthCore.Engine/UI/Sections/SectionManifest.cs create mode 100644 src/RynthCore.Engine/UI/Sections/SectionRegistry.cs create mode 100644 src/RynthCore.Engine/UI/Sections/ServerForce.cs create mode 100644 src/RynthCore.Engine/UI/Sections/ServerForceStore.cs create mode 100644 src/RynthCore.Engine/UI/Sections/ServerSelection.cs create mode 100644 src/RynthCore.Engine/UI/Sections/ServerSelectionStore.cs create mode 100644 src/RynthCore.Engine/UI/Sections/ServerStateJson.cs create mode 100644 src/RynthCore.StatusAgent/ServeGuard.cs create mode 100644 tools/SectionsTests/Program.cs create mode 100644 tools/SectionsTests/SectionsTests.csproj diff --git a/Changelog/2026-10-14-sk-engine-work-through-10-13.md b/Changelog/2026-10-14-sk-engine-work-through-10-13.md new file mode 100644 index 0000000..7305841 --- /dev/null +++ b/Changelog/2026-10-14-sk-engine-work-through-10-13.md @@ -0,0 +1,80 @@ +# SK engine and UI work through 2026-10-13, on 2026.10.13.3 + +Everything from SK's build since the 2026-10-11 batch that main doesn't have yet, merged onto +release 2026.10.13.3 with the conflicts resolved. Goes with RynthSuite's +`Changelog/2026-10-14-sk-rynthai-work-through-10-13.md`. + +Left out on purpose: SK's local installer scripts and release records, `.github` and +`.gitignore` edits for SK's fork, `BUILD.md` notes about SK's release script, and the +per-release changelogs (this file sums them up). + +## Merge notes for 2026.10.13.3 + +- **Plugin API v86.** 2026.10.13.3 took v84 for `GetObjectProperties`, so SK's additions follow it: + - v85: `ArmConfirmationFn`, `GetLastConfirmationFn` (craft-chance and other confirmation prompts); + - v86: `GetServerStateJsonFn` (the engine's server verdicts for plugins). +- `PluginContractVersion.Current` and `RynthCoreSdkApiVersion` are 86. In the SDK, + `HasConfirmationAnswers` needs v85+ and `HasGetServerStateJson` v86+. +- `tools/PluginManifestTests` checks the slot order (`GetObjectProperties` before `ArmConfirmation`). +- Plugins built against an older SK SDK must be rebuilt. + +## Confirmation answers (v85) + +- `Compatibility/ConfirmationResponder.cs` (new) binds `CM_Character::Event_ConfirmationResponse` + by byte pattern. `SmartBoxHooks` hands each ConfirmationRequest (game event 0x0274) to it. +- A plugin arms one answer (`ArmConfirmation`); the next matching prompt is answered and the result + is readable with `GetLastConfirmation`. Unarmed prompts go to the client as before. +- Char menu > Crafting opens RynthAi's Crafting tab. + +## One plugin per server, server verdicts (v86) + +- **Server plugins.** A plugin's manifest can name a server (id, hosts, world names). + `PluginManifestGate.SelectServerPlugins` loads only the matching server's plugin; with no match + every server plugin loads (fail-open). +- **Server verdicts.** The engine decides which servers are active (built-in ILT and Aelrynth, plus + every server a plugin declares) and exports them as JSON through `GetServerStateJson`. +- **Per-character override.** `ServerForce` / `ServerForceStore` save Auto, On or Off per + character; `/rc server auto|on|off` and a server picker in Options > Diagnostics set it. +- **Diagnostics server list.** `ServerMenus.Tick` runs every frame, bar or rail, so the list fills + in and each server plugin gets its "servermenu" verdict. Server plugins the gate skipped are + listed as "installed but not loaded"; forcing one On loads only that plugin on the pump thread + (`PluginManager.ServerPlugins.cs`, `UI/Sections/NotLoadedServers.cs`). +- **Launcher.** The Server Profile dialog has a known-server picker + (`src/RynthCore.App/KnownServerCatalog.cs`). +- `IltInfo.Refresh` logs its verdict at Info once per world (`RynthLog.Milestone`). + +## Mini Remote sections + +- `SectionRegistry`, `SectionCatalog` and the sections rail: each section draws the engine panels + that belong to it as tabs, then one collapsing group per active server. Plugins add sections + through `RynthPluginGetSectionsJson`. +- With the rail hidden, the plugin tabs come back in RynthAi's tab bar. +- "Char" is now "Session Stats" (the id stays `char`). Character and Charms moved to RynthOracle, + Banking to RynthInventory's Global Inventory. +- Char menu: Fellowship, and the quests open RynthOracle. The separate Hub launcher is removed + (the Mini Remote button, `/rc miniremote` and Char > Mini Remote open the same window). + +## Panels and settings + +- **Items panel:** weapons colored by damage type (UB-ILT palette, `DamageTypeColors`). +- **Progression:** one Attributes section; Infinite Leaftide's infinite attributes appear under the + retail XP costs when RynthILT reports them. +- **Settings and Damage panel:** environment-hit throttle for missile and magic (move closer, new + target or off) and per-monster attack power (High, Reckless, Variable, Reckless + Variable, with + `VariablePowerMin` / `VariablePowerMax`). +- **Session stats:** the luminance total behind luminance per hour is in the status JSON + (`luminanceSession`, additive). + +## Security review fixes + +- **A `%` in shown text could crash the client.** `ImGui/SafeImGui.cs` doubles every `%` before + ImGui formats it; 246 calls in 39 engine files use it. +- **Spoofed server replies.** The engine's own `/mastery-data` and `/mule-data` readers skip player + chat types (`Net/ChatOrigin.cs`), and the vault wire needs its marker at the start of the line. +- **StatusAgent 1.0.1:** hardening of the status server before it is opened to other PCs. + +## Tests + +- `tools/PluginManifestTests` (236 assertions), `tools/SectionsTests` (148 checks), + `tools/ObjectPropertyTests`, `EngineSettingsTests`, `LauncherSettingsTests`, `NetMessageTests`, + `StatusAgentTests`: all pass on this commit. diff --git a/docs/ACCLIENT_HOOK_INVENTORY.md b/docs/ACCLIENT_HOOK_INVENTORY.md new file mode 100644 index 0000000..0251747 --- /dev/null +++ b/docs/ACCLIENT_HOOK_INVENTORY.md @@ -0,0 +1,91 @@ +# ACClient Hook Inventory + +This file tracks RynthCore hook targets against the user's real AC client binary, with the AC client decompile used for semantics and the live binary used as the source of truth for hook placement. + +## Client Fingerprint + +- Path: `C:\Turbine\Asheron's Call\acclient.exe` +- File size: `4,841,472` bytes +- SHA256: `BCA95BBEBED4B9ED1FF09D0DA83144E2FC4208F63AD7ADA5CB47C3CA207CCBA9` +- PE machine: `0x014C` (`x86`) +- PE image size: `0x0056D000` + +## Rules For This Inventory + +- Use the decompile to understand semantics, call order, and callback behavior. +- Use the live `acclient.exe` to derive patterns, validate uniqueness, and choose the real hook address. +- Do not ship fixed RVAs from the decompile unless they have been validated against the live binary. +- Prefer hooking the AC client function that already implements the desired behavior over lower-level memory access. +- Every production hook should eventually have: + - a primary binary pattern + - at least one fallback pattern or alternate seam when practical + - runtime validation + - an explicit unsupported-state log/UI message + +## Priority Inventory + +### Lifecycle And UI + +| Surface | Decompiled seam | Actual-binary plan for this client | Status | Priority | +| --- | --- | --- | --- | --- | +| `OnLoginComplete` | `CPlayerSystem::SendLoginCompleteNotification` in `CPlayerSystem.cpp:4017-4031` | Pattern-scan the containing function using the unique `SetDisplayInventory(1)` plus `BroadcastGlobalMessage(..., 0xB, 0)` sequence, then hook the containing `thiscall` function. | Live in RynthCore | P0 | +| `OnUIInitialized` | `ClientUISystem::OnStartup` in `ClientUISystem.cpp:48` and `APIManager::SetUIReady(1)` in `APIManager.cpp:134` | Hook the tiny `OnStartup -> SetUIReady(1)` wrapper or the `SetUIReady(1)` transition path. Prefer the wrapper if the pattern is unique in the live binary. | Not implemented | P0 | +| `OnBusyCountIncremented` | `ClientUISystem::IncrementBusyCount` in `ClientUISystem.cpp:630` | Hook the wrapper that increments `m_cBusy` and updates cursor state when crossing `0 -> 1`. | Not implemented | P1 | +| `OnBusyCountDecremented` | `ClientUISystem::DecrementBusyCount` in `ClientUISystem.cpp:641` | Hook the wrapper that decrements `m_cBusy` and updates cursor state when crossing `1 -> 0`. | Not implemented | P1 | + +### Chat And Command + +| Surface | Decompiled seam | Actual-binary plan for this client | Status | Priority | +| --- | --- | --- | --- | --- | +| `OnChatWindowText` | `ClientSystem.cpp:108` | Hook the function that allocates a BSTR from `i_text`, calls `GetACPlugin()->OnChatWindowText`, then checks `bEat` before continuing UI output. | Ready for binary patterning | P0 | +| `OnChatBarEnter` | `ClientCommunicationSystem.cpp:14407` | Hook the function that allocates a BSTR from the entered line, calls `GetACPlugin()->OnChatBarEnter`, and returns early when the plugin consumes the line. | Ready for binary patterning | P0 | + +### World, Target, And Object Flow + +| Surface | Decompiled seam | Actual-binary plan for this client | Status | Priority | +| --- | --- | --- | --- | --- | +| `OnDeleteObject` | `ACCObjectMaint::DeleteObject` in `ACCObjectMaint.cpp:73-85` | Hook the clean wrapper that checks `APIIsReady`, calls `OnDeleteObject`, then calls `ACCWeenieObject::SetCorpseDeleted` and `CObjectMaint::DeleteObject`. | Ready for binary patterning | P0 | +| `OnSelectedTargetChange` | `ACCWeenieObject.cpp:710` and `ACCWeenieObject.cpp:1997` | Hook the selected-target setter path after `CM_UI::SendNotice_SelectionChanged` and before the direct plugin callback. | Ready for binary patterning | P0 | +| World/object dispatch | `ACSmartBox::DispatchSmartBoxEvent` in `ACSmartBox.cpp:37-171` | Hook the SmartBox dispatch seam as the high-value world/object/network filter layer. This is the likely replacement for many WorldFilter-style surfaces. | Ready for binary patterning | P0 | +| Object creation | `ACCObjectMaint::CreateObject` in `ACCObjectMaint.cpp:196` | Hook the object creation wrapper for higher-level object lifecycle callbacks when we need richer data than a raw SmartBox event. | Ready for binary patterning | P1 | +| Object inventory updates | `ACCObjectMaint::UpdateObjectInventory` in `ACCObjectMaint.cpp:377` | Hook the inventory update path for container/item-change compatibility events. | Ready for binary patterning | P1 | +| Update/create/delete server dispatch | `CM_Physics::DispatchSB_CreateObject`, `DispatchSB_UpdateObject`, `DispatchSB_DeleteObject` in `CM_Physics.cpp` | Use as fallback seams if the outer SmartBox dispatcher proves too broad or unstable. | Decompile-confirmed | P1 | + +### Combat And Trade + +| Surface | Decompiled seam | Actual-binary plan for this client | Status | Priority | +| --- | --- | --- | --- | --- | +| `OnCombatModeChange` | `ClientCombatSystem.cpp:1564` | Hook the branch that invokes the plugin callback after the combat mode change resolves and auto-targeting logic runs. | Ready for binary patterning | P1 | +| Trade window opened | `ClientTradeSystem.cpp:525` | Hook `Handle_Trade__Recv_RegisterTrade` after `CM_Trade::SendNotice_RegisterTrade` and before the internal attempt-to-trade follow-up. | Ready for binary patterning | P1 | +| Trade item added | `ClientTradeSystem::Handle_Trade__Recv_AddToTrade` in `ClientTradeSystem.cpp:560+` | Hook the direct wrapper that calls `CM_Trade::SendNotice_AddItemToTrade` and then `OnTradeWindowItemAdded`. | Ready for binary patterning | P1 | +| Trade completed | `ClientCommunicationSystem.cpp:3106` | Hook the message-switch case for `0x529` (`Trade Complete!`) that directly invokes `OnTradeCompleted`. | Ready for binary patterning | P1 | +| Trade accept/decline/close/clear | `ClientTradeSystem.cpp` | Hook the direct trade-system wrappers that invoke the corresponding plugin callback. | Decompiled seam confirmed, binary anchor still needed | P1 | + +## Host Call Surface To Expose Through RynthCore + +These are not plugin callback hooks, but they are part of the host API surface we should expose once the callback layer is in place. + +| API surface | Decompiled seam | Notes | Priority | +| --- | --- | --- | --- | +| `WriteToChat` | `APIManager__IAsheronsCallImpl.cpp` | Safe early host helper. | P0 | +| Selection get/set | `APIManager__IAsheronsCallImpl.cpp` | Pairs naturally with target-change callbacks. | P0 | +| `UseObject`, `UseObjectOn`, `UseEquippedItem` | `APIManager__IAsheronsCallImpl.cpp` | Good interaction helpers once lifecycle is stable. | P1 | +| `MoveItemExternal`, `MoveItemInternal` | `APIManager__IAsheronsCallImpl.cpp` | Useful once inventory callbacks exist. | P1 | +| `IsStandingStill`, `StopCompletely`, `TurnToHeading`, `SetAutoRun` | `APIManager__IAsheronsCallImpl.cpp` | Movement helper layer. Some of this already overlaps with existing RynthCore action hooks. | P0 | +| `GetCurCoords`, `GetPlayerID`, `GetGroundContainerID` | `APIManager__IAsheronsCallImpl.cpp` | Good basic state helpers. | P0 | +| `GetScreenDimensions`, `ItemIsKnown`, `GetItemName` | `APIManager__IAsheronsCallImpl.cpp` | Low-risk host helpers. | P1 | +| `IssueChatBarCommand` | `APIManager__IAsheronsCallImpl.cpp` | Treat as stub-like until runtime behavior is validated against the live client. | Hold | +| `GetCombatMode`, `GetBusyCount`, salvage panel APIs | `APIManager__IAsheronsCallImpl_vtbl.cpp` | Declared but not yet fully validated in the split. | Hold | + +## Implementation Waves + +1. Finish lifecycle/UI: `OnLoginComplete`, `OnUIInitialized`, busy count. +2. Add chat interception: `OnChatWindowText`, `OnChatBarEnter`. +3. Add world/object seams: SmartBox dispatch, delete/create/inventory, selected target. +4. Add combat/trade callbacks. +5. Expose the confirmed `IAsheronsCall` subset through RynthCore-native host APIs. + +## Notes + +- The split decompile is still very useful, but the login-complete work already showed that its function RVAs do not always line up with the user's live client binary. +- For this reason, future hook work should be tracked here first against the fingerprint above, then implemented in RynthCore with pattern scanning rather than fixed addresses. diff --git a/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj b/src/RynthCore.App.Avalonia/RynthCore.App.Avalonia.csproj index 348493a..1f697ae 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..69e59e8 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 and have a RynthSuite server plugin." + : $"{server.Note} Server plugin: {server.PluginName} (RynthCore loads it when you connect to {server.Host})."; + } + 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..ea57940 --- /dev/null +++ b/src/RynthCore.App/KnownServerCatalog.cs @@ -0,0 +1,159 @@ +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. Each Host must stay inside the matching plugin's +/// RynthPluginServerHosts, or RynthCore's load gate won't pick the plugin for it +/// (RynthServerPack.Tests checks this). +/// +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/ChatCallbackHooks.cs b/src/RynthCore.Engine/Compatibility/ChatCallbackHooks.cs index ddea408..8745129 100644 --- a/src/RynthCore.Engine/Compatibility/ChatCallbackHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ChatCallbackHooks.cs @@ -308,7 +308,7 @@ internal static class ChatCallbackHooks // Not inside our own reprint of a held line: that line was already offered here when // it first arrived (and wasn't ours, or it wouldn't have been held), so offering it // again could take a stale line for the answer to a request sent since. - if (line != null && _replayDepth == 0 && EatOwnReply(line)) + if (line != null && _replayDepth == 0 && EatOwnReply(line, chatType)) return 0; // 2. Hold the line until the plugins have heard it (IncomingChatHold.cs): AC prints it @@ -349,8 +349,11 @@ internal static class ChatCallbackHooks } [MethodImpl(MethodImplOptions.NoInlining)] - private static bool EatOwnReply(string line) + private static bool EatOwnReply(string line, uint chatType) { + // Server replies only: a line in a player's chat type is someone typing "~ael1 ..." or + // "Unknown command: ..." to feed the readers or hide their own chat. + if (Net.ChatOrigin.IsPlayerAuthored(chatType)) return false; try { return MasteryFeed.OnIncomingLine(line) || VaultFeed.OnIncomingLine(line); } catch { return false; } } diff --git a/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs b/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs index dfc31f1..5a30405 100644 --- a/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ClientHelperHooks.cs @@ -374,6 +374,9 @@ internal static class ClientHelperHooks // Skills panel raises (CM_Train senders). try { PlayerTraining.Probe(text); } catch (Exception ex) { RynthLog.Compat($"Compat: raise senders binding failed - {ex.Message}"); } + // v81 confirmation answers (CM_Character::Event_ConfirmationResponse). + try { ConfirmationResponder.Probe(text); } + catch (Exception ex) { RynthLog.Compat($"Compat: confirmation response binding failed - {ex.Message}"); } _initialized = true; _statusMessage = "Ready."; RynthLog.Verbose("Compat: helper hooks ready - validated select/state/chat helpers plus mapped interaction and inventory helpers."); diff --git a/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs b/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs index 8151693..d5ad21a 100644 --- a/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs +++ b/src/RynthCore.Engine/Compatibility/ClientObjectHooks.cs @@ -169,7 +169,8 @@ internal static class ClientObjectHooks // 1 TotalExperience, 2 AvailableExperience, 6 AvailableLuminance, 7 MaximumLuminance, then // Aelrynth's Bank session totals (custom ids, absent on other servers): 9101 Radiance earned, // 9102 Luminance auto-banked, 9103 Luminance drawn from the bank. RynthTracker reads them. - private static readonly uint[] PlayerQuadStypes = { 1u, 2u, 6u, 7u, 9101u, 9102u, 9103u }; + // 9005 is ACECustom's banked luminance (the session rates count its rises as income). + private static readonly uint[] PlayerQuadStypes = { 1u, 2u, 6u, 7u, 9005u, 9101u, 9102u, 9103u }; private static readonly Dictionary _cachedPlayerQuad = new(); // Secondary attributes (vitals) by stype 1..6 from InqAttribute2ndBaseLevel: the buffed // maximums RynthAi's getcharvital_buffedmax and RynthLua read. diff --git a/src/RynthCore.Engine/Compatibility/ConfirmationResponder.cs b/src/RynthCore.Engine/Compatibility/ConfirmationResponder.cs new file mode 100644 index 0000000..d582af7 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/ConfirmationResponder.cs @@ -0,0 +1,203 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/ConfirmationResponder.cs +// +// Plugin API v81: answer the server's yes/no prompts (craft chance, augmentation, +// ...) for a plugin, the way UtilityBelt's helper clicks "Yes" on the tinkering +// dialog, without the client ever opening that dialog. +// +// INBOUND ConfirmationRequest (GameEvent 0x0274: u32 type, u32 contextId, +// string16 text) reaches UIQueueManager::ProcessNetBlobData, which +// SmartBoxHooks already detours. Its case calls +// CM_Character::DispatchUI_ConfirmationRequest (0x006A3BB0), which hands the +// prompt to the UI handler (0x00564E40) and returns that handler's result; +// the handler returns 0 on every path. So when the request is answered here, +// the detour skips the original and returns 0: nothing else in the client +// sees the prompt, and no dialog is left on screen (ACE never sends +// ConfirmationDone after a response, so an answered dialog would stay open). +// +// OUTBOUND CM_Character::Event_ConfirmationResponse(uint type, uint contextId, +// int accept), 0x006A2030 on the live client: the generated CM_* sender +// template (see Event_GiveObjectRequest in ClientHelperHooks), arg block +// +0x10 (three args), opcode 0x0275. Cdecl, returns bool. Verified unique +// with tools/pe_pattern.py on the live acclient. +// +// ARMING A plugin arms one answer: the confirmation type, a minimum percent and +// a timeout. The next matching request inside the timeout is answered +// Yes when the server's own "N percent chance" is at least the minimum +// (or the minimum is 0), else No, and the arm is spent. An unarmed or +// expired request is left to the client, as before. The last request is +// always recorded so the plugin can see what happened. +// +// Threading: the detour runs on AC's main thread and only takes a short lock; +// the sender is called there, outside the lock. Arm/Get run on any thread. +// ============================================================================ + +using System; +using System.Runtime.InteropServices; + +namespace RynthCore.Engine.Compatibility; + +internal static unsafe class ConfirmationResponder +{ + /// GameEvent ConfirmationRequest. + public const uint EventConfirmationRequest = 0x0274; + + // ABI outcome codes (ConfirmationInfoNative.Outcome). Never renumber. + public const int OutcomeNone = 0; // no request seen this session + public const int OutcomeShown = 1; // not armed (or expired / other type): the client showed it + public const int OutcomeAccepted = 2; // answered Yes for the plugin + public const int OutcomeDeclined = 3; // answered No: the server's percent was below the minimum + public const int OutcomeSendFailed = 4; // armed, but the sender failed; the client showed it + + private const int EventConfirmationResponseVa = 0x006A2030; + + // CM_Character::Event_ConfirmationResponse: the shared CM_* sender template with the + // three-argument block (+0x10) and the opcode immediate 0x0275 at the end. + private static readonly byte?[] PatEventConfirmationResponse = [ 0x83, 0xEC, 0x0C, 0x53, 0x56, 0x57, 0xE8, null, null, null, null, 0x89, 0x44, 0x24, 0x14, 0x6A, 0x00, 0x8D, 0x44, 0x24, 0x10, 0x50, 0x8D, 0x4C, 0x24, 0x18, 0xC7, 0x44, 0x24, 0x18, 0x2C, 0x2C, 0x80, 0x00, 0xC7, 0x44, 0x24, 0x14, 0x00, 0x00, 0x00, 0x00, 0xE8, null, null, null, null, 0x8B, 0xF0, 0x83, 0xC6, 0x10, 0x56, 0xE8, null, null, null, null, 0x83, 0xC4, 0x04, 0x56, 0x8D, 0x4C, 0x24, 0x10, 0x51, 0x8D, 0x4C, 0x24, 0x18, 0x89, 0x44, 0x24, 0x14, 0x8B, 0xF8, 0xE8, null, null, null, null, 0x8B, 0x54, 0x24, 0x0C, 0x8B, 0x4C, 0x24, 0x1C, 0xC7, 0x02, 0x75, 0x02, 0x00, 0x00 ]; + + private static delegate* unmanaged[Cdecl] _eventConfirmationResponse; + + private static readonly object _lock = new(); + // The armed answer (one-shot). + private static bool _armed; + private static uint _armedType; + private static int _armedMinPercent; + private static long _armedUntil; + // The last request seen. + private static int _seq; + private static uint _lastType, _lastContext; + private static int _lastPercent = -1, _lastOutcome; + private static long _lastAt; + private static int _logCount; + + /// True when the response sender is bound on this client. + public static bool HasSender => _eventConfirmationResponse != null; + + /// Bind the sender. Called from ClientHelperHooks.Probe (engine init). + public static void Probe(AcClientTextSection text) + { + HookResolver.ResolveResult r = HookResolver.Resolve(text, "Confirmation.Event_ConfirmationResponse", + PatEventConfirmationResponse, EventConfirmationResponseVa); + _eventConfirmationResponse = r.Success && r.Source == HookResolver.ResolveSource.PatternScan + ? (delegate* unmanaged[Cdecl])r.Address + : null; + RynthLog.Compat($"Compat: confirmation response sender {(HasSender ? $"bound @0x{r.Address.ToInt32():X8}" : "not found")}"); + } + + /// + /// Arm one answer for the next request of within + /// . timeoutMs <= 0 disarms. 1 armed (or disarmed), + /// 0 the sender or the game-event hook isn't available, -3 bad arguments. + /// + public static int Arm(uint type, int minPercent, int timeoutMs) + { + if (timeoutMs <= 0) + { + lock (_lock) _armed = false; + return 1; + } + if (type == 0 || minPercent < 0 || minPercent > 100 || timeoutMs > 120_000) + return -3; + if (!HasSender || !SmartBoxHooks.IsGameEventHookInstalled) + return 0; + lock (_lock) + { + _armed = true; + _armedType = type; + _armedMinPercent = minPercent; + _armedUntil = Environment.TickCount64 + timeoutMs; + } + return 1; + } + + /// The last request: its sequence number (0 = none yet), type, context, the + /// server's percent (-1 when the text has none), outcome and age. + public static int GetLast(out uint type, out uint contextId, out int percent, out int outcome, out int ageMs) + { + lock (_lock) + { + type = _lastType; + contextId = _lastContext; + percent = _lastPercent; + outcome = _lastOutcome; + long age = _seq == 0 ? 0 : Environment.TickCount64 - _lastAt; + ageMs = age > int.MaxValue ? int.MaxValue : (int)age; + return _seq; + } + } + + /// + /// The game-event detour's hook for 0x0274 (AC's main thread). + /// is the event blob (type at +0). True = answered here: the caller must skip AC's + /// handler so no dialog opens. + /// + public static bool OnRequest(IntPtr data, uint size) + { + if (data == IntPtr.Zero || size < 12) + return false; + uint type = unchecked((uint)Marshal.ReadInt32(data, 4)); + uint context = unchecked((uint)Marshal.ReadInt32(data, 8)); + int percent = ParsePercent(data, size); + + bool answer = false, accept = false; + lock (_lock) + { + _seq++; + _lastType = type; + _lastContext = context; + _lastPercent = percent; + _lastAt = Environment.TickCount64; + _lastOutcome = OutcomeShown; + if (_armed && _armedType == type && Environment.TickCount64 <= _armedUntil) + { + _armed = false; + answer = true; + accept = _armedMinPercent <= 0 || (percent >= 0 && percent >= _armedMinPercent); + } + } + if (!answer) + return false; + + bool sent = false; + try + { + sent = _eventConfirmationResponse != null && _eventConfirmationResponse(type, context, accept ? 1 : 0) != 0; + } + catch { sent = false; } + + lock (_lock) + _lastOutcome = !sent ? OutcomeSendFailed : accept ? OutcomeAccepted : OutcomeDeclined; + if (_logCount < 40) + { + _logCount++; + RynthLog.Compat($"Confirmation type={type} ctx=0x{context:X8} percent={percent} -> {(sent ? (accept ? "yes" : "no") : "send failed, shown")}"); + } + return sent; + } + + // "You determine that you have a 38 percent chance to succeed." -> 38. The text is a + // string16 (u16 length, cp1252 bytes) at +12. -1 when there is no "N percent". + private static int ParsePercent(IntPtr data, uint size) + { + const int textOff = 12; + if (size < textOff + 2) + return -1; + int len = (ushort)Marshal.ReadInt16(data, textOff); + if (len <= 0 || len > 512 || textOff + 2 + len > size) + return -1; + byte* p = (byte*)data + textOff + 2; + ReadOnlySpan text = new(p, len); + int at = text.IndexOf(" percent"u8); + if (at <= 0) + return -1; + int end = at, start = at; + while (start > 0 && text[start - 1] >= (byte)'0' && text[start - 1] <= (byte)'9') + start--; + if (start == end || end - start > 3) + return -1; + int value = 0; + for (int i = start; i < end; i++) + value = value * 10 + (text[i] - '0'); + return value > 100 ? 100 : value; + } +} diff --git a/src/RynthCore.Engine/Compatibility/EngineStatusMetrics.cs b/src/RynthCore.Engine/Compatibility/EngineStatusMetrics.cs index 49fe936..516f2ae 100644 --- a/src/RynthCore.Engine/Compatibility/EngineStatusMetrics.cs +++ b/src/RynthCore.Engine/Compatibility/EngineStatusMetrics.cs @@ -42,13 +42,55 @@ internal static class EngineStatusMetrics _mReconciles = reconciles; _mForceClears = forceClears; } - // Per-process session baselines for the per-hour rates. Each client is its own - // process, so these naturally reset per launch; we also reset on an XP drop - // (relog / char swap). - private static long _xpBaseline = -1; - private static long _lumBaseline = -1; + // The session's XP / luminance totals and rates: RynthSuite's shared formula (SessionRates), + // a new session per character. Locked: the status JSON and the Mini Remote's Session Stats + // section read it from different threads, and chat lines arrive on a third. + private static readonly object _ratesLock = new(); + private static readonly SessionRates _rates = new(); private static int _deathsBaseline = -1; - private static DateTime _statsSessionStartUtc = DateTime.UtcNow; + private static uint _deathsCharacter; + private const uint Int64BankedLuminance = 9005; // ACECustom bank + private const uint Int64AelLuminanceBanked = 9102; // Aelrynth bank: luminance auto-banked + private const uint Int64AelLuminanceDrawn = 9103; // Aelrynth bank: luminance drawn + + /// A chat line (PluginManager.QueueChatWindowText): luminance moved into the bank isn't income. + internal static void OnChatLine(string? text) + { + if (string.IsNullOrEmpty(text) || !SessionRates.TryMovedIntoBank(text, out _)) return; + lock (_ratesLock) _rates.OnChat(text, DateTime.UtcNow); + } + + /// + /// Samples the player now and returns the session's totals and rates (the Mini Remote's + /// Session Stats section). Any thread; reads only the main-thread-cached player stats. + /// + internal static SessionRatesView SessionView() + { + try + { + ClientObjectHooks.TryGetPlayerStats(out long xp, out long lum, out _, out _, out _, out _, out _, out _, out _, out _); + return SampleRates(xp, lum); + } + catch + { + return new SessionRatesView(DateTime.UtcNow, 0, 0, 0, 0, 0); + } + } + + /// Feeds one read to the shared-formula session (bank properties read from the property cache). + private static SessionRatesView SampleRates(long xp, long lum) + { + uint player = ClientHelperHooks.GetPlayerId(); + long? Quad(uint stype) => player != 0 && ClientObjectHooks.TryGetObjectQuadProperty(player, stype, out long v) ? v : null; + var sample = new SessionRatesSample(xp > 0 ? xp : null, lum > 0 ? lum : null, + Quad(Int64BankedLuminance), Quad(Int64AelLuminanceBanked), Quad(Int64AelLuminanceDrawn)); + DateTime now = DateTime.UtcNow; + lock (_ratesLock) + { + _rates.Sample(player, sample, now); + return _rates.View(now); + } + } /// /// Compose the engine-side status fields as a JSON object string, from the @@ -120,17 +162,15 @@ internal static class EngineStatusMetrics out int encVal, out int encCap, out uint landcell, out float px, out float py, out float pz); double vitaePct = Math.Clamp((1.0 - vitae) * 100.0, 0.0, 100.0); - // Lazy baselines; reset on an XP drop (relog / char change). - if (xp > 0 && (_xpBaseline < 0 || xp < _xpBaseline)) - { - _xpBaseline = xp; _deathsBaseline = deaths; _statsSessionStartUtc = DateTime.UtcNow; - } - if (_deathsBaseline < 0 && xp > 0) _deathsBaseline = deaths; - if (lum > 0 && (_lumBaseline < 0 || lum < _lumBaseline)) _lumBaseline = lum; - double hours = (DateTime.UtcNow - _statsSessionStartUtc).TotalHours; - double xpPerHour = (hours > 1.0 / 3600.0 && _xpBaseline >= 0 && xp >= _xpBaseline) ? (xp - _xpBaseline) / hours : 0; - double lumPerHour = (hours > 1.0 / 3600.0 && _lumBaseline >= 0 && lum >= _lumBaseline) ? (lum - _lumBaseline) / hours : 0; - long xpSession = (_xpBaseline >= 0 && xp >= _xpBaseline) ? xp - _xpBaseline : 0; + // XP and luminance: the shared formula (sum of rises, ACECustom / Aelrynth bank aware), + // one session per character, the same numbers RynthAi and RynthTracker show. + SessionRatesView rates = SampleRates(xp, lum); + double xpPerHour = rates.XpPerHour; + double lumPerHour = rates.LumPerHour; + long xpSession = rates.Xp; + // Deaths this session: from the first read for this character. + uint who = ClientHelperHooks.GetPlayerId(); + if (who != 0 && who != _deathsCharacter) { _deathsCharacter = who; _deathsBaseline = deaths; } int deathsSession = (_deathsBaseline >= 0 && deaths >= _deathsBaseline) ? deaths - _deathsBaseline : 0; double burdenPct = encCap > 0 ? Math.Round((double)encVal / encCap * 100.0) : 0; w.WriteNumber("deaths", deaths); @@ -139,6 +179,7 @@ internal static class EngineStatusMetrics w.WriteNumber("xpPerHour", Math.Round(xpPerHour)); w.WriteNumber("luminancePerHour", Math.Round(lumPerHour)); w.WriteNumber("xpSession", xpSession); + w.WriteNumber("luminanceSession", rates.Lum); // additive (2026.10.5.54): the luminance total behind luminancePerHour w.WriteNumber("burdenPct", burdenPct); w.WriteString("area", landcell != 0 ? (landcell >> 16).ToString("X4") : ""); // [status-export] live map-dot position. wx/wy are ABSOLUTE world coords (cell-local origin + the diff --git a/src/RynthCore.Engine/Compatibility/IltInfo.cs b/src/RynthCore.Engine/Compatibility/IltInfo.cs index 1b16e5f..e2503b2 100644 --- a/src/RynthCore.Engine/Compatibility/IltInfo.cs +++ b/src/RynthCore.Engine/Compatibility/IltInfo.cs @@ -14,8 +14,8 @@ // defaults (InfiniteLeaftide / *Leaftide* and infiniteleaftide.online); // - RynthILT's own verdict (its server list, or the character's "Treat this // world as ILT"), read once a second by UI/Data/IltData.cs. -// Unknown means not ILT. "/rc ilt on|off|auto" overrides it for this session -// (testing), never saved. +// Unknown means not ILT. "/rc ilt on|off|auto" (or the Mini Remote's Char +// section) overrides it, saved per character (UI/Sections/ServerForceStore). // // Threads: any. Re-evaluated at most once a second; each read in between is a // volatile load and a compare. Never touches AC. @@ -33,10 +33,13 @@ internal static class IltInfo private const int RefreshMs = 1000; + /// The server id the override is saved under (UI/Sections). + public const string ServerId = "ilt"; + private static volatile IltVerdict _verdict = IltVerdict.Unknown; private static long _nextRefreshMs; - private static int _mode; // Mode private static volatile bool _lastIlt; + private static string _loggedWorld = string.Empty; // the world the last verdict line was for (Refresh only) private static volatile bool _pluginLoaded; private static volatile bool _pluginIlt; private static volatile string _pluginReason = ""; @@ -60,16 +63,38 @@ internal static class IltInfo /// True when the client is on Infinite Leaftide - or the override says so. Any thread. public static bool IsIlt => Current.IsIlt; + /// What detection alone says (no override), for the Char section and /rc server. + public static IltVerdict Detected => + IltDetect.Decide(ServerInfo.LaunchHost, AccountHooks.AnnouncedWorldName, EngineSettings.IltServerNames, EngineSettings.IltHosts); + + /// The current character's saved override (session-only before login). public static Mode Override { - get => (Mode)Volatile.Read(ref _mode); - set + get => UI.Sections.ServerForceStore.Get(ServerId) switch { - Volatile.Write(ref _mode, (int)value); - Volatile.Write(ref _nextRefreshMs, 0); - } + UI.Sections.ServerForce.On => Mode.ForceIlt, + UI.Sections.ServerForce.Off => Mode.ForceOther, + _ => Mode.Auto, + }; } + /// Sets the override (saved per character); says where it went. + public static bool SetOverride(Mode mode, out string where) + { + var force = mode switch + { + Mode.ForceIlt => UI.Sections.ServerForce.On, + Mode.ForceOther => UI.Sections.ServerForce.Off, + _ => UI.Sections.ServerForce.Auto, + }; + bool ok = UI.Sections.ServerForceStore.Set(ServerId, force, out where); + Volatile.Write(ref _nextRefreshMs, 0); + return ok; + } + + /// Re-evaluates on the next read (the character or an override changed). + public static void Invalidate() => Volatile.Write(ref _nextRefreshMs, 0); + /// The current verdict (re-evaluated at most once a second). Any thread. public static IltVerdict Current { @@ -106,18 +131,22 @@ internal static class IltInfo { IltVerdict v = Override switch { - Mode.ForceIlt => new IltVerdict { IsIlt = true, Reason = "forced on with /rc ilt on (testing)" }, - Mode.ForceOther => new IltVerdict { Reason = "forced off with /rc ilt off (testing)" }, + Mode.ForceIlt => new IltVerdict { IsIlt = true, Reason = "forced on for this character (/rc ilt auto undoes it)" }, + Mode.ForceOther => new IltVerdict { Reason = "forced off for this character (/rc ilt auto undoes it)" }, _ => IltDetect.Decide(ServerInfo.LaunchHost, AccountHooks.AnnouncedWorldName, EngineSettings.IltServerNames, EngineSettings.IltHosts), }; // RynthILT's own list / override counts too (its verdict, when the engine's says no). if (Override == Mode.Auto) v = IltDetect.Combine(v, _pluginIlt, _pluginReason); _verdict = v; - if (v.IsIlt != _lastIlt) + // Logged on every change and once per announced world, so a session's log always + // says whether (and why) it counted as ILT - "not ILT" included. + string world = AccountHooks.AnnouncedWorldName ?? string.Empty; + if (v.IsIlt != _lastIlt || !string.Equals(world, _loggedWorld, StringComparison.Ordinal)) { _lastIlt = v.IsIlt; - RynthLog.Compat($"IltInfo: {v.Reason}"); + _loggedWorld = world; + RynthLog.Milestone($"IltInfo: {v.Reason} (RynthILT loaded={_pluginLoaded}, says ILT={_pluginIlt}, override={Override})"); } } catch (Exception ex) diff --git a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs index bfb3143..930d72f 100644 --- a/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs +++ b/src/RynthCore.Engine/Compatibility/RynthCoreChatCommands.cs @@ -87,12 +87,17 @@ namespace RynthCore.Engine.Compatibility; /// /rc hotkeys - opens Settings > Hotkeys. /rc hotkey list | add <combo> <action or /// /command> | remove <combo> | enable|disable <combo> | actions | status | on|off - the user /// hotkeys (; saved for the PC in hotkeys.txt). +/// /rc diagnostics (or /rc serverpick) - opens Settings > Diagnostics, the server +/// picker: the one place a server is forced for this character (plugins' "Force a server" links). /// /// internal static class RynthCoreChatCommands { private const string Prefix = "/rc "; + /// The Settings tab with the server picker (UI/Data/SettingsData.cs "Diagnostics"). + private const string DiagnosticsTabName = "Diagnostics"; + /// /// True if was a RynthCore engine command and has /// been handled — the caller must consume it (do NOT forward to AC chat @@ -175,7 +180,7 @@ internal static class RynthCoreChatCommands return true; } - // /rc server [auto|aelrynth|other] : which server the engine thinks this is (testing override) + // /rc server [ auto|on|off | names ilt ...] : the servers, why each is active, per-character overrides if (IsVerb(sub, "server", out string serverArgs)) { try { HandleServerCommand(serverArgs); } @@ -183,7 +188,7 @@ internal static class RynthCoreChatCommands return true; } - // /rc ilt [auto|on|off] : is this Infinite Leaftide (the ILT section), with a testing override + // /rc ilt [auto|on|off] : is this Infinite Leaftide (the ILT section), with a per-character override if (IsVerb(sub, "ilt", out string iltArgs)) { try { HandleIltCommand(iltArgs); } @@ -342,21 +347,49 @@ internal static class RynthCoreChatCommands return true; } - // /rc miniremote [show|hide|toggle|tab ] : the ImGui Mini Remote panel, like its bar - // button (RynthAi's dashboard and "/ra hub" use show / hide). "tab" opens it on one of its - // tabs (RynthAi's quests, pets; RynthILT's character, banking, gear, charms, games; none = - // the remote). + // /rc miniremote [show|hide|toggle|tab |section ] : the ImGui Mini Remote panel, like + // its bar button (RynthAi's dashboard and "/ra hub" use show / hide). "tab" opens it on one of + // its tabs (RynthAi's pets, crafting; RynthILT's gear, games; none = the remote). Quests are + // RynthOracle's window (/ro) since 2026-10-13. Since 2026.10.5.54 the old "character" and + // "charms" tabs open RynthOracle's Character tab (/ro character) and "banking" opens + // RynthInventory's Global Inventory on its Banking tab (/ginv bank). + // "section" opens it on one of its sections (char = Session Stats, map, skills, ...; "remote" = the remote). if (IsVerb(sub, "miniremote", out string remoteArgs) || IsVerb(sub, "remote", out remoteArgs)) { - if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.MiniRemoteFace.Title)) + if (IsVerb(remoteArgs, "tab", out string moved) && MovedTabCommand(moved) is string movedTo) + UI.ServerMenus.Run(movedTo); + else if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.MiniRemoteFace.Title)) Reply("The Mini Remote panel isn't available (the ImGui layer is off?)."); - else if (IsVerb(remoteArgs, "tab", out string tab)) + else if (IsVerb(remoteArgs, "tab", out string tab) + && tab.Length > 0 && ImGuiBackend.Panels.MiniRemoteFace.TryRequestSurface("section:" + tab.Trim().ToLowerInvariant())) { + // A RynthAi that publishes sections: its tabs are sections here. + ImGuiBackend.ImGuiPanelHost.Open(ImGuiBackend.Panels.MiniRemoteFace.Title); + } + else if (IsVerb(remoteArgs, "tab", out tab)) + { + ImGuiBackend.Panels.MiniRemoteFace.RequestSection(UI.Sections.SectionCatalog.RemoteId); ImGuiBackend.ImGuiPanelHost.Open(ImGuiBackend.Panels.MiniRemoteFace.Title); UI.Data.RynthAiCommands.ApplyRemoteCommand("hub", tab.Length > 0 ? "tab " + tab : "tab"); } + else if (IsVerb(remoteArgs, "section", out string section)) + { + string id = UI.Sections.SectionManifestParser.Id(section); + var snap = UI.Sections.SectionRegistry.Current; + if (id != UI.Sections.SectionCatalog.RemoteId && snap.Find(id) == null) + { + var names = new System.Collections.Generic.List { UI.Sections.SectionCatalog.RemoteId }; + foreach (UI.Sections.SectionView v in snap.Sections) names.Add(v.Id); + Reply($"Usage: /rc miniremote section <{string.Join("|", names)}>"); + } + else + { + ImGuiBackend.Panels.MiniRemoteFace.RequestSection(id); + ImGuiBackend.ImGuiPanelHost.Open(ImGuiBackend.Panels.MiniRemoteFace.Title); + } + } else if (!TryPanelMode(remoteArgs, out bool? show)) - Reply("Usage: /rc miniremote [show|hide|toggle|tab ]"); + Reply("Usage: /rc miniremote [show|hide|toggle|tab |section ]"); else SetPanelOpen(ImGuiBackend.Panels.MiniRemoteFace.Title, show); return true; @@ -409,6 +442,20 @@ internal static class RynthCoreChatCommands } return true; } + // /rc diagnostics : Settings > Diagnostics, where a server is forced for this character (the + // server picker). The one place to force a server since 2026.10.5.54, so plugins link here. + if ((IsVerb(sub, "diagnostics", out string diagArgs) || IsVerb(sub, "serverpick", out diagArgs)) && diagArgs.Length == 0) + { + if (!ImGuiBackend.ImGuiPanelHost.HasFace(ImGuiBackend.Panels.SettingsFace.Title)) + Reply("The Settings panel isn't available (the ImGui layer is off?). /rc server auto|on|off works here in chat."); + else + { + ImGuiBackend.Panels.SettingsFace.RequestTab(DiagnosticsTabName); + if (!ImGuiBackend.ImGuiPanelHost.IsOpen(ImGuiBackend.Panels.SettingsFace.Title)) + UI.PanelRouter.Toggle(ImGuiBackend.Panels.SettingsFace.Title); + } + return true; + } if (IsVerb(sub, "hotkey", out hotkeyArgs) || IsVerb(sub, "hotkeys", out hotkeyArgs)) { try @@ -677,42 +724,156 @@ internal static class RynthCoreChatCommands } /// "verb" or "verb args..." (case-insensitive); args trimmed. + private const string ServerUsage = + "Usage: /rc server [ auto|on|off] | pick |auto | [aelrynth|other|auto] | names ilt [add|remove ]"; + /// - /// /rc server: the detection verdict and its signals. "aelrynth" / "other" force it - /// for this session (to test the Aelrynth-only features anywhere, or to see a - /// non-Aelrynth client on Aelrynth); "auto" goes back to detecting. Never saved. + /// /rc server: every server the engine and the plugins know, whether each is active and why. + /// "<server> on|off|auto" forces one on or off, or back to detecting, saved for this + /// character (this session only before login). "aelrynth" / "other" / "auto" alone are the + /// older Aelrynth override. "names ilt" lists, adds or removes Infinite Leaftide's world-name + /// patterns (engine.json IltServerNames). /// private static void HandleServerCommand(string args) { - switch (args.Trim().ToLowerInvariant()) + string[] words = args.Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries); + string first = words.Length > 0 ? words[0].ToLowerInvariant() : string.Empty; + + if (first == "names") { - case "aelrynth": case "on": ServerInfo.Override = ServerInfo.Mode.ForceAelrynth; break; - case "other": case "off": ServerInfo.Override = ServerInfo.Mode.ForceOther; break; - case "auto": ServerInfo.Override = ServerInfo.Mode.Auto; break; - case "": break; - default: - Reply("Usage: /rc server [auto|aelrynth|other]"); - return; + HandleServerNames(words); + return; } + if (first == "pick") + { + // One server for this character (every other off), or "auto": the Diagnostics page's picker. + if (words.Length != 2) { Reply(ServerUsage); return; } + UI.Sections.ServerSelectionStore.Apply(words[1], out string message); + Reply(message); + ReplyServers(); + return; + } + if (words.Length == 1) + { + // The older single-word form: the Aelrynth override. + ServerInfo.Mode? legacy = first switch + { + "aelrynth" or "on" => ServerInfo.Mode.ForceAelrynth, + "other" or "off" => ServerInfo.Mode.ForceOther, + "auto" => ServerInfo.Mode.Auto, + _ => null, + }; + if (legacy == null) { Reply(ServerUsage); return; } + SetServerForce(ServerInfo.ServerId, legacy switch + { + ServerInfo.Mode.ForceAelrynth => UI.Sections.ServerForce.On, + ServerInfo.Mode.ForceOther => UI.Sections.ServerForce.Off, + _ => UI.Sections.ServerForce.Auto, + }); + } + else if (words.Length == 2) + { + if (!UI.Sections.ServerForceText.TryParse(words[1], out UI.Sections.ServerForce mode)) { Reply(ServerUsage); return; } + if (!SetServerForce(first, mode)) return; + } + else if (words.Length > 2) + { + Reply(ServerUsage); + return; + } + + ReplyServers(); ServerVerdict v = ServerInfo.Current; - Reply($"Server: {(v.IsAelrynth ? (v.IsStaging ? "Aelrynth (staging)" : "Aelrynth") : "not Aelrynth")} - {v.Reason}."); - Reply($"Signals: host {ServerInfo.HostDescription}; world name {AccountHooks.AnnouncedWorldName ?? "(not announced)"}; " - + $"override {ServerInfo.Override}."); + Reply($"Aelrynth signals: host {ServerInfo.HostDescription}; world name {AccountHooks.AnnouncedWorldName ?? "(not announced)"}" + + (v.IsStaging ? "; staging" : "") + "."); Reply($"Titles (plugin API v75): {CharacterTitles.Describe()}."); } + /// Saves a server override (per character) and says where it went. False for an unknown server. + private static bool SetServerForce(string serverId, UI.Sections.ServerForce mode) + { + string id = UI.Sections.SectionManifestParser.Id(serverId); + if (id.Length == 0 || (!UI.Sections.SectionRegistry.IsBuiltInServer(id) + && UI.Sections.SectionRegistry.Current.Server(id) == null)) + { + Reply($"No server called '{serverId}'. /rc server lists them."); + return false; + } + if (!UI.Sections.ServerForceStore.Set(id, mode, out string where)) + { + Reply($"Server override not changed: {where}."); + return false; + } + UI.Sections.SectionRegistry.Invalidate(); + Reply($"Server override {id} = {UI.Sections.ServerForceText.Name(mode)} ({where})."); + return true; + } + + /// One line per server: active or not, detected or not, the override, why. + private static void ReplyServers() + { + var snap = UI.Sections.SectionRegistry.Current; + if (snap.Servers.Count == 0) + { + // Before the first frame built a snapshot: the built-in verdicts directly. + IltVerdict ilt = IltInfo.Current; + ServerVerdict ael = ServerInfo.Current; + Reply($"Server ilt (Infinite Leaftide): {(ilt.IsIlt ? "active" : "not active")} - {ilt.Reason}."); + Reply($"Server aelrynth (Aelrynth): {(ael.IsAelrynth ? "active" : "not active")} - {ael.Reason}."); + return; + } + foreach (UI.Sections.ServerState s in snap.Servers) + { + string force = s.Force == UI.Sections.ServerForce.Auto ? "auto" + : $"forced {UI.Sections.ServerForceText.Name(s.Force)} (detected: {(s.Detected ? "yes" : "no")})"; + Reply($"Server {s.Id} ({s.Name}): {(s.Active ? "active" : "not active")}, {force} - {s.Reason}."); + } + } + + /// /rc server names ilt [add|remove <pattern>]: Infinite Leaftide's world-name patterns. + private static void HandleServerNames(string[] words) + { + if (words.Length < 2 || !words[1].Equals(IltInfo.ServerId, StringComparison.OrdinalIgnoreCase)) + { + Reply("Usage: /rc server names ilt [add|remove ] (other servers' lists come from their plugins)."); + return; + } + if (words.Length >= 4) + { + bool add = words[2].Equals("add", StringComparison.OrdinalIgnoreCase); + if (!add && !words[2].Equals("remove", StringComparison.OrdinalIgnoreCase)) + { + Reply("Usage: /rc server names ilt [add|remove ]"); + return; + } + string pattern = string.Join(' ', words, 3, words.Length - 3); + bool changed = Plugins.EngineSettings.EditIltServerName(pattern, add); + Reply(changed + ? $"Infinite Leaftide world names: {(add ? "added" : "removed")} \"{pattern}\" (engine.json)." + : $"Infinite Leaftide world names: \"{pattern}\" was {(add ? "already there (or too long)" : "not there")}."); + IltInfo.Invalidate(); + UI.Sections.SectionRegistry.Invalidate(); + } + else if (words.Length == 3) + { + Reply("Usage: /rc server names ilt [add|remove ]"); + return; + } + Reply($"Infinite Leaftide lists: {IltInfo.ListsDescription}."); + } + /// /// /rc ilt: the Infinite Leaftide verdict, its signals and the lists in force. "on" / - /// "off" force it for this session (testing the ILT section anywhere); "auto" goes back - /// to detecting. Never saved; the lists are engine.json's IltServerNames / IltHosts. + /// "off" force it, saved for this character (this session only before login); "auto" goes + /// back to detecting. The lists are engine.json's IltServerNames / IltHosts. /// private static void HandleIltCommand(string args) { switch (args.Trim().ToLowerInvariant()) { - case "on": case "ilt": IltInfo.Override = IltInfo.Mode.ForceIlt; break; - case "off": case "other": IltInfo.Override = IltInfo.Mode.ForceOther; break; - case "auto": IltInfo.Override = IltInfo.Mode.Auto; break; + case "on": case "ilt": SetServerForce(IltInfo.ServerId, UI.Sections.ServerForce.On); break; + case "off": case "other": SetServerForce(IltInfo.ServerId, UI.Sections.ServerForce.Off); break; + case "auto": SetServerForce(IltInfo.ServerId, UI.Sections.ServerForce.Auto); break; case "": break; default: Reply("Usage: /rc ilt [auto|on|off]"); @@ -805,6 +966,18 @@ internal static class RynthCoreChatCommands SetPanelOpen(title, show); } + /// + /// The command for a Mini Remote tab that moved out (2026.10.5.54): "character" and "charms" + /// are RynthOracle's Character tab, "banking" is RynthInventory's Global Inventory Banking tab. + /// Null for a tab still in the Mini Remote. + /// + internal static string? MovedTabCommand(string tab) => tab.Trim().ToLowerInvariant() switch + { + "character" or "char" or "charms" => "/ro character", + "banking" or "bank" => "/ginv bank", + _ => null, + }; + private static bool IsVerb(string sub, string verb, out string args) { args = string.Empty; diff --git a/src/RynthCore.Engine/Compatibility/ServerInfo.cs b/src/RynthCore.Engine/Compatibility/ServerInfo.cs index 4f7a7a4..2ecf62b 100644 --- a/src/RynthCore.Engine/Compatibility/ServerInfo.cs +++ b/src/RynthCore.Engine/Compatibility/ServerInfo.cs @@ -10,8 +10,9 @@ // - the world name the server announced at login (AccountHooks, the // SendNotice_WorldName hook; not the launcher's own profile name); // - the Bank mod's custom player properties 9101-9103 (PropertyCaches). -// Unknown means not Aelrynth. "/rc server aelrynth|other|auto" overrides it -// for this session (testing), never saved. +// Unknown means not Aelrynth. "/rc server aelrynth|other|auto" (or the Mini +// Remote's Char section) overrides it, saved per character +// (UI/Sections/ServerForceStore). // // Threads: any. Re-evaluated at most once a second; each read in between is a // volatile load and a compare. Never touches AC (dictionary reads only). @@ -29,9 +30,11 @@ internal static class ServerInfo private const int RefreshMs = 1000; + /// The server id the override is saved under (UI/Sections). + public const string ServerId = "aelrynth"; + private static volatile ServerVerdict _verdict = ServerVerdict.Unknown; private static long _nextRefreshMs; - private static int _mode; // Mode private static int _hostRead; private static readonly object HostLock = new(); private static string _host = ""; @@ -49,13 +52,41 @@ internal static class ServerInfo /// Aelrynth's staging world (port 9030 / "Staging" world name). Any thread. public static bool IsStaging => Current.IsStaging; + /// The current character's saved override (session-only before login). public static Mode Override { - get => (Mode)Volatile.Read(ref _mode); - set + get => UI.Sections.ServerForceStore.Get(ServerId) switch { - Volatile.Write(ref _mode, (int)value); - Volatile.Write(ref _nextRefreshMs, 0); + UI.Sections.ServerForce.On => Mode.ForceAelrynth, + UI.Sections.ServerForce.Off => Mode.ForceOther, + _ => Mode.Auto, + }; + } + + /// Sets the override (saved per character); says where it went. + public static bool SetOverride(Mode mode, out string where) + { + var force = mode switch + { + Mode.ForceAelrynth => UI.Sections.ServerForce.On, + Mode.ForceOther => UI.Sections.ServerForce.Off, + _ => UI.Sections.ServerForce.Auto, + }; + bool ok = UI.Sections.ServerForceStore.Set(ServerId, force, out where); + Volatile.Write(ref _nextRefreshMs, 0); + return ok; + } + + /// Re-evaluates on the next read (the character or an override changed). + public static void Invalidate() => Volatile.Write(ref _nextRefreshMs, 0); + + /// What detection alone says (no override), for the Char section and /rc server. + public static ServerVerdict Detected + { + get + { + ReadHostOnce(); + return ServerDetect.Decide(_hostKind, _host, _port, AccountHooks.AnnouncedWorldName, _bankSeen); } } @@ -104,8 +135,8 @@ internal static class ServerInfo ServerVerdict v = Override switch { - Mode.ForceAelrynth => new ServerVerdict { IsAelrynth = true, Reason = "forced on with /rc server aelrynth (testing)" }, - Mode.ForceOther => new ServerVerdict { Reason = "forced off with /rc server other (testing)" }, + Mode.ForceAelrynth => new ServerVerdict { IsAelrynth = true, Reason = "forced on for this character (/rc server aelrynth auto undoes it)" }, + Mode.ForceOther => new ServerVerdict { Reason = "forced off for this character (/rc server aelrynth auto undoes it)" }, _ => ServerDetect.Decide(_hostKind, _host, _port, AccountHooks.AnnouncedWorldName, _bankSeen), }; _verdict = v; diff --git a/src/RynthCore.Engine/Compatibility/SessionRates.cs b/src/RynthCore.Engine/Compatibility/SessionRates.cs new file mode 100644 index 0000000..66a3b99 --- /dev/null +++ b/src/RynthCore.Engine/Compatibility/SessionRates.cs @@ -0,0 +1,160 @@ +// ============================================================================ +// RynthCore.Engine - Compatibility/SessionRates.cs +// The engine's XP / luminance session totals and per-hour rates: the status feed +// (EngineStatusMetrics, GetEngineStatusJson) and the Mini Remote's Session Stats +// section. Same formula as RynthSuite's Plugins/Shared/SessionStats.cs, which +// RynthAi, RynthTracker, RynthOracle and RynthILT show (2026-10-13), so every +// XP/hour and lum/hour on screen agrees: +// - a total is the sum of every rise of the property since the session began; +// a drop (spending luminance, a server resetting a session total) only moves +// the baseline, never takes earnings back; +// - ACECustom's bank (Int64 9005) counts its rises as income, and once it has +// been read the character's AvailableLuminance rises are withdrawals, not income; +// a deposit or incoming transfer seen in chat ("Deposited N luminance") is moved +// money, so that much of the next bank rise isn't counted; +// - Aelrynth's bank: luminance auto-banked (9102) was earned before it left the +// character, luminance drawn (9103) landed on the character without being earned; +// - rate = total / session hours, the session at least one second long. +// A different character (or the first read) starts a new session. +// +// Pure: no AC, no engine state (tools/SectionsTests compiles it). Not thread-safe: +// one caller at a time (EngineStatusMetrics locks around it). +// ============================================================================ + +using System; + +namespace RynthCore.Engine.Compatibility; + +/// One read of the player's properties (null = not readable on this server or yet). +internal readonly record struct SessionRatesSample( + long? TotalXp, long? AvailableLum, long? BankLum, long? AelBanked, long? AelDrawn); + +/// The totals and rates as of the last sample. +internal readonly record struct SessionRatesView( + DateTime StartUtc, double Seconds, long Xp, double XpPerHour, long Lum, double LumPerHour); + +internal sealed class SessionRates +{ + private uint _character; + private DateTime _startUtc; + private long _xp, _lum; + private Rise _xpRise, _lumRise, _bankRise, _aelBankedRise, _aelDrawnRise; + private bool _bankTracked; + // Luminance deposited (or transferred in) waiting for its bank rise, which isn't income. + private long _movedIntoBank; + private DateTime _movedIntoBankUntil; + private static readonly TimeSpan MovedIntoBankLife = TimeSpan.FromSeconds(60); + + /// The character the session belongs to (0 = none yet). + public uint Character => _character; + + /// Starts a fresh session for at . + public void Reset(uint character, DateTime nowUtc) + { + _character = character; + _startUtc = nowUtc; + _xp = _lum = 0; + _xpRise = default; _lumRise = default; _bankRise = default; _aelBankedRise = default; _aelDrawnRise = default; + _bankTracked = false; + _movedIntoBank = 0; + _movedIntoBankUntil = DateTime.MinValue; + } + + /// + /// A chat line: "Deposited N luminance" (character to bank) or "Received N luminance from X" + /// (a transfer) means the next N of bank rise is moved money, not income. + /// + public void OnChat(string? text, DateTime nowUtc) + { + if (!TryMovedIntoBank(text, out long moved)) return; + _movedIntoBank += moved; + _movedIntoBankUntil = nowUtc + MovedIntoBankLife; + } + + /// The deposit / incoming-transfer lines (the shared SessionLumChat.TryMovedIntoBank). + internal static bool TryMovedIntoBank(string? text, out long amount) + => TryAmount(text, "Deposited ", " luminance", out amount) + || TryAmount(text, "Received ", " luminance from ", out amount); + + // The line starts with the prefix (a player quoting it in a tell doesn't), then "1,234,567", then the suffix. + private static bool TryAmount(string? text, string prefix, string suffix, out long amount) + { + amount = 0; + if (string.IsNullOrEmpty(text)) return false; + int i = 0; + while (i < text.Length && char.IsWhiteSpace(text[i])) i++; + if (string.Compare(text, i, prefix, 0, prefix.Length, StringComparison.OrdinalIgnoreCase) != 0) return false; + i += prefix.Length; + int digits = 0; + long value = 0; + for (; i < text.Length; i++) + { + char c = text[i]; + if (c == ',') continue; + if (c < '0' || c > '9') break; + if (value > (long.MaxValue - 9) / 10) return false; + value = value * 10 + (c - '0'); + digits++; + } + if (digits == 0) return false; + if (string.Compare(text, i, suffix, 0, suffix.Length, StringComparison.OrdinalIgnoreCase) != 0) return false; + amount = value; + return true; + } + + /// Takes one read; a new character starts a new session first. + public void Sample(uint character, in SessionRatesSample s, DateTime nowUtc) + { + if (character == 0) return; + if (character != _character) Reset(character, nowUtc); + + if (s.TotalXp is long xp && xp > 0) _xp += _xpRise.Take(xp); + + if (nowUtc > _movedIntoBankUntil) _movedIntoBank = 0; + + long lumUp = 0; + // ACECustom's bank first, so the character rise below already knows it is tracked. + if (s.BankLum is long bank && bank >= 0) + { + _bankTracked = true; + long up = _bankRise.Take(bank); + long moved = Math.Min(up, _movedIntoBank); + _movedIntoBank -= moved; + lumUp += up - moved; + } + long charUp = 0; + if (s.AvailableLum is long lum && lum >= 0) + { + long up = _lumRise.Take(lum); + if (!_bankTracked) charUp += up; + } + if (s.AelDrawn is long drawn) charUp -= _aelDrawnRise.Take(drawn); + if (s.AelBanked is long banked) charUp += _aelBankedRise.Take(banked); + if (charUp > 0) lumUp += charUp; + _lum += lumUp; + } + + /// The totals and per-hour rates at (zeros before the first sample). + public SessionRatesView View(DateTime nowUtc) + { + if (_character == 0) return new SessionRatesView(nowUtc, 0, 0, 0, 0, 0); + double seconds = Math.Max(1.0, (nowUtc - _startUtc).TotalSeconds); + double hours = seconds / 3600.0; + return new SessionRatesView(_startUtc, seconds, _xp, _xp / hours, _lum, _lum / hours); + } + + /// How much a value went up since the last read; the first read is the baseline. + private struct Rise + { + private long _last; + private bool _seen; + + public long Take(long value) + { + long up = _seen && value > _last ? value - _last : 0; + _last = value; + _seen = true; + return up; + } + } +} diff --git a/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs b/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs index b270f7f..e339908 100644 --- a/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs +++ b/src/RynthCore.Engine/Compatibility/SmartBoxHooks.cs @@ -182,6 +182,7 @@ internal static class SmartBoxHooks var pOriginal = (delegate* unmanaged[Thiscall])_originalDispatchGameEventPtr; EnchantmentChange? enchantment = null; + bool answered = false; try { // Reject undersized payloads instead of clamping up: an inflated @@ -199,10 +200,19 @@ internal static class SmartBoxHooks ParseGameEvent(eventType, data, (uint)len); if ((eventType >= 0x02C2 && eventType <= 0x02C8) || eventType == 0x0312) enchantment = CaptureEnchantmentEvent(eventType, data, (uint)len); + // v81: a prompt a plugin armed an answer for is answered here instead of + // opening AC's dialog. + if (eventType == ConfirmationResponder.EventConfirmationRequest) + answered = ConfirmationResponder.OnRequest(data, (uint)len); } } catch { } + // AC's ConfirmationRequest handler returns 0 on every path, so an answered prompt + // returns the same without reaching it. + if (answered) + return 0; + uint status = pOriginal(thisPtr, data, size); // Enchantment events are queued AFTER the original ran: by then AC's diff --git a/src/RynthCore.Engine/EntryPoint.cs b/src/RynthCore.Engine/EntryPoint.cs index 15c9dd1..dcb957e 100644 --- a/src/RynthCore.Engine/EntryPoint.cs +++ b/src/RynthCore.Engine/EntryPoint.cs @@ -471,6 +471,19 @@ public static class EntryPoint return _imGuiNativeHandle; } + /// + /// Full path of in the engine's own folders (the ones + /// searches), or null. Never Windows' search order. + /// + internal static string? FindNativeDll(string dllName) + { + string? engineDir = GetEngineDirectory(); + if (string.IsNullOrEmpty(engineDir)) return null; + foreach (string path in GetNativeDllCandidates(engineDir, dllName)) + if (File.Exists(path)) return path; + return null; + } + private static string[] GetNativeDllCandidates(string engineDir, string dllName) { var candidates = new List(); @@ -569,41 +582,47 @@ public static class EntryPoint private static bool _serverMenusRegistered; /// - /// The server sections of the Char and Mini Remote menus (UI.ServerMenus): each server once, - /// then the items of the installed plugins that have windows for it. A server whose plugins - /// are all missing gets no items, so its section never shows. + /// The engine's own server items for the Mini Remote's sections and the menus + /// (UI/Sections/SectionRegistry): its windows that belong to one server, added only when + /// the plugin behind each is installed. Plugins add their own through their manifests. /// private static void RegisterServerMenus(bool rynthAi, bool rynthIlt) { if (_serverMenusRegistered) return; _serverMenusRegistered = true; - // Infinite Leaftide: IltInfo (host / world name lists, RynthILT's own verdict, or "/rc ilt on" - // for the session), with RynthILT loaded: every ILT window is RynthILT's (since 2026-10-13). - UI.ServerMenus.DefineServer("ilt", "Infinite Leaftide", static () => IltInfo.IsIlt && IltInfo.PluginLoaded, "/rc ilt on"); + // Infinite Leaftide (IltInfo: host / world-name lists, RynthILT's own verdict, or the + // per-character "/rc ilt on"). Every ILT window is RynthILT's (since 2026-10-13), so the + // engine adds them only when RynthILT is installed. + const string ilt = IltInfo.ServerId; if (rynthIlt && rynthAi) { // RynthILT's ILT tabs in RynthAi's Mini Remote (shown once the server reports each on). - // The Mini Remote's Quests and Pets tabs are universal: the Character half of the menus. - foreach ((string label, string tab) in new[] + // A RynthAi that doesn't publish sections gets these stand-ins; one that does lists them itself. + // Character and Charms are RynthOracle's Character tab and Banking is RynthInventory's + // Global Inventory since 2026.10.5.54, so only Gear and Games are left here. + foreach ((string label, string tab, string section) in new[] { - ("Character", "character"), ("Banking", "banking"), ("Gear", "gear"), ("Charms", "charms"), ("Games", "games"), + ("Gear", "gear", "inventory"), ("Games", "games", "fellowship"), }) { - UI.ServerMenus.AddItem("ilt", new UI.ServerMenuItem(label, "/rc miniremote tab " + tab, - $"The Mini Remote's {label} tab (RynthILT).", "tab:" + tab)); + UI.Sections.SectionRegistry.AddEngineItem(section, ilt, label, "/rc miniremote tab " + tab, + $"The Mini Remote's {label} tab (RynthILT).", unlessPlugin: "RynthAi"); } } if (rynthIlt) { - UI.ServerMenus.AddItem("ilt", new UI.ServerMenuItem("Guardian", "/rc guardian toggle", - "Temple of Enlightenment guardians: riddle answers and Give (RynthILT).")); - UI.ServerMenus.AddItem("ilt", new UI.ServerMenuItem("Bounties", "/rc bounties toggle", - "ACECustom bounties and your progress on each (RynthILT).")); - UI.ServerMenus.AddItem("ilt", new UI.ServerMenuItem("Progression", "/rc progression", - "XP planner, augmentations and enlightenment (the Skills panel's Progression tab; RynthILT).")); + // The engine's ILT panels, fed by RynthILT. + // Guardian sits with Progression (Temple of Enlightenment): Session Stats is session stats only. + UI.Sections.SectionRegistry.AddEngineItem("skills", ilt, "Guardian", "/rc guardian toggle", + "Temple of Enlightenment guardians: riddle answers and Give (RynthILT)."); + UI.Sections.SectionRegistry.AddEngineItem("skills", ilt, "Progression", "/rc progression", + "XP planner, augmentations and enlightenment (the Skills panel's Progression tab; RynthILT)."); + UI.Sections.SectionRegistry.AddEngineItem("combat", ilt, "Bounties", "/rc bounties toggle", + "ACECustom bounties and your progress on each (RynthILT)."); } UI.ServerMenus.PushToRynthAi = rynthAi; + UI.ServerMenus.PushToRynthIlt = rynthIlt; } private static bool HasPluginDll(string dllFileName) diff --git a/src/RynthCore.Engine/Hooking/MinHook.cs b/src/RynthCore.Engine/Hooking/MinHook.cs index bf0f758..5b10e8f 100644 --- a/src/RynthCore.Engine/Hooking/MinHook.cs +++ b/src/RynthCore.Engine/Hooking/MinHook.cs @@ -80,7 +80,7 @@ internal static unsafe class MinHook IntPtr module = GetModuleHandleW(LoaderDll); bool facade = module != IntPtr.Zero && GetProcAddress(module, "RcHooks_Version") != IntPtr.Zero; if (!facade) - module = NativeLibrary.Load(DLL, typeof(MinHook).Assembly, null); + module = LoadMinHookFromEngineFolders(); IntPtr Get(string name) { @@ -103,6 +103,19 @@ internal static unsafe class MinHook }; } + /// + /// minhook.x86.dll by full path from the engine's folders (where the early preload found it). + /// Never by bare name: Windows' search order (the AC client folder, the current directory, + /// PATH) would load a planted minhook.x86.dll into the client when ours is missing. + /// + private static IntPtr LoadMinHookFromEngineFolders() + { + string? path = EntryPoint.FindNativeDll(DLL); + if (path == null) + throw new DllNotFoundException($"{DLL} was not found beside the engine (other folders are not searched)."); + return NativeLibrary.Load(path); + } + [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] private static extern IntPtr GetModuleHandleW(string lpModuleName); diff --git a/src/RynthCore.Engine/ImGui/EngineFrameController.cs b/src/RynthCore.Engine/ImGui/EngineFrameController.cs index ec4de6e..7675718 100644 --- a/src/RynthCore.Engine/ImGui/EngineFrameController.cs +++ b/src/RynthCore.Engine/ImGui/EngineFrameController.cs @@ -766,6 +766,10 @@ internal static class EngineFrameController Hud.MonsterHud.Draw(_uiScale, worldVisible: !D3D9.VideoPatch.SkipWorldThisFrame); // Video patch "all": the "rendering paused" banner (background list, under the panels). VideoPatchBanner.Draw(); + // Server verdicts, the plugins' section manifests and the servermenu push. Every + // frame, bar or not: with the bar hidden (the rail instead) nothing else ticks them, + // so Options > Diagnostics listed no servers and no server plugin was told it is active. + RynthCore.Engine.UI.ServerMenus.Tick(); if (ImGuiBar.Visible) ImGuiBar.Draw(_uiScale); ImGuiPanelHost.DrawAll(_uiScale); diff --git a/src/RynthCore.Engine/ImGui/ImGuiBar.cs b/src/RynthCore.Engine/ImGui/ImGuiBar.cs index 68a5e38..664d97c 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiBar.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiBar.cs @@ -264,8 +264,7 @@ internal static class ImGuiBar public static void Draw(float s) { - // The bar draws every frame the ImGui shell is up: keep RynthAi's server menu current. - RynthCore.Engine.UI.ServerMenus.Tick(); + // ServerMenus.Tick runs from EngineFrameController every frame, bar shown or not. EnsureButtons(); int step = ChromeStep(out float factor); s *= factor; @@ -358,7 +357,7 @@ internal static class ImGuiBar ImGuiNET.ImGui.SetWindowPos(next); _userMoved = true; } - ImGuiNET.ImGui.SetItemTooltip(_tooltip); + SafeImGui.SetItemTooltip(_tooltip); if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) ImGuiNET.ImGui.OpenPopup("##face_bar"); PhosphorIcons.DrawCentered(dl, iconFont, PhosphorIcons.DotsSixVertical, rcPos, new Vector2(square.X * 0.8f, square.Y), RynthTheme.RcLabel); @@ -372,7 +371,7 @@ internal static class ImGuiBar if (ImGuiNET.ImGui.InvisibleButton("##barcollapse", caretSize)) RynthAiDashboardState.SetBarCollapsed(!collapsed); bool caretHot = ImGuiNET.ImGui.IsItemHovered(); - ImGuiNET.ImGui.SetItemTooltip(collapsed ? "Show the bar" : "Fold the bar to this button"); + SafeImGui.SetItemTooltip(collapsed ? "Show the bar" : "Fold the bar to this button"); PhosphorIcons.DrawCentered(dl, iconFont, collapsed ? PhosphorIcons.CaretRight : PhosphorIcons.CaretLeft, cPos, caretSize, caretHot ? RynthTheme.RcLabel : 0xFF9A9A9Au); if (collapsed) return; @@ -406,7 +405,7 @@ internal static class ImGuiBar if (only != null) PanelRouter.Toggle(only); else ImGuiNET.ImGui.OpenPopup("##ilt_menu"); } - ImGuiNET.ImGui.SetItemTooltip(only != null ? "Infinite Leaftide: " + only : "Infinite Leaftide"); + SafeImGui.SetItemTooltip(only != null ? "Infinite Leaftide: " + only : "Infinite Leaftide"); } // Script windows (decision 2): one button with a menu, only while a ShowInBar @@ -435,7 +434,7 @@ internal static class ImGuiBar ImGuiNET.ImGui.SameLine(); if (IconButton("##popout", iconFont, popped ? PhosphorIcons.ArrowSquareIn : PhosphorIcons.ArrowSquareOut, square, RynthTheme.PopOutLabel)) SetPoppedOut(!popped); - ImGuiNET.ImGui.SetItemTooltip(popped ? "Dock the bar back into the game window." : "Pop the bar out into its own floating window."); + SafeImGui.SetItemTooltip(popped ? "Dock the bar back into the game window." : "Pop the bar out into its own floating window."); } else if (Plugins.EngineSettings.EnableAvaloniaOverlay) // Avalonia/Both bar: pops out as the Avalonia bar { @@ -534,7 +533,7 @@ internal static class ImGuiBar private static void FacePopup(string popupId, string title, bool hasImGuiFace, float s = 1f) { if (!ImGuiNET.ImGui.BeginPopup(popupId)) return; - ImGuiNET.ImGui.TextDisabled(title == FaceKey ? "Bar, docked, shows as" : "Docked, shows as"); + SafeImGui.TextDisabled(title == FaceKey ? "Bar, docked, shows as" : "Docked, shows as"); PanelFace current = title == FaceKey ? ResolveFace() : PanelRouter.ResolveDockedFace(title); for (int i = 0; i < Faces.Length; i++) { diff --git a/src/RynthCore.Engine/ImGui/ImGuiFontTest.cs b/src/RynthCore.Engine/ImGui/ImGuiFontTest.cs index 0c3c8fb..9cea744 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiFontTest.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiFontTest.cs @@ -29,7 +29,7 @@ internal static class ImGuiFontTest ImGuiNET.ImGui.SetNextWindowSize(new Vector2(560, 520) * scale, ImGuiCond.FirstUseEver); if (ImGuiNET.ImGui.Begin("RynthCore font test##fonttest")) { - ImGuiNET.ImGui.TextDisabled($"scale {scale:0.##} atlas {ImGuiNET.ImGui.GetIO().Fonts.TexWidth}x{ImGuiNET.ImGui.GetIO().Fonts.TexHeight}"); + SafeImGui.TextDisabled($"scale {scale:0.##} atlas {ImGuiNET.ImGui.GetIO().Fonts.TexWidth}x{ImGuiNET.ImGui.GetIO().Fonts.TexHeight}"); for (UiFont f = 0; f < UiFont.Count; f++) { ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(f)); @@ -54,7 +54,7 @@ internal static class ImGuiFontTest ImGuiNET.ImGui.SameLine(); ImGuiNET.ImGui.TextColored(ImGuiNET.ImGui.ColorConvertU32ToFloat4(RynthTheme.ReloadLabel), "RL"); ImGuiNET.ImGui.SameLine(); - ImGuiNET.ImGui.TextColored(ImGuiNET.ImGui.ColorConvertU32ToFloat4(RynthTheme.PopOutLabel), PhosphorIcons.ArrowSquareOut); + SafeImGui.TextColored(ImGuiNET.ImGui.ColorConvertU32ToFloat4(RynthTheme.PopOutLabel), PhosphorIcons.ArrowSquareOut); } ImGuiNET.ImGui.End(); } diff --git a/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs b/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs index e5b3f26..676b110 100644 --- a/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs +++ b/src/RynthCore.Engine/ImGui/ImGuiPanelHost.cs @@ -379,6 +379,7 @@ internal static class ImGuiPanelHost /// public static void DragWindowWithLastItem() { + if (_inEmbed) return; // embedded in another panel: that panel's window isn't this face's to move if (ImGuiPopOuts.InPopOutFrame) { // Popped out: the OS window moves (it follows the cursor from here on). @@ -394,6 +395,7 @@ internal static class ImGuiPanelHost /// Asks for a new window size (logical units), applied on the next frame it draws. Any thread. public static void RequestSize(string title, Vector2 logicalSize) { + if (_inEmbed) return; // an embedded copy must not resize the face's own window lock (Sync) { if (!Entries.TryGetValue(title, out Entry? entry)) return; @@ -409,6 +411,7 @@ internal static class ImGuiPanelHost /// public static void RequestPos(string title, Vector2 logicalPos) { + if (_inEmbed) return; lock (Sync) { if (!Entries.TryGetValue(title, out Entry? entry)) return; @@ -450,10 +453,12 @@ internal static class ImGuiPanelHost /// public static void DrawAll(float uiScale) { + _frameScale = uiScale; float placeScale = PlacementScale(); while (Requests.TryDequeue(out var req)) Apply(req.Title, req.Kind, placeScale); RemoveUnregistered(); + SweepEmbedded(); List order; lock (Sync) order = DrawOrder; @@ -485,6 +490,7 @@ internal static class ImGuiPanelHost Entry? entry; lock (Sync) Entries.TryGetValue(title, out entry); if (entry == null || !entry.Shown || !entry.Popped) return; + _frameScale = uiScale; DrawPanel(entry, uiScale, PlacementScale(), display); } @@ -1025,6 +1031,148 @@ internal static class ImGuiPanelHost /// The panel whose face is drawing right now (names a text box's owner in the input log). AC thread. internal static string? DrawingTitle { get; private set; } + // ── Embedding: a face drawn inside another panel (the Mini Remote's sections) ── + + /// An embedded copy of a face: its own instance, so the face's own window is unaffected. + private sealed class EmbeddedFace + { + public required string Title; + public required IImGuiPanel Instance; + public long LastDrawnMs; + public int Failures; + public string? Error; + } + + /// Embedded copies by host + title. AC thread only (docked and pop-out frames both run there). + private static readonly Dictionary EmbeddedFaces = new(StringComparer.OrdinalIgnoreCase); + + /// An embedded copy not drawn for this long is hidden and dropped (its section was left). + private const long EmbedIdleMs = 750; + + /// Faces that can't be embedded: the hosts themselves. + private static readonly HashSet NotEmbeddable = new(StringComparer.OrdinalIgnoreCase) { "Mini Remote" }; + + /// The UI scale of the frame being drawn (docked or popped). AC thread. + private static float _frameScale = 1f; + + /// True while an embedded copy draws: its window moves and size requests are ignored. + [ThreadStatic] private static bool _inEmbed; + + /// True when is registered and may be drawn inside another panel. Any thread. + public static bool CanEmbed(string title) => !NotEmbeddable.Contains(title) && HasFace(title); + + /// A registered face's default window size (logical units). Any thread. + public static bool TryGetDefaultSize(string title, out Vector2 size) + { + Entry? entry; + lock (Sync) Entries.TryGetValue(title, out entry); + size = entry?.Spec.DefaultSize ?? Vector2.Zero; + return entry != null; + } + + /// + /// Draws a copy of the face into the current window, in a child of + /// (pixels; 0 = fill). separates the copies + /// of different hosts. The copy is created on first draw and dropped (OnHidden) once it + /// hasn't drawn for . AC thread, inside a window. + /// + public static void DrawEmbedded(string hostKey, string title, Vector2 size) + { + Entry? entry; + lock (Sync) Entries.TryGetValue(title, out entry); + if (entry == null || NotEmbeddable.Contains(title)) + { + ImGuiNET.ImGui.TextDisabled("Not available."); + return; + } + + string key = hostKey + "\u001f" + title; + if (!EmbeddedFaces.TryGetValue(key, out EmbeddedFace? face)) + { + try + { + IImGuiPanel instance = entry.Factory(); + instance.OnShown(); + face = new EmbeddedFace { Title = title, Instance = instance }; + } + catch (Exception ex) + { + RynthLog.UI($"ImGuiPanelHost: embedding {title} failed - {ex.GetType().Name}: {ex.Message}"); + face = new EmbeddedFace { Title = title, Instance = new NullFace(), Error = $"{title} failed to open: {ex.Message}" }; + } + EmbeddedFaces[key] = face; + } + face.LastDrawnMs = Environment.TickCount64; + + PanelSpec spec = entry.Spec; + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, spec.EdgeToEdge ? Vector2.Zero : new Vector2(6, 4) * _frameScale); + ImGuiWindowFlags flags = ImGuiWindowFlags.NoBackground | spec.BodyFlags; + if (spec.EdgeToEdge) flags |= ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoScrollWithMouse; + bool open = ImGuiNET.ImGui.BeginChild("##embed_" + title, size, ImGuiChildFlags.AlwaysUseWindowPadding, flags); + ImGuiNET.ImGui.PopStyleVar(); + try + { + if (!open) return; + if (face.Error != null) + { + // Never a format string: the error carries an exception message. + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, new Vector4(1f, 0.4f, 0.3f, 1f)); + ImGuiNET.ImGui.PushTextWrapPos(0f); + ImGuiNET.ImGui.TextUnformatted(face.Error); + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.PopStyleColor(); + return; + } + string? outer = DrawingTitle; + _inEmbed = true; + DrawingTitle = title; + try + { + face.Instance.Draw(); + } + catch (Exception ex) + { + face.Failures++; + RynthLog.UI($"ImGuiPanelHost: embedded {title}.Draw threw {ex.GetType().Name}: {ex.Message} ({face.Failures}/{MaxFailures})"); + if (face.Failures >= MaxFailures) + face.Error = $"{title} stopped drawing after repeated errors: {ex.Message}"; + } + finally + { + _inEmbed = false; + DrawingTitle = outer; + } + } + finally + { + ImGuiNET.ImGui.EndChild(); + } + } + + /// Hides and drops embedded copies whose host stopped drawing them. AC thread. + private static void SweepEmbedded() + { + if (EmbeddedFaces.Count == 0) return; + long now = Environment.TickCount64; + List? stale = null; + foreach (var kv in EmbeddedFaces) + if (now - kv.Value.LastDrawnMs > EmbedIdleMs) (stale ??= new List()).Add(kv.Key); + if (stale == null) return; + foreach (string key in stale) + { + EmbeddedFace face = EmbeddedFaces[key]; + EmbeddedFaces.Remove(key); + try { face.Instance.OnHidden(); } + catch (Exception ex) { RynthLog.UI($"ImGuiPanelHost: embedded {face.Title}.OnHidden threw {ex.GetType().Name}: {ex.Message}"); } + } + } + + /// Stands in for a face that failed to open, so its error line can draw. + private sealed class NullFace : IImGuiPanel + { + public void Draw() { } + } + private static void DrawBody(Entry entry) { DrawingTitle = entry.Title; @@ -1247,7 +1395,7 @@ internal static class ImGuiPanelHost if (ImGuiNET.ImGui.Button(PhosphorIcons.ArrowCounterClockwise + " Reset")) PanelTextScale.ResetWindow(title); ImGuiNET.ImGui.EndDisabled(); - ImGuiNET.ImGui.SetItemTooltip(all == 0 ? "Back to normal size" : "Back to the All Panels size (Settings > Display)"); + SafeImGui.SetItemTooltip(all == 0 ? "Back to normal size" : "Back to the All Panels size (Settings > Display)"); ImGuiNET.ImGui.SameLine(); if (ImGuiNET.ImGui.Button("Use for all windows")) PanelTextScale.UseForAll(step); diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettingsUi.cs b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettingsUi.cs index d8a908d..363b23d 100644 --- a/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettingsUi.cs +++ b/src/RynthCore.Engine/ImGui/MonsterHud/MonsterHudSettingsUi.cs @@ -249,7 +249,7 @@ internal static class MonsterHudSettingsUi if (ImGuiNET.ImGui.IsItemHovered()) { ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand); - if (tip != null) ImGuiNET.ImGui.SetTooltip(tip); + if (tip != null) SafeImGui.SetTooltip(tip); } if (clicked) value = radio || !value; dl.AddRectFilled(p + new Vector2(0, 2), p + new Vector2(12, 14), value ? ToggleOn : ToggleOff, 2); @@ -270,7 +270,7 @@ internal static class MonsterHudSettingsUi { BeginSliderRow(label, w); bool changed = ImGuiNET.ImGui.SliderFloat("##v", ref value, min, max, "%.2fx", ImGuiSliderFlags.AlwaysClamp); - if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(tip); + if (ImGuiNET.ImGui.IsItemHovered()) SafeImGui.SetTooltip(tip); return EndSliderRow(changed); } diff --git a/src/RynthCore.Engine/ImGui/MonsterHud/PlayerPlate.cs b/src/RynthCore.Engine/ImGui/MonsterHud/PlayerPlate.cs index dc4136d..7cdcc32 100644 --- a/src/RynthCore.Engine/ImGui/MonsterHud/PlayerPlate.cs +++ b/src/RynthCore.Engine/ImGui/MonsterHud/PlayerPlate.cs @@ -243,7 +243,7 @@ internal static class PlayerPlate { ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.ResizeAll); if (_hover && !_dragging) - ImGuiNET.ImGui.SetTooltip(DragTip); + SafeImGui.SetTooltip(DragTip); } _wantsMouse = _hover || _dragging; } diff --git a/src/RynthCore.Engine/ImGui/Panels/BountiesFace.cs b/src/RynthCore.Engine/ImGui/Panels/BountiesFace.cs index da71405..f06c60b 100644 --- a/src/RynthCore.Engine/ImGui/Panels/BountiesFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/BountiesFace.cs @@ -150,7 +150,7 @@ internal sealed class BountiesFace : IImGuiPanel if (Button("##bounty_hideqb", hideLabel, new Vector2(x, p.Y), new Vector2(hw, 22), d.HideQbLocked ? OnText : Mute, d.HideQbLocked ? OnBg : BtnFill)) BountiesCommands.Set("hideqblocked", !d.HideQbLocked); - if (d.HiddenCount > 0) ImGuiNET.ImGui.SetItemTooltip($"{d.HiddenCount} hidden"); + if (d.HiddenCount > 0) SafeImGui.SetItemTooltip($"{d.HiddenCount} hidden"); x += hw + 4; const string sortLabel = "Closest first"; @@ -263,7 +263,7 @@ internal sealed class BountiesFace : IImGuiPanel BountyRowStatus.NeedsQb => $"\nNeeds {N0(r.QbRequired)} QB; you have {N0(r.QbHave)}.", _ => string.Empty, }; - ImGuiNET.ImGui.SetTooltip($"{r.Where}: {N0(r.Amount)} {r.Item}\n{every}{detail}"); + SafeImGui.SetTooltip($"{r.Where}: {N0(r.Amount)} {r.Item}\n{every}{detail}"); } NextLine(p, RowH); } diff --git a/src/RynthCore.Engine/ImGui/Panels/CharactersFace.cs b/src/RynthCore.Engine/ImGui/Panels/CharactersFace.cs index 52f9dab..bb81056 100644 --- a/src/RynthCore.Engine/ImGui/Panels/CharactersFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/CharactersFace.cs @@ -369,23 +369,23 @@ internal sealed class CharactersFace : IImGuiPanel bool canFollow = me.Length > 0; if (!_menuSelf && !_menuLoggedOut) { - ImGuiNET.ImGui.TextDisabled(_menuName); + SafeImGui.TextDisabled(_menuName); if (ImGuiNET.ImGui.MenuItem("Select", "", false, _menuInView && _menuId != 0)) AcMainThreadQueue.EnqueueOverlaySelect(_menuId); ImGuiNET.ImGui.Separator(); if (ImGuiNET.ImGui.MenuItem("Follow me", "", false, canFollow && !_menuOtherWorld)) CharactersCommands.Tell(_menuName, "/ra follow " + me); - ImGuiNET.ImGui.SetItemTooltip($"/rn tell {_menuName}, /ra follow {me}"); + SafeImGui.SetItemTooltip($"/rn tell {_menuName}, /ra follow {me}"); if (ImGuiNET.ImGui.MenuItem("Stop following")) CharactersCommands.Tell(_menuName, "/ra follow off"); - ImGuiNET.ImGui.SetItemTooltip($"/rn tell {_menuName}, /ra follow off"); + SafeImGui.SetItemTooltip($"/rn tell {_menuName}, /ra follow off"); ImGuiNET.ImGui.Separator(); if (ImGuiNET.ImGui.MenuItem("Start macro")) CharactersCommands.Tell(_menuName, "/ra start"); - ImGuiNET.ImGui.SetItemTooltip($"/rn tell {_menuName}, /ra start"); + SafeImGui.SetItemTooltip($"/rn tell {_menuName}, /ra start"); if (ImGuiNET.ImGui.MenuItem("Stop macro")) CharactersCommands.Tell(_menuName, "/ra stop"); - ImGuiNET.ImGui.SetItemTooltip($"/rn tell {_menuName}, /ra stop"); + SafeImGui.SetItemTooltip($"/rn tell {_menuName}, /ra stop"); ImGuiNET.ImGui.Separator(); } if (ImGuiNET.ImGui.MenuItem("Everyone: follow me", "", false, canFollow)) diff --git a/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs b/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs index 4ddd41d..1eed5ec 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs @@ -235,7 +235,7 @@ internal sealed class ChatFace : IImGuiPanel else _drawers.Toggle(_channels); } if (ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.ForTooltip)) - ImGuiNET.ImGui.SetTooltip(mention ? "Channels (someone mentioned you)" : "Channels: pick a tab, see what's unread"); + SafeImGui.SetTooltip(mention ? "Channels (someone mentioned you)" : "Channels: pick a tab, see what's unread"); float ty = start.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f; dl.PushClipRect(start, start + new Vector2(bw - caretW - 6 - (badge != null ? badgeW + 4 : 0), h), true); dl.AddText(new Vector2(start.X + 6, ty), Text, label); @@ -994,7 +994,7 @@ internal sealed class ChatFace : IImGuiPanel ChatModel.SetHistoryLines(_historyEdit); _historyEdit = 0; } - ImGuiNET.ImGui.SetItemTooltip("How many lines the chat keeps, all tabs together (default 2000).\n" + + SafeImGui.SetItemTooltip("How many lines the chat keeps, all tabs together (default 2000).\n" + "About 2 MB of memory per 1000 lines. Lowering it drops the oldest lines."); ImGuiNET.ImGui.PopItemWidth(); @@ -1025,7 +1025,7 @@ internal sealed class ChatFace : IImGuiPanel ChatModel.LogEnabled = log; ChatModel.SaveSettings(); } - ImGuiNET.ImGui.SetItemTooltip("%%AppData%%\\RynthCore\\ChatLogs\\.log"); // a format string: %% is a literal % + SafeImGui.SetItemTooltip("%AppData%\\RynthCore\\ChatLogs\\.log"); // SafeImGui doubles the % itself bool through = ChatModel.CtrlGatedClickThrough; if (ImGuiNET.ImGui.Checkbox("Click-through (hold Ctrl to interact)", ref through)) ChatModel.SetCtrlGatedClickThrough(through); @@ -1136,7 +1136,7 @@ internal sealed class ChatFace : IImGuiPanel } ImGuiNET.ImGui.SameLine(); Label(kind.Label, RynthTheme.Argb(argb)); - ImGuiNET.ImGui.SetItemTooltip(kind.Hint + (set ? "" : kind.Key.StartsWith(ChatLineColors.TabPrefix, StringComparison.Ordinal) + SafeImGui.SetItemTooltip(kind.Hint + (set ? "" : kind.Key.StartsWith(ChatLineColors.TabPrefix, StringComparison.Ordinal) ? "\nThe built-in colour." : $"\nNot set: the {kind.Tab} tab's colour.")); if (set) { diff --git a/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs b/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs index 17c431e..88a11a6 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ChatFiltersFace.cs @@ -208,7 +208,7 @@ internal sealed class ChatFiltersFace : IImGuiPanel ImGuiNET.ImGui.PushID(p.Id); bool enabled = p.Enabled; if (ImGuiNET.ImGui.Checkbox(p.Label, ref enabled)) { p.Enabled = enabled; ChatModel.FiltersChanged(); } - ImGuiNET.ImGui.SetItemTooltip(p.Description + "\nExample: " + p.Example); + SafeImGui.SetItemTooltip(p.Description + "\nExample: " + p.Example); ImGuiNET.ImGui.SameLine(Math.Max(ImGuiNET.ImGui.GetCursorPosX() + 8, rowW * 0.6f)); string tabText = (p.Tab.Length == 0 ? "hide" : "to " + p.Tab) + Caret; if (ImGuiNET.ImGui.SmallButton(tabText)) @@ -260,7 +260,7 @@ internal sealed class ChatFiltersFace : IImGuiPanel ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X + 16, p.Y + 1)); bool on = r.Enabled; if (ImGuiNET.ImGui.Checkbox("##on", ref on)) { r.Enabled = on; ChatModel.FiltersChanged(); } - ImGuiNET.ImGui.SetItemTooltip(on ? "Rule on (click to turn off)" : "Rule off (click to turn on)"); + SafeImGui.SetItemTooltip(on ? "Rule on (click to turn off)" : "Rule off (click to turn on)"); const float btn = 22; float x = p.X + 42; @@ -275,7 +275,7 @@ internal sealed class ChatFiltersFace : IImGuiPanel moded.Recompile(); ChatModel.FiltersChanged(); }, 120); - ImGuiNET.ImGui.SetItemTooltip(ModeHelp[modeIdx]); + SafeImGui.SetItemTooltip(ModeHelp[modeIdx]); x += modeW + 4; float patW = Math.Max(80, card.X + rowW - 4 - 3 * (btn + 2) - 4 - x); if (TextBox("##pat", b.Pattern, new Vector2(x, p.Y), patW, ModeHints[modeIdx], out bool patActive)) @@ -323,7 +323,7 @@ internal sealed class ChatFiltersFace : IImGuiPanel if (rule.Action == ChatRuleAction.Color && rule.ColorMode == ChatColorMode.None) rule.ColorMode = ChatColorMode.Line; ChatModel.FiltersChanged(); }, 140); - ImGuiNET.ImGui.SetItemTooltip(ActionHelp[action]); + SafeImGui.SetItemTooltip(ActionHelp[action]); if (r.Action is ChatRuleAction.Move or ChatRuleAction.Copy) { diff --git a/src/RynthCore.Engine/ImGui/Panels/DamageDetailFace.cs b/src/RynthCore.Engine/ImGui/Panels/DamageDetailFace.cs index 6c41020..5bfdeab 100644 --- a/src/RynthCore.Engine/ImGui/Panels/DamageDetailFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/DamageDetailFace.cs @@ -111,7 +111,7 @@ internal sealed class DamageDetailFace : IImGuiPanel // ── Header ─────────────────────────────────────────────────────── string name = d != null && d.Name.Length > 0 ? d.Name : _selectedName; ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); - ImGuiNET.ImGui.TextColored(Vec(Teal), isDefault ? "DEFAULT" : name); + SafeImGui.TextColored(Vec(Teal), isDefault ? "DEFAULT" : name); ImGuiNET.ImGui.PopFont(); if (isDefault) { @@ -123,17 +123,17 @@ internal sealed class DamageDetailFace : IImGuiPanel } else if (d == null) { - ImGuiNET.ImGui.TextColored(Vec(Dim), _detail != null && !_detail.Bound ? "Waiting for RynthAi…" : "Loading…"); + SafeImGui.TextColored(Vec(Dim), _detail != null && !_detail.Bound ? "Waiting for RynthAi…" : "Loading…"); } else { ImGuiNET.ImGui.SameLine(); - ImGuiNET.ImGui.TextColored(Vec(Dim), "wcid " + wcid.ToString(CultureInfo.InvariantCulture)); + SafeImGui.TextColored(Vec(Dim), "wcid " + wcid.ToString(CultureInfo.InvariantCulture)); // Aelrynth only: which difficulty tier these numbers are (the Damage panel's chip picks it). if (UiSources.Damage.Current?.Value.Tier is { Show: true } tier) { ImGuiNET.ImGui.SameLine(); - ImGuiNET.ImGui.TextColored(Vec(tier.View == tier.Current ? Teal : Gold), + SafeImGui.TextColored(Vec(tier.View == tier.Current ? Teal : Gold), tier.View <= 0 ? "· Tier 0 (real Dereth)" : "· Tier " + tier.View.ToString(CultureInfo.InvariantCulture)); ImGuiNET.ImGui.SetItemTooltip("HP, casts to kill, seconds per kill, hits and damage taken are this difficulty tier's.\n" + "Damage per cast and weaknesses are the same at every tier. Change it on the Damage panel."); @@ -141,7 +141,7 @@ internal sealed class DamageDetailFace : IImGuiPanel string hp = d.Hp > 0 ? $"HP {d.Hp:N0} ({d.HpSrc})" : "HP unknown"; string sec = d.SecKill > 0 ? $"{d.SecKill:0.0} s per kill" : "no timed kills yet"; string hit = d.HitRate >= 0 ? $"{d.HitRate * 100:0}% hits" : "no hits yet"; - ImGuiNET.ImGui.TextColored(Vec(White), $"{hp} · {sec} · {hit}"); + SafeImGui.TextColored(Vec(White), $"{hp} · {sec} · {hit}"); float bw = ImGuiNET.ImGui.CalcTextSize(RemoveLabel).X + 16; ImGuiNET.ImGui.SameLine(); @@ -153,7 +153,7 @@ internal sealed class DamageDetailFace : IImGuiPanel ImGuiNET.ImGui.SetItemTooltip("Take this monster off the Damage panel: its learned numbers and your settings for it. It comes back if you meet it again."); if (_confirmRemove) { - ImGuiNET.ImGui.TextColored(Vec(Gold), "Remove " + name + " and everything learned about it?"); + SafeImGui.TextColored(Vec(Gold), "Remove " + name + " and everything learned about it?"); ImGuiNET.ImGui.SameLine(); if (ImGuiNET.ImGui.SmallButton("Remove##yes")) { @@ -186,7 +186,7 @@ internal sealed class DamageDetailFace : IImGuiPanel Rule? rule = _rules?.FindRule(name); if (rule != null) _renaming = null; ImGuiNET.ImGui.PushTextWrapPos(0); - ImGuiNET.ImGui.TextColored(Vec(Dim), rule == null + SafeImGui.TextColored(Vec(Dim), rule == null ? (_rules == null || _renaming == name ? "Loading…" : "There is no rule with this name (deleted?).") : "A name rule: used for every monster whose name contains \"" + name + "\"" + (string.IsNullOrWhiteSpace(rule.MatchExpression) ? "" : " and its match expression is true") @@ -200,7 +200,7 @@ internal sealed class DamageDetailFace : IImGuiPanel _confirmRemove = true; ImGuiNET.ImGui.SetItemTooltip("Delete this rule. Monsters it covered go back to Default (or another rule that matches)."); if (!_confirmRemove) return; - ImGuiNET.ImGui.TextColored(Vec(Gold), "Delete the rule " + name + "?"); + SafeImGui.TextColored(Vec(Gold), "Delete the rule " + name + "?"); ImGuiNET.ImGui.SameLine(); if (ImGuiNET.ImGui.SmallButton("Delete##yes")) { @@ -232,7 +232,7 @@ internal sealed class DamageDetailFace : IImGuiPanel ImGuiNET.ImGui.TextColored(Vec(Dim), "Nothing known yet: not in the server data, no creature type, nothing learned."); return; } - ImGuiNET.ImGui.TextColored(Vec(Dim), "Damage it takes from each element (1.0 = full, 0.5 = half), from " + d.WeakSrc + "."); + SafeImGui.TextColored(Vec(Dim), "Damage it takes from each element (1.0 = full, 0.5 = half), from " + d.WeakSrc + "."); float labelW = ImGuiNET.ImGui.CalcTextSize("Lightning ").X; float barW = Math.Max(80, ImGuiNET.ImGui.GetContentRegionAvail().X - labelW - ImGuiNET.ImGui.CalcTextSize(" 0.00x").X - 8); double top = 1.0; @@ -351,9 +351,9 @@ internal sealed class DamageDetailFace : IImGuiPanel if (!nameRule) { - ImGuiNET.ImGui.TextColored(Vec(custom || isDefault ? Gold : Dim), + SafeImGui.TextColored(Vec(custom || isDefault ? Gold : Dim), isDefault ? "Applies to every monster set to Default." : custom ? "Custom settings for this monster." : "Following Default (a change here gives it its own settings)."); - ImGuiNET.ImGui.TextColored(Vec(Dim), DebuffsHint); + SafeImGui.TextColored(Vec(Dim), DebuffsHint); if (custom) { ImGuiNET.ImGui.SameLine(); @@ -404,6 +404,17 @@ 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%)."); + // Match expression (Default never matches by name, so it has none) if (!isDefault) { @@ -434,7 +445,7 @@ internal sealed class DamageDetailFace : IImGuiPanel { ImGuiNET.ImGui.SameLine(0, 10); ImGuiNET.ImGui.AlignTextToFramePadding(); - ImGuiNET.ImGui.TextColored(Vec(Dim), "casts " + casts + (view.UseRing ? ", Ring when enough are near" : "")); + SafeImGui.TextColored(Vec(Dim), "casts " + casts + (view.UseRing ? ", Ring when enough are near" : "")); ImGuiNET.ImGui.SetItemTooltip("With several shapes on, the first of Arc, Streak, Blast, Bolt is cast.\n" + "Ring replaces it when at least Min Ring Targets monsters are within Ring Range (Settings)."); } @@ -481,7 +492,7 @@ internal sealed class DamageDetailFace : IImGuiPanel private static void Combo(string label, string id, string[] items, string current, Action onPick, string tip) { ImGuiNET.ImGui.AlignTextToFramePadding(); - ImGuiNET.ImGui.TextColored(Vec(Dim), label); + SafeImGui.TextColored(Vec(Dim), label); ImGuiNET.ImGui.SameLine(); ImGuiNET.ImGui.SetNextItemWidth(ImGuiNET.ImGui.CalcTextSize("Dual wield").X + 34); if (ImGuiNET.ImGui.BeginCombo(id, current)) @@ -492,7 +503,7 @@ internal sealed class DamageDetailFace : IImGuiPanel onPick(v); ImGuiNET.ImGui.EndCombo(); } - ImGuiNET.ImGui.SetItemTooltip(tip); + SafeImGui.SetItemTooltip(tip); } private const string RemoveLabel = PhosphorIcons.Trash + " Remove monster"; @@ -501,7 +512,7 @@ internal sealed class DamageDetailFace : IImGuiPanel private static void ToggleRow(string label, (string Field, string Label, string Tip)[] defs, Rule view, string name) { - ImGuiNET.ImGui.TextColored(Vec(Dim), label); + SafeImGui.TextColored(Vec(Dim), label); float h = ImGuiNET.ImGui.GetFrameHeight(); foreach (var (field, text, tip) in defs) { @@ -513,7 +524,7 @@ internal sealed class DamageDetailFace : IImGuiPanel if (ImGuiNET.ImGui.InvisibleButton("##t_" + field, size)) DamageCommands.EditRule(name, rule => DamageCommands.FlipToggle(rule, field)); bool hot = ImGuiNET.ImGui.IsItemHovered(); - ImGuiNET.ImGui.SetItemTooltip(tip); + SafeImGui.SetItemTooltip(tip); var dl = ImGuiNET.ImGui.GetWindowDrawList(); dl.AddRectFilled(p, p + size, hot ? FaceKit.Lighten(EntryBg) : EntryBg, 2); dl.AddRect(p, p + size, EntryBorder, 2); @@ -540,7 +551,7 @@ internal sealed class DamageDetailFace : IImGuiPanel private static void Cell(string text) { ImGuiNET.ImGui.TableNextColumn(); - ImGuiNET.ImGui.TextColored(Vec(White), text); + SafeImGui.TextColored(Vec(White), text); } private static Vector4 Vec(uint abgr) => ImGuiNET.ImGui.ColorConvertU32ToFloat4(abgr); diff --git a/src/RynthCore.Engine/ImGui/Panels/DamageFace.cs b/src/RynthCore.Engine/ImGui/Panels/DamageFace.cs index 19e4110..a232515 100644 --- a/src/RynthCore.Engine/ImGui/Panels/DamageFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/DamageFace.cs @@ -459,7 +459,7 @@ internal sealed class DamageFace : IImGuiPanel OpenPicker(new Vector2(x, y + 22), t.Following ? FollowTier : (uint)t.View, id => DamageCommands.SetViewTier(id == FollowTier ? -1 : (int)id)); } - ImGuiNET.ImGui.SetItemTooltip( + SafeImGui.SetItemTooltip( "Aelrynth's awakened worlds and scaled dungeons have the same monsters, with " + $"{t.Percent.ToString("0.#", CultureInfo.InvariantCulture)}% more health, skills and damage per tier.\n" + "HP, kills, casts to kill, seconds per kill and hit rate here are this tier's; damage per cast,\n" + @@ -521,7 +521,7 @@ internal sealed class DamageFace : IImGuiPanel if (all == null || count == 0) { ImGuiNET.ImGui.Dummy(new Vector2(0, 3)); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D4E0), all == null + SafeImGui.TextColored(RynthTheme.Vec(0xFFC8D4E0), all == null ? " Monster rules not loaded yet." : " No name rules yet: add one below."); } else @@ -553,7 +553,7 @@ internal sealed class DamageFace : IImGuiPanel string name = r.Name; if (NameLink("##rn", name, new Vector2(p.X + 4, p.Y), nameW - 8, met ? White : Gold, ImGuiFonts.Get(UiFont.Ui11))) OpenRule(name); - ImGuiNET.ImGui.SetItemTooltip(met + SafeImGui.SetItemTooltip(met ? "This monster's own settings (wcid " + wcid.ToString(CultureInfo.InvariantCulture) + "). Click for its details." : "Click to edit this rule."); float x = p.X + nameW; @@ -570,7 +570,7 @@ internal sealed class DamageFace : IImGuiPanel { ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, p.Y)); ImGuiNET.ImGui.InvisibleButton("##rx", new Vector2(exprW, RowH)); - ImGuiNET.ImGui.SetItemTooltip("Match expression: " + r.MatchExpression); + SafeImGui.SetItemTooltip("Match expression: " + r.MatchExpression); } x += exprW; @@ -586,7 +586,7 @@ internal sealed class DamageFace : IImGuiPanel if (armed) { DamageCommands.ResetRule(name); _armedDelete = ""; } else _armedDelete = name; } - ImGuiNET.ImGui.SetItemTooltip(armed ? "Click again to delete " + name : "Delete this rule (click twice)"); + SafeImGui.SetItemTooltip(armed ? "Click again to delete " + name : "Delete this rule (click twice)"); ImGuiNET.ImGui.PopID(); ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + RowH)); @@ -680,7 +680,7 @@ internal sealed class DamageFace : IImGuiPanel SortShown(); } if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand); - ImGuiNET.ImGui.SetItemTooltip("Sort by " + Headers[c]); + SafeImGui.SetItemTooltip("Sort by " + Headers[c]); string label = Headers[c] + (_sortCol == c ? (_sortDesc ? SortDown : SortUp) : ""); dl.AddText(bold, bold.FontSize, new Vector2(p.X + ColX[c] + 4, p.Y + (RowH - bold.FontSize) * 0.5f), _sortCol == c ? Teal : White, label); @@ -708,7 +708,7 @@ internal sealed class DamageFace : IImGuiPanel bool filtering = _filterWid != 0 || _searchText.Length > 0; bool anyData = _view.Rows.Exists(r => !r.IsDefault); ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D4E0), anyData && filtering + SafeImGui.TextColored(RynthTheme.Vec(0xFFC8D4E0), anyData && filtering ? " No monsters match the current filter." : " No monsters yet: fight some and they show up here."); } @@ -782,7 +782,7 @@ internal sealed class DamageFace : IImGuiPanel if (NameLink("##name", t.NameShown, new Vector2(p.X + ColX[ColMonster] + 22, p.Y), ColW[ColMonster] - 24, custom ? Gold : White, ImGuiFonts.Get(UiFont.Ui11))) DamageDetailFace.Show(r.Wcid, r.Name); - ImGuiNET.ImGui.SetItemTooltip(t.NameTip); + SafeImGui.SetItemTooltip(t.NameTip); PrioCell(r.Key, r.Name, t.PrioCopyFrom, t, p); HpCell(r, p); @@ -792,7 +792,7 @@ internal sealed class DamageFace : IImGuiPanel dl.AddText(new Vector2(p.X + ColX[ColWeak] + 4, ty), White, Fit(t.WeakTop, ColW[ColWeak] - 8)); ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X + ColX[ColWeak], p.Y)); ImGuiNET.ImGui.InvisibleButton("##weak", new Vector2(ColW[ColWeak], RowH)); - ImGuiNET.ImGui.SetItemTooltip(r.Weak + "\nDamage taken: 1.0 = full, 0.5 = half. From " + r.WeakSrc + SafeImGui.SetItemTooltip(r.Weak + "\nDamage taken: 1.0 = full, 0.5 = half. From " + r.WeakSrc + ".\nAuto spells, weapons and summons use the first element this character has."); } else @@ -835,7 +835,7 @@ internal sealed class DamageFace : IImGuiPanel dl.AddText(new Vector2(p.X + ColX[ColSec] + 4, ty), r.SecKill > 0 ? White : Dim, t.Sec); ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X + ColX[ColSec], p.Y)); ImGuiNET.ImGui.InvisibleButton("##sec", new Vector2(ColW[ColSec], RowH)); - ImGuiNET.ImGui.SetItemTooltip(t.SecTip); + SafeImGui.SetItemTooltip(t.SecTip); DebuffCell(r.Name, p, ty); @@ -845,7 +845,7 @@ internal sealed class DamageFace : IImGuiPanel _removeName = r.Name; _removeOpen = true; } - ImGuiNET.ImGui.SetItemTooltip("Remove " + r.Name + " from this list (asks first)."); + SafeImGui.SetItemTooltip("Remove " + r.Name + " from this list (asks first)."); ImGuiNET.ImGui.PopID(); ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + RowH)); @@ -961,7 +961,7 @@ internal sealed class DamageFace : IImGuiPanel WriteUtf8(_customBuf, view.CustomDebuffs ?? ""); _debuffOpen = true; } - ImGuiNET.ImGui.SetItemTooltip("Debuffs to cast on " + name); + SafeImGui.SetItemTooltip("Debuffs to cast on " + name); if (view == null) return; string marks = DamageCommands.DebuffMarks(view); var dl = ImGuiNET.ImGui.GetWindowDrawList(); @@ -970,7 +970,7 @@ internal sealed class DamageFace : IImGuiPanel { ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(bp.X + 22, p.Y)); ImGuiNET.ImGui.InvisibleButton("##dmarks", new Vector2(Math.Max(1, ColW[ColDebuffs] - 26), RowH)); - ImGuiNET.ImGui.SetItemTooltip(DebuffTip(view)); + SafeImGui.SetItemTooltip(DebuffTip(view)); } } @@ -1006,7 +1006,7 @@ internal sealed class DamageFace : IImGuiPanel Rule? view = RuleFor(name, out bool custom); bool isDefault = name.Equals("Default", StringComparison.OrdinalIgnoreCase); ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), "Debuffs · " + name); + SafeImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), "Debuffs · " + name); ImGuiNET.ImGui.PopFont(); if (view == null) { @@ -1015,7 +1015,7 @@ internal sealed class DamageFace : IImGuiPanel return; } ImGuiNET.ImGui.PushTextWrapPos(0); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(custom || isDefault ? 0xFFFFD16A : 0xFFC8D4E0), + SafeImGui.TextColored(RynthTheme.Vec(custom || isDefault ? 0xFFFFD16A : 0xFFC8D4E0), isDefault ? "Every monster set to Default uses these." : custom ? "This monster's own debuffs." : "Following Default: a change here gives it its own."); ImGuiNET.ImGui.PopTextWrapPos(); @@ -1028,7 +1028,7 @@ internal sealed class DamageFace : IImGuiPanel string f = field; DamageCommands.EditRule(name, rule => rule.SetToggle(f, v)); } - ImGuiNET.ImGui.SetItemTooltip(tip); + SafeImGui.SetItemTooltip(tip); } ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D4E0), "Extra Vuln"); @@ -1167,7 +1167,7 @@ internal sealed class DamageFace : IImGuiPanel bool commit = enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit(); ImGuiNET.ImGui.PopStyleVar(); ImGuiNET.ImGui.PopStyleColor(2); - ImGuiNET.ImGui.SetItemTooltip(t.PrioTip + "\nType a number, Enter to save."); + SafeImGui.SetItemTooltip(t.PrioTip + "\nType a number, Enter to save."); if (!commit) return; if (int.TryParse(Utf8(e.Buffer).Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int typed)) @@ -1316,7 +1316,7 @@ internal sealed class DamageFace : IImGuiPanel if (ropen) { ImGuiNET.ImGui.PushTextWrapPos(0); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), "Remove " + _removeName + "?"); + SafeImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), "Remove " + _removeName + "?"); ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), "Its learned numbers and your settings for it (weapon, offhand, pet, HP) are deleted. It comes back if you meet it again."); diff --git a/src/RynthCore.Engine/ImGui/Panels/DamageTypeColors.cs b/src/RynthCore.Engine/ImGui/Panels/DamageTypeColors.cs new file mode 100644 index 0000000..dbcaf67 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/DamageTypeColors.cs @@ -0,0 +1,32 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/DamageTypeColors.cs +// Text colour per damage type, from UB-ILT's LeaftideDamageTypeVtColors (the +// Virindi Tank / Leaftide label palette its Items, Spell and Pets tabs share). +// RynthAi's Pets roster uses the same values (IltHub\IltDamageTypeTint.cs); +// keep the two tables in step. Colours are the panels' ABGR (RynthTheme.Argb). +// ============================================================================ + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal static class DamageTypeColors +{ + private static uint C(uint argb) => RynthTheme.Argb(argb); + + public static readonly uint Slash = C(0xFFFFB478), Pierce = C(0xFFF0C88C), Bludgeon = C(0xFFDCBE8C), + Cold = C(0xFFA0D2FF), Fire = C(0xFFFF8246), Acid = C(0xFFA0FF8C), Lightning = C(0xFFFFF078), + Nether = C(0xFFC8A0FF); + + /// Colour for an element name as the panels write it; for anything else (Shield, Auto, None). + public static uint For(string? element, uint fallback) => element switch + { + "Slash" or "Slashing" => Slash, + "Pierce" or "Piercing" => Pierce, + "Bludgeon" or "Bludgeoning" => Bludgeon, + "Cold" or "Frost" => Cold, + "Fire" => Fire, + "Acid" => Acid, + "Lightning" or "Electric" or "Storm" => Lightning, + "Nether" => Nether, + _ => fallback, + }; +} diff --git a/src/RynthCore.Engine/ImGui/Panels/DashboardDrawers.cs b/src/RynthCore.Engine/ImGui/Panels/DashboardDrawers.cs index 068c419..173c84c 100644 --- a/src/RynthCore.Engine/ImGui/Panels/DashboardDrawers.cs +++ b/src/RynthCore.Engine/ImGui/Panels/DashboardDrawers.cs @@ -103,7 +103,7 @@ internal abstract class DashboardDrawer if (FaceKit.IconButton("##drawer_close", PhosphorIcons.X, new Vector2(x + w - closeSize.X, y + (th - closeSize.Y) * 0.5f), closeSize, DMute, DBtnFill, border: DBtnBord, font: UiFont.Dash10)) Close(); - ImGuiNET.ImGui.SetItemTooltip(closeTip); + SafeImGui.SetItemTooltip(closeTip); return y + th + 4 * k; } } @@ -306,7 +306,7 @@ internal sealed class DashboardDrawers bool hot = ImGuiNET.ImGui.IsItemHovered(); // Like SetItemTooltip (same delay), but the closed tooltip is only built while it shows. if (ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.ForTooltip)) - ImGuiNET.ImGui.SetTooltip(open ? d.HideTip : d.TabTooltip(right)); + SafeImGui.SetTooltip(open ? d.HideTip : d.TabTooltip(right)); if (clicked) Toggle(d); uint fill = ImGuiNET.ImGui.IsItemActive() ? FaceKit.Darken(BtnFill) : hot ? FaceKit.Lighten(BtnFill) : BtnFill; diff --git a/src/RynthCore.Engine/ImGui/Panels/DungeonMapFace.cs b/src/RynthCore.Engine/ImGui/Panels/DungeonMapFace.cs index 53893c9..fcb8f8b 100644 --- a/src/RynthCore.Engine/ImGui/Panels/DungeonMapFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/DungeonMapFace.cs @@ -878,7 +878,7 @@ internal sealed class DungeonMapFace : IImGuiPanel return; } int i = _menuPt; - ImGuiNET.ImGui.TextDisabled($"Point {i} {TypeName(nav.Points[i].Type)}"); + SafeImGui.TextDisabled($"Point {i} {TypeName(nav.Points[i].Type)}"); ImGuiNET.ImGui.Separator(); if (ImGuiNET.ImGui.MenuItem("Delete")) { diff --git a/src/RynthCore.Engine/ImGui/Panels/HotkeysSettingsUi.cs b/src/RynthCore.Engine/ImGui/Panels/HotkeysSettingsUi.cs index 2ffcf5e..067f700 100644 --- a/src/RynthCore.Engine/ImGui/Panels/HotkeysSettingsUi.cs +++ b/src/RynthCore.Engine/ImGui/Panels/HotkeysSettingsUi.cs @@ -135,7 +135,7 @@ internal sealed class HotkeysSettingsUi ImGuiNET.ImGui.SetCursorScreenPos(p); if (ImGuiNET.ImGui.InvisibleButton("##on", new Vector2(14, 16))) HotkeyService.Replace(i, b with { Enabled = !b.Enabled }); - ImGuiNET.ImGui.SetItemTooltip(b.Enabled ? "On. Click to switch this hotkey off." : "Off. Click to switch this hotkey on."); + SafeImGui.SetItemTooltip(b.Enabled ? "On. Click to switch this hotkey off." : "Off. Click to switch this hotkey on."); dl.AddRectFilled(p + new Vector2(0, 2), p + new Vector2(12, 14), b.Enabled ? ToggleOn : ToggleOff, 2); dl.AddText(bold, bold.FontSize, p + new Vector2(18, 1), b.Enabled ? Amber : Mute, b.Combo.ToString()); @@ -147,7 +147,7 @@ internal sealed class HotkeysSettingsUi // The full text on hover (a long chat command is clipped). ImGuiNET.ImGui.SetCursorScreenPos(p + new Vector2(18, 0)); ImGuiNET.ImGui.InvisibleButton("##what", new Vector2(Math.Max(1, textRight - p.X - 18), rowH)); - ImGuiNET.ImGui.SetItemTooltip(b.Combo + ": " + what + (b.Enabled ? "" : " (off)")); + SafeImGui.SetItemTooltip(b.Combo + ": " + what + (b.Enabled ? "" : " (off)")); float x = p.X + w - 4 * 20; if (IconButton("##up", new Vector2(x, p.Y), PhosphorIcons.CaretUp, i > 0)) @@ -231,7 +231,7 @@ internal sealed class HotkeysSettingsUi else { HotkeyService.BeginCapture(); _waitingForKey = true; } } ImGuiNET.ImGui.PopStyleColor(); - ImGuiNET.ImGui.SetItemTooltip(_waitingForKey ? "Waiting for a key. Click again or press Esc to stop." : "Click, then press the key combination."); + SafeImGui.SetItemTooltip(_waitingForKey ? "Waiting for a key. Click again or press Esc to stop." : "Click, then press the key combination."); if (_waitingForKey && HotkeyService.CaptureNote.Length > 0) Warning(HotkeyService.CaptureNote, w); @@ -250,7 +250,7 @@ internal sealed class HotkeysSettingsUi ImGuiNET.ImGui.PushStyleColor(ImGuiCol.FrameBg, BtnFill); bool open = ImGuiNET.ImGui.BeginCombo("##action", current, ImGuiComboFlags.HeightLarge); ImGuiNET.ImGui.PopStyleColor(3); - if (!open && picked is { Tip.Length: > 0 }) ImGuiNET.ImGui.SetItemTooltip(picked.Tip); + if (!open && picked is { Tip.Length: > 0 }) SafeImGui.SetItemTooltip(picked.Tip); if (open) { if (ImGuiNET.ImGui.Selectable(ChatCommandItem, isCommand)) _editAction = HotkeyActions.Command; @@ -275,7 +275,7 @@ internal sealed class HotkeysSettingsUi if (ImGuiNET.ImGui.Selectable((a.Group.Length > 0 ? " " : "") + a.Name + "##" + a.Id, string.Equals(a.Id, _editAction, StringComparison.OrdinalIgnoreCase))) _editAction = a.Id; - if (a.Tip.Length > 0) ImGuiNET.ImGui.SetItemTooltip(a.Tip); + if (a.Tip.Length > 0) SafeImGui.SetItemTooltip(a.Tip); } ImGuiNET.ImGui.EndCombo(); } @@ -326,7 +326,7 @@ internal sealed class HotkeysSettingsUi } ImGuiNET.ImGui.EndDisabled(); if (ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled)) - ImGuiNET.ImGui.SetTooltip(!canSave + SafeImGui.SetTooltip(!canSave ? (_editCombo.IsEmpty || _waitingForKey ? "Pick a key first." : !paramOk ? $"Pick the {picked?.Param?.ToLowerInvariant() ?? "value"} first." : "Type the chat command (starting with /).") @@ -361,7 +361,7 @@ internal sealed class HotkeysSettingsUi bool typing = ImGuiNET.ImGui.IsItemActive(); ImGuiNET.ImGui.PopStyleVar(); ImGuiNET.ImGui.PopStyleColor(3); - ImGuiNET.ImGui.SetItemTooltip(meta ? "The state's name, as in the meta (the case doesn't matter)." : a.Tip); + SafeImGui.SetItemTooltip(meta ? "The state's name, as in the meta (the case doesn't matter)." : a.Tip); if (states.Count > 0) { diff --git a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.AttrFilter.cs b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.AttrFilter.cs index f8dd9f9..b2a46d8 100644 --- a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.AttrFilter.cs +++ b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.AttrFilter.cs @@ -126,7 +126,7 @@ internal sealed partial class InventoryFace : "Filter by item attributes (armor level, ratings, spells, slot...)"; if (on && _unidentified.Count > 0) tip += "\n" + _unidentified.Count.ToString(CultureInfo.InvariantCulture) + " hidden until identified."; - ImGuiNET.ImGui.SetTooltip(tip); + SafeImGui.SetTooltip(tip); } // ── The editor popup ──────────────────────────────────────────────── @@ -257,11 +257,11 @@ internal sealed partial class InventoryFace InventoryAttributeFilter.SetAttr(rule, a.Id); AttrChanged(); } - ImGuiNET.ImGui.SetItemTooltip(a.Tip); + SafeImGui.SetItemTooltip(a.Tip); } ImGuiNET.ImGui.EndCombo(); } - ImGuiNET.ImGui.SetItemTooltip(info.Tip); + SafeImGui.SetItemTooltip(info.Tip); info = InventoryAttributeFilter.Info(rule.Attr); ImGuiNET.ImGui.SameLine(); diff --git a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs index 7fa456f..8b60e2d 100644 --- a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs +++ b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.Classic.cs @@ -238,10 +238,10 @@ internal sealed partial class InventoryFace var bMinus = new Vector2(bPlus.X - btn - 2 * s, b2.Y); if (TitleToggle("##inv_smaller", PhosphorIcons.Minus, bMinus, btn, false)) InventorySettingsStore.StepSize(-1); - ImGuiNET.ImGui.SetItemTooltip($"Smaller ({InventorySettingsStore.SizePct}%)"); + SafeImGui.SetItemTooltip($"Smaller ({InventorySettingsStore.SizePct}%)"); if (TitleToggle("##inv_bigger", PhosphorIcons.Plus, bPlus, btn, false)) InventorySettingsStore.StepSize(+1); - ImGuiNET.ImGui.SetItemTooltip($"Bigger ({InventorySettingsStore.SizePct}%)"); + SafeImGui.SetItemTooltip($"Bigger ({InventorySettingsStore.SizePct}%)"); if (TitleToggle("##inv_tools", PhosphorIcons.Funnel, b1, btn, InventorySettingsStore.ShowTools)) { // Closing the search / filter row shows every item again. @@ -729,7 +729,7 @@ internal sealed partial class InventoryFace if (hovered && hoverCell >= 0 && hoverCell < items.Length) { VaultItem hot = items[hoverCell]; - ImGuiNET.ImGui.SetTooltip(hot.Stack > 1 ? $"{hot.Name} ({hot.Stack:N0})" : hot.Name); + SafeImGui.SetTooltip(hot.Stack > 1 ? $"{hot.Name} ({hot.Stack:N0})" : hot.Name); if (ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Right)) { _vaultCtx = hot; @@ -753,7 +753,7 @@ internal sealed partial class InventoryFace if (it == null) ImGuiNET.ImGui.CloseCurrentPopup(); else { - ImGuiNET.ImGui.TextDisabled(it.Name); + SafeImGui.TextDisabled(it.Name); ImGuiNET.ImGui.Separator(); if (ImGuiNET.ImGui.MenuItem("Withdraw", "", false, VaultFeed.Available)) VaultFeed.Withdraw(it); diff --git a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.MultiSelect.cs b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.MultiSelect.cs index 05431fe..1e275cd 100644 --- a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.MultiSelect.cs +++ b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.MultiSelect.cs @@ -228,8 +228,8 @@ internal sealed partial class InventoryFace ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Amber); ImGuiNET.ImGui.TextUnformatted(_confirmTitle); ImGuiNET.ImGui.PopStyleColor(); - foreach (string line in _confirmNames) ImGuiNET.ImGui.BulletText(line); - if (_confirmNote.Length > 0) ImGuiNET.ImGui.TextDisabled(_confirmNote); + foreach (string line in _confirmNames) SafeImGui.BulletText(line); + if (_confirmNote.Length > 0) SafeImGui.TextDisabled(_confirmNote); if (_confirmItems.Length > 0 && _confirmItems[0].Kind == InventoryActionKind.Give) ImGuiNET.ImGui.TextDisabled("Given items can't be taken back."); @@ -287,7 +287,7 @@ internal sealed partial class InventoryFace bool idle = InventoryModel.Pending == null && !InventoryModel.BatchRunning; InventoryTarget? target = InventoryModel.Target; RefreshSelectionLabels(target); - ImGuiNET.ImGui.TextDisabled(_menuCount); + SafeImGui.TextDisabled(_menuCount); ImGuiNET.ImGui.Separator(); if (ImGuiNET.ImGui.MenuItem(_menuDrop, "", false, idle && InventoryModel.DropAvailable)) GroupAction(DropKind.Drop, 0, string.Empty); diff --git a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs index c001ab0..1714618 100644 --- a/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/InventoryFace.cs @@ -220,7 +220,7 @@ internal sealed partial class InventoryFace : IImGuiPanel float bw = ImGuiNET.ImGui.CalcTextSize(view.BurdenText).X; ImGuiNET.ImGui.SetCursorScreenPos(p); ImGuiNET.ImGui.InvisibleButton("##burden", new Vector2(x + bw - p.X, RowH)); - ImGuiNET.ImGui.SetItemTooltip(view.BurdenTip); + SafeImGui.SetItemTooltip(view.BurdenTip); x += bw + 16; PhosphorIcons.DrawCentered(dl, icons, PhosphorIcons.Coins, new Vector2(x, p.Y), new Vector2(18, RowH), Amber); @@ -654,7 +654,7 @@ internal sealed partial class InventoryFace : IImGuiPanel ImGuiNET.ImGui.SetCursorScreenPos(pos); bool clicked = ImGuiNET.ImGui.InvisibleButton(id, size); bool hot = ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenBlockedByActiveItem); - ImGuiNET.ImGui.SetItemTooltip(tip); + SafeImGui.SetItemTooltip(tip); // the Give zone's tip carries the target's name bool dropHot = enabled && _dragItem != null && hot; var dl = ImGuiNET.ImGui.GetWindowDrawList(); uint fill = dropHot ? DropHot : _dragItem != null && enabled ? Selected : hot && enabled ? Lighten(BtnFill) : BtnFill; @@ -1019,7 +1019,7 @@ internal sealed partial class InventoryFace : IImGuiPanel if (it == null) { ImGuiNET.ImGui.CloseCurrentPopup(); return; } if (IsGroup(it)) { GroupMenu(view, it); return; } bool idle = InventoryModel.Pending == null && !InventoryModel.BatchRunning; - ImGuiNET.ImGui.TextDisabled(it.Name); + SafeImGui.TextDisabled(it.Name); ImGuiNET.ImGui.Separator(); if (ImGuiNET.ImGui.MenuItem("Use", "double-click", false, idle)) Act(InventoryActionKind.Use, it, 0, "", 0); diff --git a/src/RynthCore.Engine/ImGui/Panels/ItemCountFace.cs b/src/RynthCore.Engine/ImGui/Panels/ItemCountFace.cs index 72f5d93..af0c291 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ItemCountFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ItemCountFace.cs @@ -112,7 +112,7 @@ internal sealed class ItemCountFace : IImGuiPanel { if (ItemHudMath.TryFind(items, sel, out HudItem it)) Add(it.Name); } - ImGuiNET.ImGui.SetItemTooltip(haveSel ? "Count the selected item" : "Select an item in your inventory to count it (or drag one onto this panel)"); + SafeImGui.SetItemTooltip(haveSel ? "Count the selected item" : "Select an item in your inventory to count it (or drag one onto this panel)"); NextLine(start, h + 4); } @@ -183,7 +183,7 @@ internal sealed class ItemCountFace : IImGuiPanel ImGuiNET.ImGui.PushID(i); ImGuiNET.ImGui.InvisibleButton("##row", new Vector2(bw - XW, RowH)); bool hot = ImGuiNET.ImGui.IsItemHovered(); - if (hot) ImGuiNET.ImGui.SetItemTooltip($"{data.Counts[i]}: {_countText[i]} carried"); + if (hot) SafeImGui.SetItemTooltip($"{data.Counts[i]}: {_countText[i]} carried"); ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X + bw - XW, p.Y)); if (ImGuiNET.ImGui.InvisibleButton("##x", new Vector2(XW, RowH))) remove = i; bool hotX = ImGuiNET.ImGui.IsItemHovered(); diff --git a/src/RynthCore.Engine/ImGui/Panels/ItemsFace.cs b/src/RynthCore.Engine/ImGui/Panels/ItemsFace.cs index 95e3e43..81f53df 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ItemsFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ItemsFace.cs @@ -71,7 +71,7 @@ internal sealed class ItemsFace : IImGuiPanel { ItemsPanel.WeaponEntry wpn = _data.Weapons[i]; ImGuiNET.ImGui.PushID("w" + i); - int r = Row(wpn.Name, wpn.Element, i, bw, _data.MissingIds.Contains(wpn.Id)); + int r = Row(wpn.Name, wpn.Element, i, bw, _data.MissingIds.Contains(wpn.Id), DamageTypeColors.For(wpn.Element, Text)); ImGuiNET.ImGui.PopID(); if (r == 1) { @@ -103,7 +103,7 @@ 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, Text); ImGuiNET.ImGui.PopID(); if (r == 1) { @@ -214,9 +214,10 @@ internal sealed class ItemsFace : IImGuiPanel /// /// Name | [value picker] | Del. Returns 1 when the picker was clicked, 2 for Del, else 0. /// : the item isn't carried any more (amber, a warning icon, - /// "(missing)" and a tooltip saying what to do). + /// "(missing)" and a tooltip saying what to do). Otherwise the name and value are drawn in + /// (a weapon's damage-type colour, as UB-ILT's Items tab). /// - 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, uint tint) { Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); var dl = ImGuiNET.ImGui.GetWindowDrawList(); @@ -235,14 +236,14 @@ internal sealed class ItemsFace : IImGuiPanel } else { - dl.AddText(new Vector2(p.X + 6, ty), Text, name); + dl.AddText(new Vector2(p.X + 6, ty), tint, name); } dl.PopClipRect(); if (missing && ImGuiNET.ImGui.IsWindowHovered() && ImGuiNET.ImGui.IsMouseHoveringRect(p, p + new Vector2(nameW, 24))) - ImGuiNET.ImGui.SetTooltip("Not in your pack any more - select the item in your inventory and click\n" + SafeImGui.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 (Button("##pick", value, new Vector2(p.X + nameW + 2, p.Y + 2), new Vector2(96, 20), tint, 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; ImGuiNET.ImGui.SetItemTooltip("Remove"); NextLine(p, 24); @@ -254,7 +255,7 @@ internal sealed class ItemsFace : IImGuiPanel Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos() + new Vector2(4, 4); float bw = ButtonWidth(label) + 4; if (Button(id, label, p, new Vector2(bw, 24), Teal, BtnFill)) onClick(); - if (tooltip != null) ImGuiNET.ImGui.SetItemTooltip(tooltip); + if (tooltip != null) SafeImGui.SetItemTooltip(tooltip); ImFontPtr f9 = ImGuiFonts.Get(UiFont.Ui9); ImGuiNET.ImGui.GetWindowDrawList().AddText(f9, f9.FontSize, new Vector2(p.X + bw + 8, p.Y + (24 - f9.FontSize) * 0.5f), Mute, hint); NextLine(new Vector2(p.X - 4, p.Y - 4), 32); diff --git a/src/RynthCore.Engine/ImGui/Panels/LootAddDialog.cs b/src/RynthCore.Engine/ImGui/Panels/LootAddDialog.cs index a0fe2b2..8e3bd8b 100644 --- a/src/RynthCore.Engine/ImGui/Panels/LootAddDialog.cs +++ b/src/RynthCore.Engine/ImGui/Panels/LootAddDialog.cs @@ -243,7 +243,7 @@ internal sealed class LootAddDialog ImGuiNET.ImGui.TextDisabled("Profile:"); ImGuiNET.ImGui.SameLine(); ImGuiNET.ImGui.TextUnformatted(d.TargetFile + (d.TargetInUse ? " (in use)" : " (not the one RynthAi loots with)")); - if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(d.TargetPath); + if (ImGuiNET.ImGui.IsItemHovered()) SafeImGui.SetTooltip(d.TargetPath); } bool changed = false; @@ -257,7 +257,7 @@ internal sealed class LootAddDialog _match = i; changed = true; } - if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(MatchTips[i]); + if (ImGuiNET.ImGui.IsItemHovered()) SafeImGui.SetTooltip(MatchTips[i]); } // T11 attributes. Shown for every item: a non-T11 item answers with a note saying so. @@ -268,7 +268,7 @@ internal sealed class LootAddDialog changed = true; } if (ImGuiNET.ImGui.IsItemHovered()) - ImGuiNET.ImGui.SetTooltip( + 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" + @@ -306,7 +306,7 @@ internal sealed class LootAddDialog changed = true; } ImGuiNET.ImGui.SameLine(); - ImGuiNET.ImGui.TextDisabled(d.Stackable ? "(counts stack sizes)" : "(items)"); + SafeImGui.TextDisabled(d.Stackable ? "(counts stack sizes)" : "(items)"); } // Name. @@ -316,7 +316,7 @@ internal sealed class LootAddDialog ImGuiNET.ImGui.InputText("##la_name", _name, (uint)_name.Length); if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) changed = true; if (Utf8(_name).Trim().Length == 0 && d.DefaultRuleName.Length > 0) - ImGuiNET.ImGui.TextDisabled("Left empty, the rule is named \"" + d.DefaultRuleName + "\"."); + SafeImGui.TextDisabled("Left empty, the rule is named \"" + d.DefaultRuleName + "\"."); // Preview. ImGuiNET.ImGui.Separator(); @@ -360,7 +360,7 @@ internal sealed class LootAddDialog Send("item_add"); } if (ImGuiNET.ImGui.IsItemHovered()) - ImGuiNET.ImGui.SetTooltip(d.InsertAt >= 0 + SafeImGui.SetTooltip(d.InsertAt >= 0 ? $"Insert at {d.InsertAt + 1} of {d.RuleCount + 1}, save {d.TargetFile} (old file kept as .bak) and reload it" : "Add the rule"); if (Button("##la_cancel", "Cancel", bp + new Vector2(116, 0), new Vector2(80, 24), Text, BtnFill)) diff --git a/src/RynthCore.Engine/ImGui/Panels/LootEditorFace.cs b/src/RynthCore.Engine/ImGui/Panels/LootEditorFace.cs index f7fca3a..f05523f 100644 --- a/src/RynthCore.Engine/ImGui/Panels/LootEditorFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/LootEditorFace.cs @@ -393,7 +393,7 @@ internal sealed class LootEditorFace : IImGuiPanel if (i >= 0 && i < s.Files.Count) RequestOpen(s.Files[i].Path); }, Math.Max(260, pickW)); } - ImGuiNET.ImGui.SetItemTooltip(s.Path.Length == 0 ? "Pick a loot profile" : s.Path); + SafeImGui.SetItemTooltip(s.Path.Length == 0 ? "Pick a loot profile" : s.Path); PhosphorIcons.DrawCentered(ImGuiNET.ImGui.GetWindowDrawList(), ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.CaretDown, new Vector2(p.X + pickW - 18, p.Y), new Vector2(16, h), Mute); @@ -410,12 +410,12 @@ internal sealed class LootEditorFace : IImGuiPanel if (Button("##save", PhosphorIcons.FloppyDisk + " Save", new Vector2(x, p.Y), new Vector2(saveW, h), canSave ? Green : Mute, canSave ? StartBg : BtnFill, canSave)) Save(force: false); - ImGuiNET.ImGui.SetItemTooltip(_saveTip); + SafeImGui.SetItemTooltip(_saveTip); x += saveW + 4; if (IconButton("##external", PhosphorIcons.ArrowSquareOut, new Vector2(x, p.Y), new Vector2(icon, h), Text, BtnFill)) LaunchExternal(s.Path.Length > 0 ? s.Path : s.InUsePath); - ImGuiNET.ImGui.SetItemTooltip(s.Dirty + SafeImGui.SetItemTooltip(s.Dirty ? "Open external editor (it reads the file on disk: save first to take your edits)" : "Open external editor"); NextLine(p, h + 4); @@ -455,7 +455,7 @@ internal sealed class LootEditorFace : IImGuiPanel var b = new Vector2(x + ts.X + 12, y + h - 1); dl.AddRect(a, b, color, 8); dl.AddText(new Vector2(x + 6, y + (h - ts.Y) * 0.5f), color, text); - if (ImGuiNET.ImGui.IsMouseHoveringRect(a, b) && tooltip.Length > 0) ImGuiNET.ImGui.SetTooltip(tooltip); + if (ImGuiNET.ImGui.IsMouseHoveringRect(a, b) && tooltip.Length > 0) SafeImGui.SetTooltip(tooltip); return b.X + 6; } @@ -650,7 +650,7 @@ internal sealed class LootEditorFace : IImGuiPanel LootEditCommands.Simple("set_enabled", index, r.Enabled ? "false" : "true", expect: r.Name); changed = true; } - ImGuiNET.ImGui.SetItemTooltip(r.Enabled ? "Enabled: click to disable" : "Disabled: click to enable"); + SafeImGui.SetItemTooltip(r.Enabled ? "Enabled: click to disable" : "Disabled: click to enable"); x += 20; // Action badge @@ -675,7 +675,7 @@ internal sealed class LootEditorFace : IImGuiPanel Expect(Await.ScrollFocus); changed = true; } - ImGuiNET.ImGui.SetItemTooltip(reorder ? "Move up" : Filtering ? "Clear the search and filter to reorder" : "Move up"); + SafeImGui.SetItemTooltip(reorder ? "Move up" : Filtering ? "Clear the search and filter to reorder" : "Move up"); bx += 18; if (IconButton("##dn", PhosphorIcons.ArrowDown, new Vector2(bx, p.Y + 2), new Vector2(16, 16), Mute, BtnFill, reorder && index < s.Rules.Count - 1, font: UiFont.Ui11)) @@ -684,7 +684,7 @@ internal sealed class LootEditorFace : IImGuiPanel Expect(Await.ScrollFocus); changed = true; } - ImGuiNET.ImGui.SetItemTooltip(reorder ? "Move down" : Filtering ? "Clear the search and filter to reorder" : "Move down"); + SafeImGui.SetItemTooltip(reorder ? "Move down" : Filtering ? "Clear the search and filter to reorder" : "Move down"); bx += 18; if (IconButton("##dup", PhosphorIcons.Copy, new Vector2(bx, p.Y + 2), new Vector2(16, 16), Mute, BtnFill, !ro, font: UiFont.Ui11)) { @@ -710,7 +710,7 @@ internal sealed class LootEditorFace : IImGuiPanel { ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand); dl.AddRect(new Vector2(x - 2, p.Y), new Vector2(x + textW, p.Y + RowH), BtnBord, 2); - ImGuiNET.ImGui.SetTooltip((r.Name.Length == 0 ? "(no name)" : r.Name) + "\n" + r.Summary); + SafeImGui.SetTooltip((r.Name.Length == 0 ? "(no name)" : r.Name) + "\n" + r.Summary); } ImGuiNET.ImGui.PopID(); @@ -754,7 +754,7 @@ internal sealed class LootEditorFace : IImGuiPanel bool canItem = s.Path.Length > 0 && !s.Dirty && (!s.ReadOnly || s.Format == "json"); if (Button("##add_item", itemLabel, new Vector2(p.X + addW + 6, p.Y), new Vector2(itemW, h), canItem ? Teal : Mute, BtnFill, canItem)) _lootAdd.Open(0, string.Empty, toOpenProfile: true); - ImGuiNET.ImGui.SetItemTooltip(canItem + SafeImGui.SetItemTooltip(canItem ? "A rule for the item selected in the game (click it first): preview, then add it here" : s.Dirty ? "Save or discard your edits first" : "This profile is read-only here"); addW += itemW + 6; @@ -769,7 +769,7 @@ internal sealed class LootEditorFace : IImGuiPanel dl.PushClipRect(at, new Vector2(Math.Max(at.X + 1, right), at.Y + h), true); dl.AddText(new Vector2(at.X, at.Y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), _msgOk ? Green : Red, _msg); dl.PopClipRect(); - if (ImGuiNET.ImGui.IsMouseHoveringRect(at, new Vector2(right, at.Y + h))) ImGuiNET.ImGui.SetTooltip(_msg); + if (ImGuiNET.ImGui.IsMouseHoveringRect(at, new Vector2(right, at.Y + h))) SafeImGui.SetTooltip(_msg); } // ===================================================================== @@ -1017,7 +1017,7 @@ internal sealed class LootEditorFace : IImGuiPanel { if (!_rawShown.Remove(i)) _rawShown.Add(i); } - ImGuiNET.ImGui.SetItemTooltip(rawToggle ? "Show the raw data lines (any key id, any value)" : "This condition is edited as raw lines"); + SafeImGui.SetItemTooltip(rawToggle ? "Show the raw data lines (any key id, any value)" : "This condition is edited as raw lines"); tx += 18; int result = 0; int prev = PrevVisible(r, i), next = NextVisible(r, i); @@ -1105,7 +1105,7 @@ internal sealed class LootEditorFace : IImGuiPanel string hint = node.Labels.Count > 0 ? node.Labels[0].ToLowerInvariant() : "value"; if (Field("##val", FieldFor(i, 0), c.Lines[0], new Vector2(p.X + kw + 2, p.Y), w - kw - 2, hint, ro, out string v, h)) c.Lines[0] = v; - ImGuiNET.ImGui.SetItemTooltip(node.Labels.Count > 0 ? node.Labels[0] : "Value"); + SafeImGui.SetItemTooltip(node.Labels.Count > 0 ? node.Labels[0] : "Value"); break; } case "keypattern": @@ -1153,7 +1153,7 @@ internal sealed class LootEditorFace : IImGuiPanel ClearFields(); }, Math.Max(220, w)); } - ImGuiNET.ImGui.SetItemTooltip(sel >= 0 ? table.Names[sel] : "Not in the list: use the raw lines button to type any id"); + SafeImGui.SetItemTooltip(sel >= 0 ? table.Names[sel] : "Not in the list: use the raw lines button to type any id"); } /// The value names for this condition's long key, or null (no table, or a RynthAi that sends none). @@ -1185,7 +1185,7 @@ internal sealed class LootEditorFace : IImGuiPanel } string tip = sel >= 0 ? table.Items[sel] : "Not in the list: pick \"" + OtherNumber + "\" to type any number"; if (table.Flags) tip += "\nFlags: other combinations are typed as a number"; - ImGuiNET.ImGui.SetItemTooltip(tip); + SafeImGui.SetItemTooltip(tip); } /// A whole number: "45", "45.0" (a buffed-long value written as a double). diff --git a/src/RynthCore.Engine/ImGui/Panels/LuaFace.cs b/src/RynthCore.Engine/ImGui/Panels/LuaFace.cs index 840d2ec..700bbb2 100644 --- a/src/RynthCore.Engine/ImGui/Panels/LuaFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/LuaFace.cs @@ -176,7 +176,7 @@ internal sealed class LuaFace : IImGuiPanel dl.AddText(new Vector2(x + runW + sepW, ty), ai ? Green : Amber, aiText); dl.PopClipRect(); if (ImGuiNET.ImGui.IsMouseHoveringRect(new Vector2(x + runW + sepW, p.Y), new Vector2(right, p.Y + h))) - ImGuiNET.ImGui.SetTooltip(ai + SafeImGui.SetTooltip(ai ? "RynthAi's script interface is there: scripts can use its macro, nav and meta features." : "RynthAi isn't loaded (or is too old): scripts' RynthAi calls won't work."); NextLine(p, h + 2); @@ -245,7 +245,7 @@ internal sealed class LuaFace : IImGuiPanel if (ImGuiNET.ImGui.IsItemHovered()) { if (!isSel) dl.AddRectFilled(p, p + new Vector2(nameW, RowH), BtnFill); - ImGuiNET.ImGui.SetTooltip(RowTooltip(info, notSaved)); + SafeImGui.SetTooltip(RowTooltip(info, notSaved)); } if (isSel) dl.AddRectFilled(p, p + new Vector2(2, RowH), Teal); @@ -267,7 +267,7 @@ internal sealed class LuaFace : IImGuiPanel _picker.Open(new Vector2(x, by + bh + 2), items, Array.IndexOf(AutoCodes, info.Autostart), k => LuaCommands.Send("autostart", name, AutoCodes[k]), 190); } - ImGuiNET.ImGui.SetItemTooltip(notSaved + SafeImGui.SetItemTooltip(notSaved ? "Save it to a file to autostart it." : "Start at login: off, on every character (global), or on this character only."); x += autoW + gap; @@ -281,7 +281,7 @@ internal sealed class LuaFace : IImGuiPanel x += runW + gap; if (Button("##restart", RestartLabel, new Vector2(x, by), new Vector2(restartW, bh), Text, BtnFill, enabled: info.Running && !notSaved)) LuaCommands.Send("restart", info.Name); - ImGuiNET.ImGui.SetItemTooltip(notSaved ? "Not saved: run it again from the Editor." : "Stop it and start it again from its file."); + SafeImGui.SetItemTooltip(notSaved ? "Not saved: run it again from the Editor." : "Stop it and start it again from its file."); NextLine(p, RowH); } @@ -334,7 +334,7 @@ internal sealed class LuaFace : IImGuiPanel LuaCommands.Send("load", sel); _editorTab = true; } - ImGuiNET.ImGui.SetItemTooltip(canOpen + SafeImGui.SetItemTooltip(canOpen ? (si!.IsFolder ? "Edit its index.lua in the Editor tab." : "Edit it in the Editor tab.") : "It has no file to open."); NextLine(p, h); @@ -407,7 +407,7 @@ internal sealed class LuaFace : IImGuiPanel dl.PopClipRect(); if (Button("##run", RunLabel, new Vector2(p.X + statusW + 4, p.Y), new Vector2(bw, 24), Text, StartBg)) LuaCommands.Send("run", edName, _editor?.GetText() ?? string.Empty); - ImGuiNET.ImGui.SetItemTooltip("Run the editor's text as " + runName + " (replaces a running copy)."); + SafeImGui.SetItemTooltip("Run the editor's text as " + runName + " (replaces a running copy)."); if (Button("##stop", StopLabel, new Vector2(p.X + statusW + bw + 8, p.Y), new Vector2(bw, 24), Text, StopBg, enabled: running)) LuaCommands.Send("stopScript", runName); NextLine(p, 24); @@ -495,7 +495,7 @@ internal sealed class LuaFace : IImGuiPanel _editor?.MarkClean(); } } - if (saveTip != null) ImGuiNET.ImGui.SetItemTooltip(saveTip); + if (saveTip != null) SafeImGui.SetItemTooltip(saveTip); x += bw + 4; if (Button("##new", PhosphorIcons.FilePlus + " New", new Vector2(x, p.Y), new Vector2(bw, 22), Text, BtnFill)) { @@ -508,7 +508,7 @@ internal sealed class LuaFace : IImGuiPanel string name = Utf8(_name).Trim(); if (name.Length > 0) LuaCommands.Send("delete", name); } - if (deleteTip != null) ImGuiNET.ImGui.SetItemTooltip(deleteTip); + if (deleteTip != null) SafeImGui.SetItemTooltip(deleteTip); ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 22)); ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); } @@ -555,7 +555,7 @@ internal sealed class LuaFace : IImGuiPanel ImGuiNET.ImGui.PushTextWrapPos(0); string text = _data?.Console ?? string.Empty; if (text.Length > 0) ImGuiNET.ImGui.TextUnformatted(text); - if (_note.Length > 0) ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFE8B333), "[panel] " + _note); + if (_note.Length > 0) SafeImGui.TextColored(RynthTheme.Vec(0xFFE8B333), "[panel] " + _note); ImGuiNET.ImGui.PopTextWrapPos(); ImGuiNET.ImGui.PopStyleColor(); ImGuiNET.ImGui.PopFont(); diff --git a/src/RynthCore.Engine/ImGui/Panels/MetaFace.Editor.cs b/src/RynthCore.Engine/ImGui/Panels/MetaFace.Editor.cs index 547c199..f3a0be9 100644 --- a/src/RynthCore.Engine/ImGui/Panels/MetaFace.Editor.cs +++ b/src/RynthCore.Engine/ImGui/Panels/MetaFace.Editor.cs @@ -281,7 +281,7 @@ internal sealed partial class MetaFace if (actions) MetaRuleEdit.AddAction(r); else MetaRuleEdit.AddCondition(r); _editChanged = true; } - ImGuiNET.ImGui.SetItemTooltip(actions + SafeImGui.SetItemTooltip(actions ? (r.Action == MetaRuleEdit.DoAll ? "Add one more action" : "Add another action: this one and the new one run in order (All)") : !canAdd ? "A Not has one condition" : r.Condition is MetaRuleEdit.All or MetaRuleEdit.Any or MetaRuleEdit.Not ? "Add one more condition" @@ -515,7 +515,7 @@ internal sealed partial class MetaFace c.ConditionData = here; _editChanged = true; } - ImGuiNET.ImGui.SetItemTooltip(here != null + SafeImGui.SetItemTooltip(here != null ? $"Set to where you are now: {here}" : "Your position isn't known right now (portal space, or not in the world)."); } @@ -524,7 +524,7 @@ internal sealed partial class MetaFace ImGuiNET.ImGui.SetCursorScreenPos(p); DataBox(id, c, action: false, MetaVocabulary.ConditionHint(c.Condition), width, height); if (c.Condition == MetaRuleEdit.NoKillsWithinMinutes) - ImGuiNET.ImGui.SetItemTooltip(MetaRuleEdit.NoKillsTooltip(c.ConditionData).Replace("%", "%%")); // a format string: typed text may hold % + SafeImGui.SetItemTooltip(MetaRuleEdit.NoKillsTooltip(c.ConditionData)); // typed text may hold %: SafeImGui escapes it } ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + height)); ImGuiNET.ImGui.Dummy(new Vector2(0, 0)); @@ -617,7 +617,7 @@ internal sealed partial class MetaFace } bool removed = IconButton("##rm", PhosphorIcons.X, new Vector2(p.X + rw - xw, p.Y), new Vector2(xw, rh), TextDim, DelFill, BtnBord); - ImGuiNET.ImGui.SetItemTooltip(action ? "Remove this action" : nests ? "Remove this group and what is in it" : "Remove this condition"); + SafeImGui.SetItemTooltip(action ? "Remove this action" : nests ? "Remove this group and what is in it" : "Remove this condition"); int moveTo = -1; if (action) { @@ -720,7 +720,7 @@ internal sealed partial class MetaFace if (draft) { _autosave.Clear(); LeaveEditor(); } else _editConfirmDelete = true; } - ImGuiNET.ImGui.SetItemTooltip(draft ? "Drop this new rule (it was never added)" : "Delete this rule (asks first)"); + SafeImGui.SetItemTooltip(draft ? "Drop this new rule (it was never added)" : "Delete this rule (asks first)"); } else { @@ -787,7 +787,7 @@ internal sealed partial class MetaFace ImGuiNET.ImGui.GetWindowDrawList().AddRect(pos, pos + new Vector2(boxW, height), Red, 3); bool ok = IconButton(id + "_ok", PhosphorIcons.Check, new Vector2(pos.X + boxW + 3, pos.Y), new Vector2(bw, height), Green, NewFill, Green, enabled: _nameProblem == null); - ImGuiNET.ImGui.SetItemTooltip(_nameProblem ?? $"Make the state '{name}' (Enter)"); + SafeImGui.SetItemTooltip(_nameProblem ?? $"Make the state '{name}' (Enter)"); bool cancel = IconButton(id + "_cancel", PhosphorIcons.X, new Vector2(pos.X + boxW + bw + 6, pos.Y), new Vector2(bw, height), TextDim, BtnFill, BtnBord); ImGuiNET.ImGui.SetItemTooltip("Cancel (Esc)"); @@ -861,7 +861,7 @@ internal sealed partial class MetaFace private static void Note(string text) { ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D6E4), text); + SafeImGui.TextColored(RynthTheme.Vec(0xFFC8D6E4), text); ImGuiNET.ImGui.PopFont(); } diff --git a/src/RynthCore.Engine/ImGui/Panels/MetaFace.List.cs b/src/RynthCore.Engine/ImGui/Panels/MetaFace.List.cs index f42ba75..55ee815 100644 --- a/src/RynthCore.Engine/ImGui/Panels/MetaFace.List.cs +++ b/src/RynthCore.Engine/ImGui/Panels/MetaFace.List.cs @@ -276,7 +276,7 @@ internal sealed partial class MetaFace float toggleX = x; if (Toggle(compactLabel, ref x, p.Y, !anyRuleOpen)) SetAllFolded(anyRuleOpen); x = toggleX + compactW + 4; // the button keeps one width whichever label it shows - ImGuiNET.ImGui.SetItemTooltip(anyRuleOpen + SafeImGui.SetItemTooltip(anyRuleOpen ? "Fold every rule to one line (hover one to see all of it; its caret opens it again)." : "Show every rule in full: each condition and action on its own line."); @@ -288,7 +288,7 @@ internal sealed partial class MetaFace if (anyOpen) foreach ((string s, List _) in _groups) _collapsed.Add(s); else _collapsed.Clear(); } - ImGuiNET.ImGui.SetItemTooltip(anyOpen ? "Collapse every state" : "Expand every state"); + SafeImGui.SetItemTooltip(anyOpen ? "Collapse every state" : "Expand every state"); ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X, p.Y + 22)); ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); @@ -451,7 +451,7 @@ internal sealed partial class MetaFace rx -= pw; if (GlyphButton("##add", PhosphorIcons.Plus, new Vector2(rx, hp.Y + (hh - 18) * 0.5f), new Vector2(pw, 18), Green, Lighten(Green))) OpenEditor(-1, new MetaRuleDto { State = state, Action = 1 }); - ImGuiNET.ImGui.SetItemTooltip($"New rule in {state}"); + SafeImGui.SetItemTooltip($"New rule in {state}"); rx -= 4; } if (current) @@ -464,7 +464,7 @@ internal sealed partial class MetaFace dl.AddRect(a, b, Teal, 8); dl.AddText(small, small.FontSize, new Vector2(a.X + 5, a.Y + 2), Teal, tag); if (_stateClock.Known && ImGuiNET.ImGui.IsMouseHoveringRect(a, b)) - ImGuiNET.ImGui.SetTooltip("The meta's current state, and how long it has been in it (what \"In state >= N s\" rules count)."); + SafeImGui.SetTooltip("The meta's current state, and how long it has been in it (what \"In state >= N s\" rules count)."); rx = a.X - 6; // The Watchdog, while one is set: it sends the meta to its state when the time runs out @@ -554,7 +554,7 @@ internal sealed partial class MetaFace new Vector2(p.X + 2, firstLineY + (_lineH - 16) * 0.5f), new Vector2(14, 16), Faded(TextDim), Teal)) SetFolded(index, !folded); caretHot = ImGuiNET.ImGui.IsItemHovered(); - ImGuiNET.ImGui.SetItemTooltip(folded ? "Show all of this rule" : "Fold this rule to one line"); + SafeImGui.SetItemTooltip(folded ? "Show all of this rule" : "Fold this rule to one line"); } if (GlyphButton("##en", rule.Enabled ? PhosphorIcons.CheckSquare : PhosphorIcons.Square, new Vector2(p.X + 16, firstLineY + (_lineH - 16) * 0.5f), new Vector2(16, 16), rule.Enabled ? Green : Mute, TextDim)) @@ -562,7 +562,7 @@ internal sealed partial class MetaFace rule.Enabled = !rule.Enabled; SendEdit(new MetaCmd { Op = "set_rule_enabled", Index = index, Value = rule.Enabled ? "true" : "false" }); } - ImGuiNET.ImGui.SetItemTooltip(rule.Enabled ? "Enabled: click to disable" : "Disabled: click to enable"); + SafeImGui.SetItemTooltip(rule.Enabled ? "Enabled: click to disable" : "Disabled: click to enable"); if ((hot && !filtering) || dragged) // on hover the number becomes a grip: the row drags PhosphorIcons.DrawCentered(dl, ImGuiFonts.Get(UiFont.Ui11), PhosphorIcons.DotsSixVertical, new Vector2(p.X + 34, firstLineY), new Vector2(_numW + 4, _lineH), dragged ? Teal : Mute); @@ -617,13 +617,13 @@ internal sealed partial class MetaFace if (IconButton("##up", PhosphorIcons.ArrowUp, new Vector2(bx, by), new Vector2(bs, bs), Mute, BtnFill, BtnBord, enabled: canMove && gi > 0)) changed |= Move(index, -1); toolHot |= ImGuiNET.ImGui.IsItemHovered(); - ImGuiNET.ImGui.SetItemTooltip(canMove ? "Move up" : "Clear the filter to move rules"); + SafeImGui.SetItemTooltip(canMove ? "Move up" : "Clear the filter to move rules"); bx += bs + gap; if (IconButton("##dn", PhosphorIcons.ArrowDown, new Vector2(bx, by), new Vector2(bs, bs), Mute, BtnFill, BtnBord, enabled: canMove && gi < groupCount - 1)) changed |= Move(index, +1); toolHot |= ImGuiNET.ImGui.IsItemHovered(); - ImGuiNET.ImGui.SetItemTooltip(canMove ? "Move down" : "Clear the filter to move rules"); + SafeImGui.SetItemTooltip(canMove ? "Move down" : "Clear the filter to move rules"); bx += bs + gap; if (IconButton("##dup", PhosphorIcons.Copy, new Vector2(bx, by), new Vector2(bs, bs), Mute, BtnFill, BtnBord)) changed |= Duplicate(index, rule); @@ -644,7 +644,7 @@ internal sealed partial class MetaFace } } toolHot |= ImGuiNET.ImGui.IsItemHovered(); - ImGuiNET.ImGui.SetItemTooltip(arming ? "Click again to delete this rule" : "Delete rule"); + SafeImGui.SetItemTooltip(arming ? "Click again to delete this rule" : "Delete rule"); } dl.AddLine(new Vector2(p.X, p.Y + h - 0.5f), new Vector2(p.X + w, p.Y + h - 0.5f), RowLine); @@ -1023,7 +1023,7 @@ internal sealed partial class MetaFace _stateClock.StateSet(NowMs); // picking a state enters it afresh (RynthAi resets its clock) } if (inState != null && ImGuiNET.ImGui.IsMouseHoveringRect(new Vector2(pickX, p.Y + 1), new Vector2(pickX + pickW, p.Y + 23))) - ImGuiNET.ImGui.SetTooltip($"The meta's current state; in it for {inState}."); + SafeImGui.SetTooltip($"The meta's current state; in it for {inState}."); bool canGo = HasRulesIn(_data.CurrentState); if (IconButton("##goto_current", PhosphorIcons.Crosshair, new Vector2(pickX + pickW + 4, p.Y + 1), new Vector2(goW, 22), Teal, BtnFill, BtnBord, enabled: canGo, font: UiFont.Ui14)) @@ -1035,7 +1035,7 @@ internal sealed partial class MetaFace SetFilter(string.Empty); } } - ImGuiNET.ImGui.SetItemTooltip(canGo ? "Show the current state in the list" : "The current state has no rules"); + SafeImGui.SetItemTooltip(canGo ? "Show the current state in the list" : "The current state has no rules"); if (Button(ruleLabel + "##new", new Vector2(ruleX, p.Y), new Vector2(newW, 24), TextDim, NewFill, Green)) OpenEditor(-1, new MetaRuleDto { State = _data.CurrentState, Action = 1 }); ImGuiNET.ImGui.SetItemTooltip("A new rule in the current state (added once its condition and action are filled in)"); diff --git a/src/RynthCore.Engine/ImGui/Panels/MetaFace.Schedule.cs b/src/RynthCore.Engine/ImGui/Panels/MetaFace.Schedule.cs index 07ec4f4..dbde4fc 100644 --- a/src/RynthCore.Engine/ImGui/Panels/MetaFace.Schedule.cs +++ b/src/RynthCore.Engine/ImGui/Panels/MetaFace.Schedule.cs @@ -166,7 +166,7 @@ internal sealed partial class MetaFace ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, y)); TextBox(id, buf, boxW, "", ImGuiInputTextFlags.CharsDecimal, out _); bool done = ImGuiNET.ImGui.IsItemDeactivatedAfterEdit(); - ImGuiNET.ImGui.SetItemTooltip(tip); + SafeImGui.SetItemTooltip(tip); if (done && int.TryParse(Utf8(buf).Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int n)) commit(n); x += boxW + 3; @@ -183,9 +183,9 @@ internal sealed partial class MetaFace : sc.LastPollMs == 0 ? "Waiting for the first /myquests." : $"{sc.QuestCount} quest timer(s), /myquests {Span(now - sc.LastPollMs)} ago."; ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(sc.ServerDisabled ? 0xFFE8B333 : 0xFFC8D6E4), Fit(poll, w)); + SafeImGui.TextColored(RynthTheme.Vec(sc.ServerDisabled ? 0xFFE8B333 : 0xFFC8D6E4), Fit(poll, w)); if (sc.LastSwitch.Length > 0) - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), + SafeImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), Fit($"Last: {sc.LastSwitch}{(sc.LastSwitchMs > 0 ? $", {Span(now - sc.LastSwitchMs)} ago" : "")}", w)); ImGuiNET.ImGui.PopFont(); } @@ -220,7 +220,7 @@ internal sealed partial class MetaFace r.Enabled = !r.Enabled; MetaCommands.Simple("mm_rule_enabled", i, r.Enabled ? "true" : "false"); } - ImGuiNET.ImGui.SetItemTooltip(r.Enabled ? "On - click to turn this rule off" : "Off - click to turn it on"); + SafeImGui.SetItemTooltip(r.Enabled ? "On - click to turn this rule off" : "Off - click to turn it on"); x += 16; if (IconButton("##up", PhosphorIcons.ArrowUp, new Vector2(x + 1, p.Y + 2), new Vector2(16, 16), Mute, BtnFill, BtnBord, enabled: i > 0)) { @@ -245,7 +245,7 @@ internal sealed partial class MetaFace if (IconButton("##cd", running ? PhosphorIcons.Stop : PhosphorIcons.Play, new Vector2(x + 1, p.Y + 2), new Vector2(16, 16), running ? Amber : Green, BtnFill, BtnBord)) MetaCommands.Simple(running ? "mm_countdown_stop" : "mm_countdown_start", i); - ImGuiNET.ImGui.SetItemTooltip(running ? "Stop the countdown" : $"Start the countdown ({Num(r.Minutes)} min)"); + SafeImGui.SetItemTooltip(running ? "Stop the countdown" : $"Start the countdown ({Num(r.Minutes)} min)"); } else if (r.Fired || (r.State ?? "").StartsWith("error", StringComparison.Ordinal) || (r.State ?? "").Contains("holding")) { @@ -270,7 +270,7 @@ internal sealed partial class MetaFace if (ImGuiNET.ImGui.IsItemHovered()) { ImGuiNET.ImGui.SetMouseCursor(ImGuiMouseCursor.Hand); - ImGuiNET.ImGui.SetTooltip(RuleTooltip(r, i, first)); + SafeImGui.SetTooltip(RuleTooltip(r, i, first)); } ImGuiNET.ImGui.PopID(); if (changed) return; // the list changed: draw it again next frame @@ -367,7 +367,7 @@ internal sealed partial class MetaFace ScheduleRuleDto r = _schedRule; ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), _schedEdit == -1 ? "New rule" : $"Edit rule {_schedEdit + 1}"); + SafeImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), _schedEdit == -1 ? "New rule" : $"Edit rule {_schedEdit + 1}"); ImGuiNET.ImGui.PopFont(); FieldLabel("When:"); @@ -428,7 +428,7 @@ internal sealed partial class MetaFace else MetaCommands.Send(new MetaCmd { Op = "mm_update", Index = _schedEdit, ScheduleRule = send }); _schedEdit = -2; } - if (!valid) ImGuiNET.ImGui.SetItemTooltip(r.Meta.Length == 0 ? "Pick a meta to load" : "Name the quest"); + if (!valid) SafeImGui.SetItemTooltip(r.Meta.Length == 0 ? "Pick a meta to load" : "Name the quest"); if (Button("Cancel##sched_cancel", new Vector2(b.X + sw + 6, b.Y), new Vector2(60, 22), Mute, BtnFill, BtnBord)) _schedEdit = -2; ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(b.X, b.Y + 22)); diff --git a/src/RynthCore.Engine/ImGui/Panels/MetaFace.cs b/src/RynthCore.Engine/ImGui/Panels/MetaFace.cs index 9ac960b..20acc8f 100644 --- a/src/RynthCore.Engine/ImGui/Panels/MetaFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/MetaFace.cs @@ -299,7 +299,7 @@ internal sealed partial class MetaFace : IImGuiPanel bool noFile = string.IsNullOrEmpty(_data.CurrentMetaPath); if (Button("Save As##save_as", new Vector2(x, p.Y), new Vector2(saveAsW, 22), TextDim, noFile ? NewFill : BtnFill, noFile ? Green : BtnBord)) BeginSaveAs(); - ImGuiNET.ImGui.SetItemTooltip(noFile ? "Name a file for this meta; after that every change saves on its own." + SafeImGui.SetItemTooltip(noFile ? "Name a file for this meta; after that every change saves on its own." : "Save a copy under a new name (and keep editing that one)."); x += saveAsW + 4; SaveIndicator(new Vector2(x, p.Y), p.X + w - x, 22); @@ -346,7 +346,7 @@ internal sealed partial class MetaFace : IImGuiPanel float tw = ImGuiNET.ImGui.CalcTextSize(text).X; ImGuiNET.ImGui.SetCursorScreenPos(pos); ImGuiNET.ImGui.InvisibleButton("##save_ind", new Vector2(width, height)); - ImGuiNET.ImGui.SetItemTooltip(tip); + SafeImGui.SetItemTooltip(tip); ImGuiNET.ImGui.GetWindowDrawList().AddText(new Vector2(pos.X + Math.Max(0, width - tw), pos.Y + (height - ImGuiNET.ImGui.GetFontSize()) * 0.5f), color, text); } @@ -460,7 +460,7 @@ internal sealed partial class MetaFace : IImGuiPanel if (showMsg) { ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(_msgOk ? 0xFF33CC66 : 0xFFE04848), _msg); + SafeImGui.TextColored(RynthTheme.Vec(_msgOk ? 0xFF33CC66 : 0xFFE04848), _msg); ImGuiNET.ImGui.PopTextWrapPos(); } if (_sourceStale) @@ -987,7 +987,7 @@ internal sealed partial class MetaFace : IImGuiPanel private static void FieldLabel(string text) { ImGuiNET.ImGui.Dummy(new Vector2(0, 1)); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFC8D6E4), text); + SafeImGui.TextColored(RynthTheme.Vec(0xFFC8D6E4), text); } private static void Separator(float w) diff --git a/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.Sections.cs b/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.Sections.cs new file mode 100644 index 0000000..4129655 --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.Sections.cs @@ -0,0 +1,542 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/MiniRemoteFace.Sections.cs +// The Mini Remote's sections (UI/Sections): the rail down the left, and the +// body of the section picked on it. +// +// rail Remote (the slots / RynthAi's remote), then the core sections and +// the plugins' own, in SectionRegistry's order. Right-click: the +// menu (sections, active servers' items, hide the rail). Hidden, the +// sections stay reachable from the menu and /rc miniremote section. +// body a row of tabs when there is more than one view: the section's views +// (engine panels embedded whole, the Session Stats overview, plugin views), +// then one tab per active server with options here ("Server: ILT") +// and "Plugins" for options every world gets. A view fills the body; +// an options tab lists the plugins' option surfaces (collapsible) and +// command buttons. +// fit picking a section sizes the window for its first view; a resize by +// hand holds until the next pick. Back on Remote, the remote refits. +// saved the core section last picked, and whether the rail shows +// (panel_columns.txt, for the whole PC). +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Numerics; +using System.Text; +using System.Threading; +using ImGuiNET; +using RynthCore.Engine.Compatibility; +using RynthCore.Engine.Plugins; +using RynthCore.Engine.UI; +using RynthCore.Engine.UI.Sections; +using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal sealed partial class MiniRemoteFace +{ + private const string SectionKey = "MiniRemote.section", RailKey = "MiniRemote.rail"; + private const float RailMinW = 52f, RailMaxW = 96f, RailRowH = 18f, TabRowH = 20f; + /// The host key that keeps this window's embedded panels apart from other hosts'. + private const string EmbedHost = "MiniRemote"; + /// Preferred body size (logical) for a view that doesn't say. + private static readonly Vector2 DefaultViewSize = new(420, 380); + private static readonly Vector2 OverviewSize = new(360, 200); + + // Shared by every instance (the face is recreated on each open): the section shown. + private static string _section = LoadSection(); + private static string? _requestedSection, _requestedSurface; // from commands, taken on the next draw + private static readonly Dictionary TabBySection = new(StringComparer.OrdinalIgnoreCase); + + // This instance: the window fit and the plugin surfaces. + private bool _fitPending = true; + private Vector2 _remoteWindowSize; + private readonly Dictionary _surfaceBytes = new(StringComparer.Ordinal); + private readonly Dictionary _surfaceHeights = new(StringComparer.Ordinal); + private readonly HashSet _surfaceOff = new(StringComparer.Ordinal); + private float _railW; + private int _railRevision = -1; + + private static bool IsRemote => _section.Equals(SectionCatalog.RemoteId, StringComparison.OrdinalIgnoreCase); + + private static bool RailShown => PanelColumnStore.Get(RailKey, 1f) >= 0.5f; + + // ── Requests (commands; render thread) ────────────────────────────── + + /// Shows section ("remote" = the remote) on the next draw. + public static void RequestSection(string sectionId) + { + Volatile.Write(ref _requestedSurface, null); + Volatile.Write(ref _requestedSection, sectionId); + } + + /// + /// Shows the section and tab holding plugin surface (RynthAi's + /// "section:banking"), when one does now. False when no section has it. + /// + public static bool TryRequestSurface(string surface) + { + foreach (SectionView v in SectionRegistry.Current.Sections) + if (TabOfSurface(v, surface) >= 0) + { + Volatile.Write(ref _requestedSurface, surface); + Volatile.Write(ref _requestedSection, v.Id); + return true; + } + return false; + } + + private void TakeRequestedSection(SectionRegistry.Snapshot snap) + { + string? id = Interlocked.Exchange(ref _requestedSection, null); + if (id == null) return; + string? surface = Interlocked.Exchange(ref _requestedSurface, null); + SelectSection(id); + SectionView? v = snap.Find(_section); + if (v != null && surface != null) + { + int tab = TabOfSurface(v, surface); + if (tab >= 0) TabBySection[v.Id] = tab; + } + } + + /// The tab index (views, then option groups) holding , else -1. + private static int TabOfSurface(SectionView v, string surface) + { + for (int i = 0; i < v.Panes.Length; i++) + if (v.Panes[i].Contribution?.Surface.Equals(surface, StringComparison.OrdinalIgnoreCase) == true) return i; + for (int g = 0; g < v.Groups.Length; g++) + foreach (SectionContribution c in v.Groups[g].Items) + if (c.Surface.Equals(surface, StringComparison.OrdinalIgnoreCase)) return v.Panes.Length + g; + return -1; + } + + private void SelectSection(string id) + { + string next = id.Length == 0 ? SectionCatalog.RemoteId : id; + if (next.Equals(_section, StringComparison.OrdinalIgnoreCase)) return; + bool leavingRemote = IsRemote; + if (leavingRemote && !ImGuiPopOuts.InPopOutFrame) + _remoteWindowSize = ImGuiNET.ImGui.GetWindowSize() / ImGuiPanelHost.PlacementScale(); + _section = next; + _fitPending = true; + if (IsRemote) + { + // Back on the remote: RynthAi's asks again; the engine grid gets the size it had. + _lastWant = Vector2.Zero; + _requested = Vector2.Zero; + if (_remoteWindowSize.X > 0 && !_hosted && !ImGuiPopOuts.InPopOutFrame) + ImGuiPanelHost.RequestSize(Title, _remoteWindowSize); + } + SaveSection(_section); + } + + private static string LoadSection() + { + int i = (int)PanelColumnStore.Get(SectionKey, -1f); + return i >= 0 && i < SectionCatalog.Core.Length ? SectionCatalog.Core[i].Id : SectionCatalog.RemoteId; + } + + /// Saves a core section (a plugin's own isn't: it may not be there next time). + private static void SaveSection(string id) + { + int index = -1; + for (int i = 0; i < SectionCatalog.Core.Length; i++) + if (SectionCatalog.Core[i].Id.Equals(id, StringComparison.OrdinalIgnoreCase)) index = i; + if (PanelColumnStore.Get(SectionKey, -1f) != index) PanelColumnStore.Set(SectionKey, index); + } + + // ── Rail ──────────────────────────────────────────────────────────── + + /// Draws the rail at the body's left; returns the width it takes (with its gap). + private float DrawRail(SectionRegistry.Snapshot snap, Vector2 origin, Vector2 size) + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + try + { + if (_railRevision != snap.Revision || _railW <= 0) + { + float widest = ImGuiNET.ImGui.CalcTextSize("Remote").X; + foreach (SectionView v in snap.Sections) widest = MathF.Max(widest, ImGuiNET.ImGui.CalcTextSize(v.Label).X); + _railW = Math.Clamp(widest + 14f, RailMinW, RailMaxW); + _railRevision = snap.Revision; + } + float h = Math.Max(RailRowH, size.Y - 12 - GripOverlap()); + ImGuiNET.ImGui.SetCursorScreenPos(origin + new Vector2(6, 6)); + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, Vector2.Zero); + bool open = ImGuiNET.ImGui.BeginChild("##mr_rail", new Vector2(_railW, h), ImGuiChildFlags.None, + ImGuiWindowFlags.NoBackground | ImGuiWindowFlags.NoScrollbar); + ImGuiNET.ImGui.PopStyleVar(); + try + { + if (open) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + RailButton(SectionCatalog.RemoteId, "Remote", "The remote: item slots, and RynthAi's when it is loaded.", true, ref p); + var dl = ImGuiNET.ImGui.GetWindowDrawList(); + dl.AddLine(p + new Vector2(2, 1), p + new Vector2(_railW - 2, 1), BtnBord); + p.Y += 4; + foreach (SectionView v in snap.Sections) + RailButton(v.Id, v.Label, RailTooltip(v), v.HasContent, ref p); + ImGuiNET.ImGui.SetCursorScreenPos(p); + ImGuiNET.ImGui.Dummy(new Vector2(_railW, 1)); + if (ImGuiNET.ImGui.IsWindowHovered() && ImGuiNET.ImGui.IsMouseClicked(ImGuiMouseButton.Right)) + { + _menuSlot = -1; + _openMenu = true; + } + } + } + finally + { + ImGuiNET.ImGui.EndChild(); + } + } + finally + { + ImGuiNET.ImGui.PopFont(); + } + return _railW + 4f; + } + + private void RailButton(string id, string label, string tooltip, bool hasContent, ref Vector2 p) + { + bool selected = id.Equals(_section, StringComparison.OrdinalIgnoreCase); + var size = new Vector2(_railW, RailRowH); + if (Button("##rail_" + id, label, p, size, hasContent ? Text : Faded(Text), selected ? Selected : BtnFill, + leftAlign: true, border: selected ? Teal : 0)) + SelectSection(id); + if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) { _menuSlot = -1; _openMenu = true; } + if (tooltip.Length > 0) SafeImGui.SetItemTooltip(tooltip); + p.Y += RailRowH + 2; + } + + private static string RailTooltip(SectionView v) + { + if (!v.HasContent) return v.Label + ": " + EmptyNote(v.Id); + var parts = new List(); + foreach (SectionPane pane in v.Panes) parts.Add(pane.Title); + foreach (SectionGroup g in v.Groups) parts.Add(g.Title); + return v.Label + ": " + string.Join(", ", parts); + } + + /// What an empty section says (nothing installed fills it on this world). + private static string EmptyNote(string id) => id switch + { + "friends" => "no friends list yet. A server plugin can add one here.", + "fellowship" => "the fellowship view comes from RynthAi; it isn't loaded.", + "pets" or "crafting" or "spells" => "this view comes from RynthAi; it isn't loaded.", + "map" or "combat" or "nav" or "chat" or "skills" or "inventory" => "its engine panels are off (Settings, or the plugins they need aren't installed).", + _ => "nothing installed adds to it on this world.", + }; + + // ── Section body ──────────────────────────────────────────────────── + + private void DrawSection(SectionRegistry.Snapshot snap, float w, Vector2 origin, Vector2 size) + { + SectionView? view = snap.Find(_section); + if (view == null) + { + // A plugin's section that went away (its server isn't active any more): back to the remote. + if (snap.Sections.Count > 0) SelectSection(SectionCatalog.RemoteId); + Label("Loading sections...", Mute); + return; + } + + int tabs = view.Panes.Length + view.Groups.Length; + if (tabs == 0) + { + Label(view.Label, Teal); + ImGuiNET.ImGui.PushTextWrapPos(ImGuiNET.ImGui.GetCursorPosX() + w); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Mute); + SafeImGui.TextWrapped(char.ToUpperInvariant(EmptyNote(view.Id)[0]) + EmptyNote(view.Id)[1..]); + ImGuiNET.ImGui.PopStyleColor(); + ImGuiNET.ImGui.PopTextWrapPos(); + return; + } + + if (!TabBySection.TryGetValue(view.Id, out int tab) || tab < 0 || tab >= tabs) tab = 0; + float haveH = Remaining(origin, size); + if (tabs > 1) tab = DrawTabRow(view, tab, w); + TabBySection[view.Id] = tab; + + if (_fitPending) + { + _fitPending = false; + Vector2 pref = PreferredSize(view, tab); + float place = ImGuiPanelHost.PlacementScale(); + float extra = (tabs > 1 ? TabRowH + 4 : 0) + GripOverlap(); + FitWindow(new Vector2(pref.X * place, pref.Y * place + extra), w, haveH); + } + + var box = new Vector2(w, Math.Max(40f, Remaining(origin, size) - GripOverlap())); + if (tab < view.Panes.Length) DrawPane(snap, view.Panes[tab], box); + else DrawGroup(view.Groups[tab - view.Panes.Length], box); + } + + /// The section's tabs as a wrapped row of buttons; returns the one selected. + private int DrawTabRow(SectionView view, int tab, float w) + { + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui9)); + try + { + Vector2 start = ImGuiNET.ImGui.GetCursorScreenPos(); + Vector2 p = start; + int count = view.Panes.Length + view.Groups.Length; + for (int i = 0; i < count; i++) + { + string label = i < view.Panes.Length ? view.Panes[i].Title : view.Groups[i - view.Panes.Length].Title; + float bw = Math.Min(w, ButtonWidth(label)); + if (p.X > start.X && p.X + bw > start.X + w) p = new Vector2(start.X, p.Y + TabRowH + 2); + bool selected = i == tab; + bool enabled = i >= view.Panes.Length || view.Panes[i].Contribution?.Enabled != false; + if (Button("##sectab_" + view.Id + "_" + i, label, p, new Vector2(bw, TabRowH), enabled ? Text : Faded(Text), + selected ? Selected : BtnFill, border: selected ? Teal : 0) && i != tab) + { + tab = i; + _fitPending = true; + } + p.X += bw + 3; + } + NextLine(start, p.Y - start.Y + TabRowH + 4); + } + finally + { + ImGuiNET.ImGui.PopFont(); + } + return tab; + } + + /// The body size (logical) a tab would like: its panel's default, or what its plugin said. + private Vector2 PreferredSize(SectionView view, int tab) + { + if (tab >= view.Panes.Length) return DefaultViewSize; + SectionPane pane = view.Panes[tab]; + switch (pane.Kind) + { + case SectionPaneKind.Overview: + return OverviewSize; + case SectionPaneKind.CorePanel: + return ImGuiPanelHost.TryGetDefaultSize(pane.Panel, out Vector2 s) && s.X > 0 && s.Y > 0 ? s : DefaultViewSize; + default: + SectionContribution c = pane.Contribution!; + return new Vector2(c.Width > 0 ? c.Width : DefaultViewSize.X, c.Height > 0 ? c.Height : DefaultViewSize.Y); + } + } + + private void DrawPane(SectionRegistry.Snapshot snap, SectionPane pane, Vector2 box) + { + switch (pane.Kind) + { + case SectionPaneKind.Overview: + DrawOverview(snap, box); + break; + case SectionPaneKind.CorePanel: + ImGuiPanelHost.DrawEmbedded(EmbedHost, pane.Panel, box); + break; + default: + SectionContribution c = pane.Contribution!; + if (!c.Enabled) { DrawDisabledNote(c); break; } + DrawSurface(c, box); + break; + } + } + + /// An options tab: a server's (or every world's) option surfaces and command buttons. + private void DrawGroup(SectionGroup group, Vector2 box) + { + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(2, 2)); + bool open = ImGuiNET.ImGui.BeginChild("##mr_group_" + group.Title, box, ImGuiChildFlags.AlwaysUseWindowPadding, + ImGuiWindowFlags.NoBackground); + ImGuiNET.ImGui.PopStyleVar(); + try + { + if (!open) return; + if (group.Server is ServerState s) + Label(s.Force == ServerForce.Auto ? $"{s.Name}: detected ({s.Reason})." : $"{s.Name}: forced on for this character.", + Faded(Mute)); + float w = ImGuiNET.ImGui.GetContentRegionAvail().X; + foreach (SectionContribution c in group.Items) + { + ImGuiNET.ImGui.PushID(c.Plugin + "|" + c.Label + "|" + c.Surface + c.Command); + try + { + if (c.IsSurface) DrawOptionSurface(c, w); + else DrawCommandButton(c, w); + } + finally + { + ImGuiNET.ImGui.PopID(); + } + } + } + finally + { + ImGuiNET.ImGui.EndChild(); + } + } + + private void DrawOptionSurface(SectionContribution c, float w) + { + if (!ImGuiNET.ImGui.CollapsingHeader(c.Label, ImGuiTreeNodeFlags.DefaultOpen)) + { + if (c.Tooltip.Length > 0) SafeImGui.SetItemTooltip(c.Tooltip); + return; + } + if (c.Tooltip.Length > 0) SafeImGui.SetItemTooltip(c.Tooltip); + if (!c.Enabled) { DrawDisabledNote(c); return; } + string key = c.Plugin + "|" + c.Surface; + if (!_surfaceHeights.TryGetValue(key, out float h)) h = c.Height > 0 ? c.Height : 220f; + Vector2 want = DrawSurface(c, new Vector2(w, h)); + if (want.Y > 0 && Math.Abs(want.Y - h) > 1f) _surfaceHeights[key] = Math.Min(want.Y, SectionManifestParser.MaxSurfaceSize); + } + + private static void DrawCommandButton(SectionContribution c, float w) + { + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + float bw = Math.Min(w, Math.Max(120f, ButtonWidth(c.Label))); + if (Button("##cmd", c.Label, p, new Vector2(bw, 22), c.Enabled ? Text : Faded(Text), BtnFill, c.Enabled)) + ServerMenus.Run(c.Command); + string tip = c.Enabled || c.Note.Length == 0 ? c.Tooltip : c.Note; + SafeImGui.SetItemTooltip(tip.Length > 0 ? tip + "\n" + c.Command : c.Command); + NextLine(p, 26); + if (!c.Enabled && c.Note.Length > 0) DrawDisabledNote(c); + } + + private static void DrawDisabledNote(SectionContribution c) + { + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Faded(Mute)); + ImGuiNET.ImGui.PushTextWrapPos(0f); + SafeImGui.TextWrapped(c.Note.Length > 0 ? c.Note : c.Label + " isn't available right now."); + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.PopStyleColor(); + } + + /// + /// A plugin surface in a child of ; returns the size the plugin asked + /// for (zero when it didn't say). A surface whose export threw stays off for the session. + /// + private Vector2 DrawSurface(SectionContribution c, Vector2 box) + { + string key = c.Plugin + "|" + c.Surface; + if (_surfaceOff.Contains(key)) + { + Label($"{c.Label}: {c.Plugin} stopped drawing it (see the log).", Amber); + return Vector2.Zero; + } + if (!_surfaceBytes.TryGetValue(c.Surface, out byte[]? bytes)) + _surfaceBytes[c.Surface] = bytes = Encoding.UTF8.GetBytes(c.Surface + "\0"); + + int result = PluginManager.EmbedNotReady; + Vector2 want = Vector2.Zero; + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, Vector2.Zero); + bool open = ImGuiNET.ImGui.BeginChild("##surf_" + key, box, ImGuiChildFlags.None, ImGuiWindowFlags.NoBackground); + ImGuiNET.ImGui.PopStyleVar(); + try + { + if (open) + { + // Plugin widgets use the default UI font, as in their own windows. + ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui11)); + try { result = PluginManager.RenderEmbed(c.Plugin, bytes, box, out want); } + finally { ImGuiNET.ImGui.PopFont(); } + if (result == PluginManager.EmbedNotReady) ImGuiNET.ImGui.TextDisabled("Loading..."); + else if (result == PluginManager.EmbedNoPlugin) + SafeImGui.TextDisabled($"{c.Plugin} isn't loaded, or is too old for this view."); + } + } + finally + { + ImGuiNET.ImGui.EndChild(); + } + if (result == PluginManager.EmbedFailed) _surfaceOff.Add(key); + return result == PluginManager.EmbedDrawn ? want : Vector2.Zero; + } + + // ── Session Stats overview ────────────────────────────────────────── + + /// + /// The Session Stats section's stand-in (shown only while no plugin fills the section; RynthAi + /// does): this session's XP and luminance with their per-hour rates, from the engine's + /// SessionRates, the same formula RynthAi, RynthTracker, RynthOracle and RynthILT use. + /// Character details are RynthOracle's Character tab; server picks are Options > Diagnostics. + /// + private void DrawOverview(SectionRegistry.Snapshot snap, Vector2 box) + { + ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, new Vector2(2, 2)); + bool open = ImGuiNET.ImGui.BeginChild("##mr_overview", box, ImGuiChildFlags.AlwaysUseWindowPadding, ImGuiWindowFlags.NoBackground); + ImGuiNET.ImGui.PopStyleVar(); + try + { + if (!open) return; + string who = SessionStateRegistry.LastCharacterName; + Label(who.Length > 0 ? who : "No character logged in", Teal); + float w = ImGuiNET.ImGui.GetContentRegionAvail().X; + Separator(w); + + SessionRatesView r = EngineStatusMetrics.SessionView(); + if (r.Seconds <= 0) + { + ImGuiNET.ImGui.TextDisabled("The session starts once a character is in the world."); + return; + } + StatRow("Session", FormatDuration(r.Seconds)); + StatRow("XP", $"{Compact(r.Xp)} ({Compact(r.XpPerHour)}/hr)"); + StatRow("Luminance", $"{Compact(r.Lum)} ({Compact(r.LumPerHour)}/hr)"); + ImGuiNET.ImGui.Spacing(); + ImGuiNET.ImGui.PushTextWrapPos(0f); + ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, Faded(Mute)); + SafeImGui.TextWrapped("Kills, deaths and per-kill XP come with RynthAi's session stats. " + + "Character details: RynthOracle's Character tab (/ro character). Server picks: Options > Diagnostics."); + ImGuiNET.ImGui.PopStyleColor(); + ImGuiNET.ImGui.PopTextWrapPos(); + } + finally + { + ImGuiNET.ImGui.EndChild(); + } + } + + /// One "label value" row of the overview. + private static void StatRow(string label, string value) + { + Label(label, Mute); + ImGuiNET.ImGui.SameLine(90f); + ImGuiNET.ImGui.TextUnformatted(value); + } + + /// 12.3k, 4.5m, 1.2b (the Mini Remote's compact numbers). + private static string Compact(double v) + { + double a = Math.Abs(v); + if (a >= 1e9) return (v / 1e9).ToString("0.0", System.Globalization.CultureInfo.InvariantCulture) + "b"; + if (a >= 1e6) return (v / 1e6).ToString("0.0", System.Globalization.CultureInfo.InvariantCulture) + "m"; + if (a >= 1e4) return (v / 1e3).ToString("0.0", System.Globalization.CultureInfo.InvariantCulture) + "k"; + return v.ToString("0", System.Globalization.CultureInfo.InvariantCulture); + } + + /// "1h 05m" or "4m 12s". + private static string FormatDuration(double seconds) + { + var t = TimeSpan.FromSeconds(Math.Max(0, seconds)); + return t.TotalHours >= 1 ? $"{(int)t.TotalHours}h {t.Minutes:00}m" : $"{t.Minutes}m {t.Seconds:00}s"; + } + // ── Menu ──────────────────────────────────────────────────────────── + + /// The menu's section half: every section, the active servers' items, the rail switch. + private void DrawSectionsMenuItems() + { + SectionRegistry.Snapshot snap = SectionRegistry.Current; + if (ImGuiNET.ImGui.MenuItem("Remote##sec_remote", "", IsRemote)) SelectSection(SectionCatalog.RemoteId); + foreach (SectionView v in snap.Sections) + if (ImGuiNET.ImGui.MenuItem(v.Label + "##sec_" + v.Id, "", v.Id.Equals(_section, StringComparison.OrdinalIgnoreCase))) + SelectSection(v.Id); + ServerMenus.DrawImGuiMenu(separatorFirst: true); + 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 ."); + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.cs b/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.cs index b84f73c..0a6c73b 100644 --- a/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/MiniRemoteFace.cs @@ -1,11 +1,16 @@ // ============================================================================ // RynthCore.Engine - ImGui/Panels/MiniRemoteFace.cs -// The Mini Remote: one window for the quick-use item slots, whoever draws them. +// The Mini Remote: one window for the quick-use item slots, whoever draws them, +// and the sections (MiniRemoteFace.Sections.cs): a rail down the left with +// Remote (this file) and the core sections Char, Map, Skills, Combat, Nav, +// Inventory, Crafting, Spells, Chat, Friends, Fellowship and Pets, plus any a +// plugin adds, each showing its engine panels or plugin views and the active +// servers' options (UI/Sections). // // With RynthAi loaded it hosts RynthAi's Mini Remote (session rates, target, // summon, item slots, toggles, bank, rebuff, Translate, Guardian and its // Options menu, its Quests and Pets tabs, plus on ILT worlds the RynthILT -// plugin's tabs Character, Banking, Gear, Charms and Games, which RynthAi asks +// plugin's tabs Gear and Games (Character and Charms moved to RynthOracle, Banking to RynthInventory, 2026.10.5.54), which RynthAi asks // RynthILT to draw), drawn by the plugin through // RynthPluginRenderEmbed ("miniremote-window"). The window fits itself to what // the plugin asks for whenever that changes (another tab, a section shown or @@ -47,7 +52,7 @@ using static RynthCore.Engine.ImGuiBackend.Panels.FaceKit; namespace RynthCore.Engine.ImGuiBackend.Panels; -internal sealed class MiniRemoteFace : IImGuiPanel +internal sealed partial class MiniRemoteFace : IImGuiPanel { public const string Title = "Mini Remote"; @@ -59,8 +64,21 @@ internal sealed class MiniRemoteFace : IImGuiPanel ItemHudStore.EnsureLoadQueued(); } - /// The RynthAi surface for this window (NUL-terminated for the export). - private static ReadOnlySpan Surface => "miniremote-window\0"u8; + /// + /// The RynthAi surface for this window (NUL-terminated for the export): "miniremote-remote" + /// (the remote alone: its tabs are sections here) from a RynthAi that publishes sections + /// while the sections rail shows, else "miniremote-window" (the remote with its own tab bar). + /// With the rail hidden the tab bar is the only way to RynthILT's tabs (Gear, Games). + /// + private static ReadOnlySpan Surface => + RailShown && RynthAiPublishesSections() ? "miniremote-remote\0"u8 : "miniremote-window\0"u8; + + private static bool RynthAiPublishesSections() + { + foreach (UI.Sections.SectionManifest m in UI.Sections.SectionRegistry.Current.Manifests) + if (m.Plugin.Contains("RynthAi", StringComparison.OrdinalIgnoreCase)) return true; + return false; + } private const float Gap = 4f, StatusH = 18f; /// Pixels a Ctrl+wheel notch or a Bigger / Smaller menu click changes the box edge by. @@ -116,12 +134,39 @@ internal sealed class MiniRemoteFace : IImGuiPanel public void Draw() { float w = Begin(out Vector2 origin, out Vector2 size); - if (DrawRynthAi(w, origin, size)) - { - End(origin, size); - return; - } + UI.Sections.SectionRegistry.Snapshot snap = UI.Sections.SectionRegistry.Current; + TakeRequestedSection(snap); + // 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) + { + ImGuiNET.ImGui.SetCursorScreenPos(origin + new Vector2(6 + railW, 6)); + ImGuiNET.ImGui.Indent(railW); + } + float cw = Math.Max(40f, w - railW); + try + { + if (!IsRemote) + { + // This window is still the Mini Remote while it shows another section: RynthAi + // keeps its floating copy hidden while it hears from it each frame. + if (!_embedOff) PingRynthAiHost(); + DrawSection(snap, cw, origin, size); + } + else if (!DrawRynthAi(cw, origin, size)) DrawEngineGrid(cw, origin, size); + } + finally + { + if (railW > 0) ImGuiNET.ImGui.Unindent(railW); + } + End(origin, size); + DrawMenu(); + } + + /// The engine's own slot grid (no RynthAi to draw the remote). + private void DrawEngineGrid(float w, Vector2 origin, Vector2 size) + { InventoryView view = InventoryModel.Current; HudItem[] items = _items.Get(view); ItemHudCharacter data = ItemHudStore.Current; @@ -133,8 +178,6 @@ internal sealed class MiniRemoteFace : IImGuiPanel DrawGrid(data, items, w, gridH, ready); DrawStatus(ready); FitGrid(data, w, haveH); - End(origin, size); - DrawMenu(data, items); } // ── RynthAi's Mini Remote ─────────────────────────────────────────── @@ -184,6 +227,15 @@ internal sealed class MiniRemoteFace : IImGuiPanel return true; } + /// "miniremote-host": tells RynthAi this window is open on a section; it draws nothing. + private void PingRynthAiHost() + { + int result; + try { result = PluginManager.RenderEmbed("RynthAi", "miniremote-host\0"u8, Vector2.Zero, out _); } + catch { result = PluginManager.EmbedFailed; } + if (result == PluginManager.EmbedFailed) _embedOff = true; + } + // ── Window fit ────────────────────────────────────────────────────── /// @@ -301,7 +353,7 @@ internal sealed class MiniRemoteFace : IImGuiPanel dl.AddText(cp, id == 0 ? Amber : Text, count); } if (hot) - ImGuiNET.ImGui.SetItemTooltip(id == 0 + SafeImGui.SetItemTooltip(id == 0 ? $"{s.Name}: none carried.\nRight-click for options." : $"{s.Name} ({count switch { "" => "1", _ => count }} carried)\nClick to use. Right-click for options."); } @@ -391,7 +443,11 @@ internal sealed class MiniRemoteFace : IImGuiPanel // ── Right-click menu ──────────────────────────────────────────────── - private void DrawMenu(ItemHudCharacter data, HudItem[] items) + /// + /// The right-click menu: a slot's options (the engine grid), then the sections, the active + /// servers' items and the rail switch. Opened from a slot or from the rail. + /// + private void DrawMenu() { if (_openMenu) { @@ -407,6 +463,23 @@ internal sealed class MiniRemoteFace : IImGuiPanel ImGuiNET.ImGui.PopStyleColor(3); if (!open) return; + try + { + if (_menuSlot >= 0 && IsRemote) + { + DrawSlotMenu(ItemHudStore.Current, _items.Get(InventoryModel.Current)); + ImGuiNET.ImGui.Separator(); + } + DrawSectionsMenuItems(); + } + finally + { + ImGuiNET.ImGui.EndPopup(); + } + } + + private void DrawSlotMenu(ItemHudCharacter data, HudItem[] items) + { int i = _menuSlot; RemoteSlot? s = i >= 0 && i < data.Slots.Length ? data.Slots[i] : null; Label(i >= 0 ? $"Slot {i + 1}{(s != null ? ": " + s.Name : " (empty)")}" : "Mini Remote", Mute); @@ -430,6 +503,5 @@ internal sealed class MiniRemoteFace : IImGuiPanel ResizeSlots(-SlotSizeStep); if (ImGuiNET.ImGui.MenuItem("Default box size", "", false, px != ItemHudCharacter.DefaultSlotSize)) ResizeSlots(ItemHudCharacter.DefaultSlotSize - px); - ImGuiNET.ImGui.EndPopup(); } } diff --git a/src/RynthCore.Engine/ImGui/Panels/NavFace.cs b/src/RynthCore.Engine/ImGui/Panels/NavFace.cs index 36d4235..f8ca69f 100644 --- a/src/RynthCore.Engine/ImGui/Panels/NavFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/NavFace.cs @@ -296,7 +296,7 @@ internal sealed class NavFace : IImGuiPanel { string text = (on ? PhosphorIcons.CheckSquare : PhosphorIcons.Square) + " " + label; bool clicked = Button(id, text, pos, new Vector2(width, 22), on ? Teal : Mute, BtnFill, leftAlign: true); - if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(tooltip); + if (ImGuiNET.ImGui.IsItemHovered()) SafeImGui.SetTooltip(tooltip); return clicked; } @@ -324,7 +324,7 @@ internal sealed class NavFace : IImGuiPanel dl.AddText(new Vector2(p.X, p.Y + (22 - ImGuiNET.ImGui.GetFontSize()) * 0.5f), Mute, label); ImGuiNET.ImGui.SetCursorScreenPos(p); ImGuiNET.ImGui.InvisibleButton("##reach_label", new Vector2(Math.Max(1, labelW), 22)); - if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(SettingsSchema.NavPointReachTip); + if (ImGuiNET.ImGui.IsItemHovered()) SafeImGui.SetTooltip(SettingsSchema.NavPointReachTip); const float stepW = 22, boxW = 52; float right = p.X + w; @@ -456,7 +456,7 @@ internal sealed class NavFace : IImGuiPanel _picker.Open(new Vector2(tp.X, tp.Y + 22), NavCommands.TrailChoices, -1, i => NavCommands.Send(new NavCmd { Cmd = "trailToRoute", Reverse = i == 1 }), width: 300); if (ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled)) - ImGuiNET.ImGui.SetTooltip(_data.TrailPoints >= 2 + SafeImGui.SetTooltip(_data.TrailPoints >= 2 ? $"Breadcrumb trail: {_data.TrailPoints} crumbs, {_data.TrailYards:0} yd.\nThe new route is unsaved; the loaded nav file is not changed." : "Turn on Breadcrumbs and walk a while to build a trail."); NextLine(p, 26); diff --git a/src/RynthCore.Engine/ImGui/Panels/P1Faces.cs b/src/RynthCore.Engine/ImGui/Panels/P1Faces.cs index d1c7f66..0d99fe3 100644 --- a/src/RynthCore.Engine/ImGui/Panels/P1Faces.cs +++ b/src/RynthCore.Engine/ImGui/Panels/P1Faces.cs @@ -130,14 +130,14 @@ internal sealed class StatusFace : IImGuiPanel private static void Header(string text) { ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); - ImGuiNET.ImGui.TextColored(HeaderColor, text); + SafeImGui.TextColored(HeaderColor, text); ImGuiNET.ImGui.PopFont(); } private static void Row(string text, bool error) { ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, error ? ErrorColor : RowColor); - ImGuiNET.ImGui.TextWrapped(text); + SafeImGui.TextWrapped(text); ImGuiNET.ImGui.PopStyleColor(); } @@ -274,7 +274,7 @@ internal sealed class TrackerFace : IImGuiPanel { float rowRight = ImGuiNET.ImGui.GetCursorPosX() + ImGuiNET.ImGui.GetContentRegionAvail().X; if (ImGuiNET.ImGui.GetCursorScreenPos().Y + rowH > gripTop) rowRight -= grip; - ImGuiNET.ImGui.TextColored(LabelColor, labels[i]); + SafeImGui.TextColored(LabelColor, labels[i]); if (labels[i].StartsWith("Pass", StringComparison.Ordinal)) ImGuiNET.ImGui.SetItemTooltip("Luminance that reached your bank without a \"You've banked\" line: your vassals' pass-up.\nFellowship and Zone Share splits arrive the same silent way and are included."); else if (labels[i] == "Lum/5m") diff --git a/src/RynthCore.Engine/ImGui/Panels/RadarFace.cs b/src/RynthCore.Engine/ImGui/Panels/RadarFace.cs index f1ef7a4..0a4ec03 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RadarFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RadarFace.cs @@ -130,7 +130,7 @@ internal sealed class RadarFace : IImGuiPanel { if (IconButton("##radar_pop", popPos, ImGuiPanelHost.PopOutGlyph)) ImGuiPanelHost.TogglePopOut(Title); - ImGuiNET.ImGui.SetItemTooltip(ImGuiPanelHost.PopOutTooltip); + SafeImGui.SetItemTooltip(ImGuiPanelHost.PopOutTooltip); } bool gear = IconButton("##radar_gear", gearPos, PhosphorIcons.Gear); ImGuiNET.ImGui.SetItemTooltip("Radar settings"); @@ -629,7 +629,7 @@ internal sealed class RadarFace : IImGuiPanel bool sub = kind == RadarKind.OwnCorpse; if (sub) { ImGuiNET.ImGui.Indent(14 * scale); ImGuiNET.ImGui.BeginDisabled(!RadarSettingsStore.ShowCorpses); } changed |= ImGuiNET.ImGui.Checkbox("##show", ref RadarSettingsStore.ShowFlag(kind)); - if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(KindTips[kind]); + if (ImGuiNET.ImGui.IsItemHovered()) SafeImGui.SetTooltip(KindTips[kind]); ImGuiNET.ImGui.SameLine(); // The marker exactly as the radar draws it; faded while the kind is hidden, so the // legend doesn't look like the box did nothing. @@ -643,7 +643,7 @@ internal sealed class RadarFace : IImGuiPanel ImGuiNET.ImGui.SameLine(); ImGuiNET.ImGui.AlignTextToFramePadding(); ImGuiNET.ImGui.TextUnformatted(label); - if (ImGuiNET.ImGui.IsItemHovered()) ImGuiNET.ImGui.SetTooltip(KindTips[kind]); + if (ImGuiNET.ImGui.IsItemHovered()) SafeImGui.SetTooltip(KindTips[kind]); ImGuiNET.ImGui.SameLine(190 * scale); Vector4 v = RynthTheme.Vec(RadarSettingsStore.KindColors[kind]); if (ImGuiNET.ImGui.ColorEdit4("##col", ref v, pickFlags)) diff --git a/src/RynthCore.Engine/ImGui/Panels/RangesSlideOut.cs b/src/RynthCore.Engine/ImGui/Panels/RangesSlideOut.cs index 3e275dc..58c3ad0 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RangesSlideOut.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RangesSlideOut.cs @@ -203,7 +203,7 @@ internal sealed class RangesSlideOut : DashboardDrawer dl.AddText(new Vector2(x, y + (h - fs) * 0.5f), White, r.Label); ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, y)); ImGuiNET.ImGui.InvisibleButton("##label", new Vector2(Math.Max(1, labelW - 2 * k), h)); - ImGuiNET.ImGui.SetItemTooltip(r.Tip); + SafeImGui.SetItemTooltip(r.Tip); // Box at the right. float boxW = 46 * k; @@ -221,7 +221,7 @@ internal sealed class RangesSlideOut : DashboardDrawer } else WriteValue(r, value); // bad input reverts } - ImGuiNET.ImGui.SetItemTooltip(r.Tip); + SafeImGui.SetItemTooltip(r.Tip); // Slider between them: drag (or click) to pick, saved when let go. float sx = x + labelW, sw = boxX - 6 * k - sx; @@ -245,7 +245,7 @@ internal sealed class RangesSlideOut : DashboardDrawer r.Dragging = false; if (r.DragValue != value) Changed(r, r.DragValue); } - ImGuiNET.ImGui.SetItemTooltip(r.Tip); + SafeImGui.SetItemTooltip(r.Tip); float cy = y + h * 0.5f; float frac = s.Max > s.Min ? (float)((shownValue - s.Min) / (s.Max - s.Min)) : 0f; @@ -316,13 +316,13 @@ internal sealed class RangesSlideOut : DashboardDrawer if (FaceKit.IconButton("##mon_edit", PhosphorIcons.PencilSimple, new Vector2(bx, y), bsize, monster ? Teal : Mute, BtnFill, enabled: monster, border: BtnBord, font: UiFont.Dash10)) DamageDetailFace.Show(_selWcid, _selName); - ImGuiNET.ImGui.SetItemTooltip(monster ? _editTip : NoEditTip); + SafeImGui.SetItemTooltip(monster ? _editTip : NoEditTip); if (FaceKit.IconButton("##mon_damage", PhosphorIcons.Skull, new Vector2(bx + bsize.X + 2 * k, y), bsize, monster ? Teal : Mute, BtnFill, enabled: monster, border: BtnBord, font: UiFont.Dash10)) { if (!ImGuiPanelHost.IsOpen(DamageFace.Title)) PanelRouter.ToggleMonsters(); } - ImGuiNET.ImGui.SetItemTooltip(monster ? _damageTip : NoDamageTip); + SafeImGui.SetItemTooltip(monster ? _damageTip : NoDamageTip); // Name line. string name; uint nameColor; @@ -357,7 +357,7 @@ internal sealed class RangesSlideOut : DashboardDrawer { ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x, fy)); ImGuiNET.ImGui.InvisibleButton("##mon_facts", new Vector2(w, 2 * lh)); - ImGuiNET.ImGui.SetItemTooltip(_factsTip); + SafeImGui.SetItemTooltip(_factsTip); } } diff --git a/src/RynthCore.Engine/ImGui/Panels/ReportFace.cs b/src/RynthCore.Engine/ImGui/Panels/ReportFace.cs index b93449c..e150b44 100644 --- a/src/RynthCore.Engine/ImGui/Panels/ReportFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/ReportFace.cs @@ -149,7 +149,7 @@ internal sealed class ReportFace : IImGuiPanel if (Button("##report_send", label, row, new Vector2(bw, 24), Text, StartBg, enabled: enabled)) StartSend(); if (ImGuiNET.ImGui.IsItemHovered(ImGuiHoveredFlags.AllowWhenDisabled | ImGuiHoveredFlags.ForTooltip)) - ImGuiNET.ImGui.SetTooltip(!hasText ? "Write what went wrong first." + SafeImGui.SetTooltip(!hasText ? "Write what went wrong first." : cooldown > 0 ? "One report a minute: " + CooldownText(cooldown) : "Send this report to the staff."); NextLine(row, 28); diff --git a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.Drawers.cs b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.Drawers.cs index e92559c..5b74fd4 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.Drawers.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.Drawers.cs @@ -16,8 +16,8 @@ // item slots, toggles, bank, rebuff, Translate, Guardian) // with its Options menu. The plugin draws it here through // RynthPluginRenderEmbed("miniremote") and says how big it -// wants the panel; the Hub launcher's right-click opens it -// (popped out: the floating Mini Remote instead). +// wants the panel; its drawer tab opens it (popped out +// there are no drawers: the Mini Remote window instead). // AC thread only (inside the dashboard's Draw). // ============================================================================ @@ -149,7 +149,7 @@ internal sealed partial class RynthAiFace } } - /// RynthAi's Mini Remote, drawn by the plugin into this drawer (the Hub launcher's right-click). + /// RynthAi's Mini Remote, drawn by the plugin into this drawer (its drawer tab). private sealed class RemoteDrawer : DashboardDrawer { /// The plugin surface name, NUL-terminated for the export. @@ -169,7 +169,7 @@ internal sealed partial class RynthAiFace public override string TabTooltip(bool right) => "Mini Remote: session rates, attack target, summon, item slots, toggles, bank, rebuff, Translate.\n" + - "Its Options button picks the sections (also: right-click Hub). RynthILT's ILT tabs are in the Mini Remote window.\n" + + "Its Options button picks the sections. RynthILT's ILT tabs are in the Mini Remote window (Char, or the bar button).\n" + (right ? "Click to slide it out (to the right: there's no room on the left)." : "Click to slide it out."); public override float Width(float k) => @@ -209,12 +209,12 @@ internal sealed partial class RynthAiFace { _want = Vector2.Zero; ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, DMute); - ImGuiNET.ImGui.TextWrapped(result switch + SafeImGui.TextWrapped(result switch { PluginManager.EmbedNoPlugin => - "This RynthAi can't draw its Mini Remote here (it needs RynthAi 0.5.27 or later). Left-click Hub for the floating Mini Remote.", + "This RynthAi can't draw its Mini Remote here (it needs RynthAi 0.5.27 or later). Use the bar's Mini Remote button (/rc miniremote).", PluginManager.EmbedFailed => - "The Mini Remote failed to draw here (see the log). Left-click Hub for the floating Mini Remote.", + "The Mini Remote failed to draw here (see the log). Use the bar's Mini Remote button (/rc miniremote).", _ => "The Mini Remote shows here once RynthAi is ready: in the world, with plugin windows on (engine.json EnablePluginOverlayWindows).", }); ImGuiNET.ImGui.PopStyleColor(); diff --git a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs index 7c15d42..719d72c 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RynthAiFace.cs @@ -254,7 +254,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y)); ImGuiNET.ImGui.InvisibleButton("##dash_drag", new Vector2(Math.Max(1, width - chipsW), rowH)); ImGuiPanelHost.DragWindowWithLastItem(); - ImGuiNET.ImGui.SetItemTooltip(DragTip); + SafeImGui.SetItemTooltip(DragTip); ImFontPtr title = ImGuiFonts.Get(UiFont.Dash14); float ty = y + (rowH - title.FontSize) * 0.5f; @@ -275,7 +275,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel RynthAiDashboardState.SetShowTargetBar(!target); _fit = true; } - ImGuiNET.ImGui.SetItemTooltip(target + SafeImGui.SetItemTooltip(target ? "Target bar on: the target's name and health at the bottom. Click to hide it." : "Target bar off. Click to show the target's name and health at the bottom."); cx += chipW + chipGap; @@ -285,14 +285,14 @@ internal sealed partial class RynthAiFace : IImGuiPanel RynthAiDashboardState.SetShowVitals(!vitals); _fit = true; } - ImGuiNET.ImGui.SetItemTooltip(vitals + SafeImGui.SetItemTooltip(vitals ? "Player vitals on: your health, stamina and mana at the bottom. Click to hide them." : "Player vitals off. Click to show your health, stamina and mana at the bottom."); cx += chipW + chipGap; if (IconButton("##chip_lock", new Vector2(cx, cy), chip, raw.IsLocked ? PhosphorIcons.Lock : PhosphorIcons.LockOpen, chipFont, BtnFill, raw.IsLocked ? Amber : Mute, BtnBord, chipRound)) RynthAiCommands.TogglePanelLock(); - ImGuiNET.ImGui.SetItemTooltip(raw.IsLocked ? "Locked. Click to unlock the dashboard." : "Click to lock the dashboard in place."); + SafeImGui.SetItemTooltip(raw.IsLocked ? "Locked. Click to unlock the dashboard." : "Click to lock the dashboard in place."); cx += chipW + chipGap; if (IconButton("##chip_minus", new Vector2(cx, cy), chip, PhosphorIcons.Minus, chipFont, BtnFill, Mute, BtnBord, chipRound)) RynthAiCommands.AdjustOpacity(-0.1f); @@ -308,13 +308,13 @@ internal sealed partial class RynthAiFace : IImGuiPanel RynthAiDashboardState.SetMinimized(!minimized); _fit = true; // the window fits the other mode's content next frame } - ImGuiNET.ImGui.SetItemTooltip(minimized ? "Expand" : "Minimize"); + SafeImGui.SetItemTooltip(minimized ? "Expand" : "Minimize"); cx += chipW + chipGap; if (PanelRouter.CanPopOut) { if (IconButton("##chip_dock", new Vector2(cx, cy), chip, ImGuiPanelHost.PopOutGlyph, chipFont, BtnFill, Mute, BtnBord, chipRound)) ImGuiPanelHost.TogglePopOut(Title); - ImGuiNET.ImGui.SetItemTooltip(ImGuiPanelHost.PopOutTooltip); + SafeImGui.SetItemTooltip(ImGuiPanelHost.PopOutTooltip); } // The size, from the title row (no host title bar here): Ctrl+wheel steps it, right-click @@ -533,7 +533,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel if (IconButton("##macro", new Vector2(x, y), square, on ? PhosphorIcons.Stop : PhosphorIcons.Play, UiFont.Dash14, on ? MacroRun : BarBg, on ? White : Mute, on ? Green : BtnBord, round)) RynthAiCommands.ToggleMacro(); - ImGuiNET.ImGui.SetItemTooltip(on ? "Macro running. Click to stop it." : "Macro stopped. Click to start it."); + SafeImGui.SetItemTooltip(on ? "Macro running. Click to stop it." : "Macro stopped. Click to start it."); x += sqStep + Px(6); } Toggle("##t_combat", PhosphorIcons.Sword, raw.CombatEnabled, 0, new Vector2(x, y), "Combat"); @@ -554,7 +554,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel if (IconButton("##t_sort", new Vector2(x, y), square, PhosphorIcons.SortAscending, UiFont.Dash14, on ? TealSoft : BarBg, on ? Teal : Mute, on ? Teal : BtnBord, round)) RynthSortCommands.SetAuto(!on); - ImGuiNET.ImGui.SetItemTooltip(on ? "Auto-sort (RynthSort) on. Click to turn it off." : "Auto-sort (RynthSort) off. Click to turn it on."); + SafeImGui.SetItemTooltip(on ? "Auto-sort (RynthSort) on. Click to turn it off." : "Auto-sort (RynthSort) off. Click to turn it on."); x += sqStep; } @@ -568,7 +568,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel if (IconButton("##files_open", new Vector2(frX - Px(4) - caretW, y), new Vector2(caretW, sq), PhosphorIcons.CaretDown, UiFont.Dash11, BtnFill, Teal, BtnBord, Px(2))) RynthAiDashboardState.SetFilesOpen(true); - ImGuiNET.ImGui.SetItemTooltip("Profile: " + (view?.ProfileText ?? "Default") + "\nNav: " + (view?.NavText ?? "None") + + SafeImGui.SetItemTooltip("Profile: " + (view?.ProfileText ?? "Default") + "\nNav: " + (view?.NavText ?? "None") + "\nLoot: " + (view?.LootText ?? "None") + "\nMeta: " + (view?.MetaText ?? "None") + "\nBuffs: " + (view?.BuffText ?? "Built-in") + "\n\nClick to show the Profile, Nav, Loot, Meta and Buffs pickers."); @@ -587,7 +587,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel dl.PopClipRect(); ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(ax, y)); ImGuiNET.ImGui.InvisibleButton("##activity", new Vector2(aRight - ax, sq)); - ImGuiNET.ImGui.SetItemTooltip("Bot activity: " + activity + "\nMeta state: " + (view?.MetaStateText ?? "Default")); + SafeImGui.SetItemTooltip("Bot activity: " + activity + "\nMeta state: " + (view?.MetaStateText ?? "Default")); } } @@ -607,7 +607,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel { if (IconButton(id, pos, new Vector2(Px(Square), Px(Square)), icon, UiFont.Dash14, on ? TealSoft : BarBg, on ? Teal : Mute, on ? Teal : BtnBord, Px(3))) RynthAiCommands.SetSubsystemEnabled(subsystem, !on); - ImGuiNET.ImGui.SetItemTooltip(on ? name + " on. Click to turn it off." : name + " off. Click to turn it on."); + SafeImGui.SetItemTooltip(on ? name + " on. Click to turn it off." : name + " off. Click to turn it on."); } // ── Launchers: one row of icon buttons ────────────────────────────── @@ -617,7 +617,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel private void Launchers(float x0, float width) { float y = ImGuiNET.ImGui.GetCursorScreenPos().Y; - const int buttons = 10; + const int buttons = 9; float gap = Px(LauncherGap); float bw = MathF.Floor((width - buttons * gap) / buttons); // Short labels only when every button has room for its icon and label. @@ -659,30 +659,18 @@ internal sealed partial class RynthAiFace : IImGuiPanel } x += bw + gap; - // Char and Hub open the Mini Remote window (MiniRemoteFace, hosting RynthAi's remote): Char - // on its Character tab (RynthILT's ILT tab; elsewhere the remote shows), Hub as it was left. + // Char opens RynthOracle's Character tab (character, level XP, session rates and, on + // Infinite Leaftide, the charms) since 2026.10.5.54; without RynthOracle, the Mini Remote's + // Session Stats section. The Mini Remote as it was left is the bar button (/rc miniremote) + // and "Mini Remote" in Char's right-click menu; its drawer is the drawer tab on the dashboard's edge. Launcher("##l_char", PhosphorIcons.User, "Char", - "Char. Left-click: the Mini Remote on its Character tab (ILT worlds). Right-click: Character windows (Spells, Quests, Pets, Skills, Inventory...), then Server: this server's plugin windows.", - x, y, bw, labels, () => ShowMiniRemoteTab("character")); + "Char. Left-click: RynthOracle's Character tab (charms on Infinite Leaftide). Right-click: Character windows (Mini Remote, Spells, Quests, Pets, Crafting, Fellowship, Skills, Inventory...), then Server: this server's plugin windows.", + x, y, bw, labels, ShowCharacter); if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) { ImGuiNET.ImGui.SetNextWindowPos(ImGuiNET.ImGui.GetItemRectMin(), ImGuiCond.Always, new Vector2(0, 1)); ImGuiNET.ImGui.OpenPopup("##charmenu"); } - x += bw + gap; - // Left-click is the Mini Remote window (MiniRemoteFace, which hosts RynthAi's remote, the - // same window as the bar button). Right-click is the Mini Remote drawer, as Patrol's is - // its drawer; popped out there are no drawers, so it opens the window. Inventory HUDs - // setup is in the Mini Remote's Options menu. - Launcher("##l_hub", PhosphorIcons.SquaresFour, "Hub", - popped ? "Hub. Left-click: the Mini Remote window (/rc miniremote). Right-click: open the Mini Remote window." - : "Hub. Left-click: the Mini Remote window (/rc miniremote). Right-click: the Mini Remote drawer (left), with its Options.", - x, y, bw, labels, () => PanelRouter.Toggle(MiniRemoteFace.Title)); - if (ImGuiNET.ImGui.IsItemClicked(ImGuiMouseButton.Right)) - { - if (popped) ImGuiPanelHost.Open(MiniRemoteFace.Title); - else _drawers.Toggle(_remote); - } ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x0, y + Px(LauncherH))); } @@ -695,7 +683,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel var dl = ImGuiNET.ImGui.GetWindowDrawList(); ImGuiNET.ImGui.SetCursorScreenPos(pos); bool clicked = ImGuiNET.ImGui.InvisibleButton(id, size); - ImGuiNET.ImGui.SetItemTooltip(tooltip); + SafeImGui.SetItemTooltip(tooltip); uint fill = ImGuiNET.ImGui.IsItemActive() ? Darken(BtnFill) : ImGuiNET.ImGui.IsItemHovered() ? Lighten(BtnFill) : BtnFill; dl.AddRectFilled(pos, pos + size, fill, Px(3)); dl.AddRect(pos, pos + size, BtnBord, Px(3)); @@ -885,9 +873,10 @@ internal sealed partial class RynthAiFace : IImGuiPanel // (UI.ServerMenus): the installed server plugins' windows for the world you're on. /// - /// Opens the Mini Remote window on one of its tabs ("" = the remote). Quests and Pets show on - /// every server; RynthILT's ILT tabs show once the server reports that feature on (and only with - /// RynthILT), and until then the window shows the remote. + /// Opens the Mini Remote window on one of its tabs ("" = the remote). Pets and Crafting show on + /// every server (Quests and Fellowship are RynthOracle's windows since 2026-10-13); RynthILT's ILT + /// tabs show once the server reports that feature on (and only with RynthILT), and until then + /// the window shows the remote. /// private static void ShowMiniRemoteTab(string section) { @@ -895,6 +884,16 @@ internal sealed partial class RynthAiFace : IImGuiPanel RynthAiCommands.ApplyRemoteCommand("hub", section.Length > 0 ? "tab " + section : "tab"); } + /// + /// RynthOracle's Character tab ("/ro character"), or the Mini Remote's Session Stats section + /// when RynthOracle isn't loaded. Every "Character" / "Charms" link goes here. + /// + private static void ShowCharacter() + { + if (UI.ScriptWindows.ScriptWindowRegistry.Has(OracleMainKey)) UI.ServerMenus.Run("/ro character"); + else UI.ServerMenus.Run("/rc miniremote section char"); + } + /// A Char menu item that toggles a registered ImGui panel (checked while open). private static void PanelMenuItem(string title, string command) { @@ -903,6 +902,23 @@ internal sealed partial class RynthAiFace : IImGuiPanel PanelRouter.Toggle(title); } + // RynthOracle's script window keys (RynthOraclePlugin: UiWindow keys). + private const string OracleMainKey = "RynthOracle/Oracle"; + private const string OracleTimersKey = "RynthOracle/QuestTimers"; + + /// + /// A Character menu line for one of RynthOracle's script windows: toggles it as the bar does, + /// checked while open, greyed out when RynthOracle isn't loaded (or hasn't drawn it yet). + /// + private static void OracleMenuItem(string label, string command, string key, string tooltip) + { + bool has = UI.ScriptWindows.ScriptWindowRegistry.Has(key); + bool open = has && UI.ScriptWindows.ScriptWindowRegistry.IsOpen(key); + if (ImGuiNET.ImGui.MenuItem(label, command, open, has)) + UI.ScriptWindows.ScriptWindowRegistry.PlayerSetVisible(key, !open); + ImGuiNET.ImGui.SetItemTooltip(has ? tooltip : tooltip + " (RynthOracle isn't loaded.)"); + } + private static void CharMenu() { ImGuiNET.ImGui.PushStyleColor(ImGuiCol.PopupBg, ShellBg); @@ -915,16 +931,32 @@ internal sealed partial class RynthAiFace : IImGuiPanel try { ImGuiNET.ImGui.TextDisabled("Character"); + bool hasOracle = UI.ScriptWindows.ScriptWindowRegistry.Has(OracleMainKey); + if (ImGuiNET.ImGui.MenuItem("Character", "/ro character", false, hasOracle)) ShowCharacter(); + ImGuiNET.ImGui.SetItemTooltip(hasOracle + ? "RynthOracle's Character tab: level, XP, session rates and (Infinite Leaftide) your charms." + : "RynthOracle's Character tab (RynthOracle isn't loaded)."); if (ImGuiNET.ImGui.MenuItem("Mini Remote", "/rc miniremote", ImGuiPanelHost.IsOpen(MiniRemoteFace.Title))) ShowMiniRemoteTab(""); if (ImGuiNET.ImGui.MenuItem("Spells", "/rc spells")) RynthAiCommands.ApplyRemoteCommand("spells", "toggle"); ImGuiNET.ImGui.SetItemTooltip("RynthAi Spells: the spell catalog and buff profiles."); + // Quests live in RynthOracle (its script windows), since 2026-10-13. + OracleMenuItem("Quests", "/ro", OracleMainKey, + "RynthOracle: every quest flag, timers, tracking, rewards and (Infinite Leaftide) the /qb list."); + OracleMenuItem("Quest Timers", "/ro timers", OracleTimersKey, + "RynthOracle's Quest Timers: the quests you track and the time left on each."); // The Mini Remote's universal tabs (every server); RynthILT's ILT tabs are in the server half. - if (ImGuiNET.ImGui.MenuItem("Quests", "/rc miniremote tab quests")) ShowMiniRemoteTab("quests"); - ImGuiNET.ImGui.SetItemTooltip("The Mini Remote's Quests tab: /myquests timers and favorites (RynthAi)."); if (ImGuiNET.ImGui.MenuItem("Pets", "/rc miniremote tab pets")) ShowMiniRemoteTab("pets"); ImGuiNET.ImGui.SetItemTooltip("The Mini Remote's Pets tab: summoning essences, priorities and the healing pet (RynthAi)."); + if (ImGuiNET.ImGui.MenuItem("Crafting", "/rc miniremote tab crafting")) ShowMiniRemoteTab("crafting"); + ImGuiNET.ImGui.SetItemTooltip("The Mini Remote's Crafting tab: armor, weapon, jewelry and item tinkering, chunking and arrows (RynthAi)."); + // Fellowship is RynthOracle's Fellowship tab ("/ro fellowship" opens the window on it). + bool oracle = hasOracle; + if (ImGuiNET.ImGui.MenuItem("Fellowship", "/ro fellowship", false, oracle)) UI.ServerMenus.Run("/ro fellowship"); + ImGuiNET.ImGui.SetItemTooltip(oracle + ? "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"); PanelMenuItem(InventoryFace.Title, "/rc inventory"); PanelMenuItem(ItemCountFace.Title, "/rc itemcount"); @@ -971,14 +1003,14 @@ internal sealed partial class RynthAiFace : IImGuiPanel if (withTitle) { ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Dash11)); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), PatrolTitle); + SafeImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), PatrolTitle); ImGuiNET.ImGui.PopFont(); } Section("THIS DUNGEON"); if (info.InDungeon) { - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), $"0x{info.CurrentLandblock} · {info.CurrentHazards} hazard cell(s)"); + SafeImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), $"0x{info.CurrentLandblock} · {info.CurrentHazards} hazard cell(s)"); if (info.CurrentHazards > 0) { ImGuiNET.ImGui.SameLine(); @@ -1008,7 +1040,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel { DungeonHazards d = info.Dungeons[i]; ImGuiNET.ImGui.PushID(i); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), $"0x{d.Landblock} · {d.Cells} cell(s)"); + SafeImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), $"0x{d.Landblock} · {d.Cells} cell(s)"); ImGuiNET.ImGui.SameLine(); if (Mini("Clear")) RynthAiCommands.SendNavCommand($"{{\"Cmd\":\"clearHazards\",\"NavName\":\"{d.Landblock}\"}}", refreshPatrol: true); @@ -1021,7 +1053,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel if (info.Routes.Length == 0) ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), "No .nav routes saved."); foreach (string name in info.Routes) - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), "• " + name); + SafeImGui.TextColored(RynthTheme.Vec(0xFFF2F7FC), "• " + name); ImGuiNET.ImGui.PopFont(); } @@ -1033,7 +1065,7 @@ internal sealed partial class RynthAiFace : IImGuiPanel { ImGuiNET.ImGui.Dummy(new Vector2(0, Px(4))); ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Dash9)); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), text); + SafeImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), text); ImGuiNET.ImGui.PopFont(); } diff --git a/src/RynthCore.Engine/ImGui/Panels/RynthNavArrowFace.cs b/src/RynthCore.Engine/ImGui/Panels/RynthNavArrowFace.cs index 4371e91..efd7f86 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RynthNavArrowFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RynthNavArrowFace.cs @@ -129,7 +129,7 @@ internal sealed class RynthNavArrowFace : IImGuiPanel { if (IconButton("##rna_pop", ImGuiPanelHost.PopOutGlyph, popPos, new Vector2(sb, sb), Done, Glass, font: UiFont.Ui9)) ImGuiPanelHost.TogglePopOut(Title); - ImGuiNET.ImGui.SetItemTooltip(ImGuiPanelHost.PopOutTooltip); + SafeImGui.SetItemTooltip(ImGuiPanelHost.PopOutTooltip); } if (IconButton("##rna_close", PhosphorIcons.X, closePos, new Vector2(sb, sb), Done, Glass, font: UiFont.Ui9)) ImGuiPanelHost.Close(Title); @@ -150,11 +150,11 @@ internal sealed class RynthNavArrowFace : IImGuiPanel if (typed.Length > 0) RynthNavCommands.Command("route " + typed); else if (st?.Arrow is RynthNavArrow pa) RynthNavCommands.Route(pa.Final, pa.FinalNs, pa.FinalEw); } - ImGuiNET.ImGui.SetItemTooltip(typed.Length > 0 + SafeImGui.SetItemTooltip(typed.Length > 0 ? "Plan a route to " + typed + " without walking it (the steps open below)" : "Plan a route to the arrow's target without walking it (the steps open below)"); bool go = IconButton("##rna_go", PhosphorIcons.Play, goPos, new Vector2(b, b), Green, BtnFill, enabled: canGo, font: UiFont.Ui11); - ImGuiNET.ImGui.SetItemTooltip(typed.Length > 0 + SafeImGui.SetItemTooltip(typed.Length > 0 ? "Go to " + typed + " (with portals and recalls when RynthNav's routing is on)" : "Go: RynthNav walks to the arrow's target (with portals and recalls when its routing is on)"); if ((go || enter) && canGo) @@ -171,7 +171,7 @@ internal sealed class RynthNavArrowFace : IImGuiPanel _showRoute = !_showRoute; _scrolledTo = -1; } - ImGuiNET.ImGui.SetItemTooltip(hasRoute ? (_showRoute ? "Hide the route's steps" : "Show the route's steps") : "No route yet: Plan or Go makes one"); + SafeImGui.SetItemTooltip(hasRoute ? (_showRoute ? "Hide the route's steps" : "Show the route's steps") : "No route yet: Plan or Go makes one"); if (_showRoute && hasRoute) RouteList(st!, new Vector2(origin.X + pad, rowY + b + 4), new Vector2(size.X - 2 * pad, listH), bold, lineH); @@ -182,7 +182,7 @@ internal sealed class RynthNavArrowFace : IImGuiPanel ImGuiNET.ImGui.InvisibleButton("##rna_surface", new Vector2(size.X, rowY - origin.Y - 2)); ImGuiPanelHost.DragWindowWithLastItem(); if (ImGuiNET.ImGui.IsItemHovered() && _read.Tooltip.Length > 0) - ImGuiNET.ImGui.SetItemTooltip(_read.Tooltip + (_read.Line3.Length > 0 && _read.Kind == "portal" ? "\n" + _read.Line3 : "")); + SafeImGui.SetItemTooltip(_read.Tooltip + (_read.Line3.Length > 0 && _read.Kind == "portal" ? "\n" + _read.Line3 : "")); } /// The coordinates or place typed in the box, trimmed. @@ -241,7 +241,7 @@ internal sealed class RynthNavArrowFace : IImGuiPanel ImGuiNET.ImGui.TextUnformatted(st.RouteLines[i]); ImGuiNET.ImGui.PopStyleColor(); if (ImGuiNET.ImGui.IsItemHovered()) - ImGuiNET.ImGui.SetTooltip(current && st.StepLeft.Length > 0 ? st.RouteLines[i] + "\n" + st.StepLeft : st.RouteLines[i]); + SafeImGui.SetTooltip(current && st.StepLeft.Length > 0 ? st.RouteLines[i] + "\n" + st.StepLeft : st.RouteLines[i]); if (current && _scrolledTo != i) { ImGuiNET.ImGui.SetScrollHereY(0.3f); _scrolledTo = i; } } } diff --git a/src/RynthCore.Engine/ImGui/Panels/RynthNavFace.cs b/src/RynthCore.Engine/ImGui/Panels/RynthNavFace.cs index 6662c88..c177ef6 100644 --- a/src/RynthCore.Engine/ImGui/Panels/RynthNavFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/RynthNavFace.cs @@ -194,7 +194,7 @@ internal sealed class RynthNavFace : IImGuiPanel // The whole line on hover (it's clipped to one line). ImGuiNET.ImGui.SetCursorScreenPos(p); ImGuiNET.ImGui.InvisibleButton("##rnav_status", new Vector2(Math.Max(1, textRight - p.X), h)); - if (text.Length > 40) ImGuiNET.ImGui.SetItemTooltip(text); + if (text.Length > 40) SafeImGui.SetItemTooltip(text); if (stop) { if (IconButton("##rnav_status_stop", PhosphorIcons.Stop, new Vector2(p.X + w - 22, p.Y + 1), new Vector2(20, 20), Text, StopBg, font: UiFont.Ui11)) @@ -272,7 +272,7 @@ internal sealed class RynthNavFace : IImGuiPanel { if (IconButton("##go_star", PhosphorIcons.Star, p, new Vector2(18, 18), fav ? Gold : Faded(Mute), fav ? Selected : PanelBg, font: UiFont.Ui11)) RynthNavCommands.ToggleFavorite(_pick!.Name, _pick.Ns, _pick.Ew); - ImGuiNET.ImGui.SetItemTooltip(fav ? "Remove from favorites" : "Add to favorites"); + SafeImGui.SetItemTooltip(fav ? "Remove from favorites" : "Add to favorites"); lx += 22; } dl.PushClipRect(new Vector2(lx, p.Y), new Vector2(p.X + w, p.Y + 18), true); @@ -290,19 +290,19 @@ internal sealed class RynthNavFace : IImGuiPanel bool walking = st?.Goto == true; float bw = (w - 3 * 4) / 4f; if (Button("##go_go", GoLabel, p, new Vector2(bw, 26), Green, BtnFill, enabled: canGo)) Go(text); - ImGuiNET.ImGui.SetItemTooltip(travel + SafeImGui.SetItemTooltip(travel ? (st!.PortalsOn ? "Walk there, through portals and with recalls when that is quicker" : "Walk there (portals and recalls are switched off)") : "Walk the navmesh to these coordinates (update RynthNav for places and routes)"); if (Button("##go_route", PhosphorIcons.Path + " Route", new Vector2(p.X + bw + 4, p.Y), new Vector2(bw, 26), Text, BtnFill, enabled: travel && has)) RynthNavCommands.Command("route " + Arg(text)); - ImGuiNET.ImGui.SetItemTooltip(travel ? "Plan only: show the steps below, don't walk" : "Update RynthNav (0.6.0+) for routes"); + SafeImGui.SetItemTooltip(travel ? "Plan only: show the steps below, don't walk" : "Update RynthNav (0.6.0+) for routes"); if (Button("##go_arrow", PhosphorIcons.NavigationArrow + " Arrow", new Vector2(p.X + 2 * (bw + 4), p.Y), new Vector2(bw, 26), Teal, BtnFill, enabled: travel && has)) RynthNavCommands.Command("arrow " + Arg(text)); - ImGuiNET.ImGui.SetItemTooltip(travel ? "Show the arrow overlay pointing there" : "Update RynthNav (0.6.0+) for the arrow"); + SafeImGui.SetItemTooltip(travel ? "Show the arrow overlay pointing there" : "Update RynthNav (0.6.0+) for the arrow"); if (Button("##go_stop", PhosphorIcons.Stop + " Stop", new Vector2(p.X + 3 * (bw + 4), p.Y), new Vector2(bw, 26), walking ? Text : Red, walking ? StopBg : BtnFill, border: walking ? Red : 0)) RynthNavCommands.Move(5); - ImGuiNET.ImGui.SetItemTooltip(walking ? "Stop walking" : "Stop any movement"); + SafeImGui.SetItemTooltip(walking ? "Stop walking" : "Stop any movement"); NextLine(p, 32); // Switches @@ -427,7 +427,7 @@ internal sealed class RynthNavFace : IImGuiPanel if (IconButton("##fav", PhosphorIcons.Star, rp + new Vector2(2, 1), new Vector2(btn, btn), r.Favorite ? Gold : Faded(Mute), r.Favorite ? Selected : PanelBg, enabled: travel && r.OnMap, font: UiFont.Ui11)) RynthNavCommands.ToggleFavorite(r.Name, r.Ns, r.Ew); - ImGuiNET.ImGui.SetItemTooltip(r.Favorite ? "Remove from favorites" : "Add to favorites"); + SafeImGui.SetItemTooltip(r.Favorite ? "Remove from favorites" : "Add to favorites"); float bodyX = rp.X + btn + 4, bodyW = w - btn - 4; ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(bodyX, rp.Y)); @@ -594,7 +594,7 @@ internal sealed class RynthNavFace : IImGuiPanel ImGuiNET.ImGui.SetItemTooltip("Is there navmesh under you?"); if (Button("##preview", "Preview", new Vector2(p.X + 2 * (bw + 4), p.Y), new Vector2(bw, 24), Text, BtnFill, enabled: coord.Length > 0)) RynthNavCommands.Preview(coord); - ImGuiNET.ImGui.SetItemTooltip(coord.Length > 0 ? "Plan the navmesh path to the destination (close places only), no walking" + SafeImGui.SetItemTooltip(coord.Length > 0 ? "Plan the navmesh path to the destination (close places only), no walking" : "Pick a destination on the map first"); NextLine(p, 30); @@ -638,7 +638,7 @@ internal sealed class RynthNavFace : IImGuiPanel { if (IconButton("##mv" + cmd, glyph, pos, new Vector2(58, 42), Text, active ? RunGreen : BtnFill)) RynthNavCommands.Move(cmd); - ImGuiNET.ImGui.SetItemTooltip(tip); + SafeImGui.SetItemTooltip(tip); } // Avoidance, one row per kind of thing kept away from: on/off, then − value +. Each click @@ -664,7 +664,7 @@ internal sealed class RynthNavFace : IImGuiPanel } else Button("##av_" + key, label, p, new Vector2(lw, 22), Text, BtnFill, enabled: false, leftAlign: true); - ImGuiNET.ImGui.SetItemTooltip(tip); + SafeImGui.SetItemTooltip(tip); bool active = on ?? true; float x = p.X + lw + 4; string Fmt(double v) => v.ToString("0.#", System.Globalization.CultureInfo.InvariantCulture); @@ -684,7 +684,7 @@ internal sealed class RynthNavFace : IImGuiPanel float w1 = (w - 8) * 0.40f, w2 = (w - 8) * 0.28f, w3 = w - 8 - w1 - w2; if (Toggle("##mk_on", "Path markers", st.MarkersOn, p, w1)) RynthNavCommands.Command(st.MarkersOn ? "markers off" : "markers on"); - ImGuiNET.ImGui.SetItemTooltip("Show the planned trip on the ground, the way RynthAi shows its nav routes: rings at the\n" + SafeImGui.SetItemTooltip("Show the planned trip on the ground, the way RynthAi shows its nav routes: rings at the\n" + "waypoints, lines between them, the portals, recalls and the goal in their own colours.\n" + "They go when the trip ends, you stop, or you land somewhere that isn't on it." + (st.MarkerStatus.Length > 0 ? "\n\nNow: " + st.MarkerStatus : "")); @@ -721,7 +721,7 @@ internal sealed class RynthNavFace : IImGuiPanel if (Button("##save_go", st.SaveBusy ? "Saving…" : PhosphorIcons.FloppyDisk + " Save", new Vector2(p.X + boxW + 4, p.Y), new Vector2(bw, 22), Teal, BtnFill, enabled: can) || (enter && can)) RynthNavCommands.Command("saveroute " + name); - ImGuiNET.ImGui.SetItemTooltip("Write this trip as a RynthAi nav route (NavProfiles\\" + (name.Length > 0 ? name : "name") + ".nav):\n" + SafeImGui.SetItemTooltip("Write this trip as a RynthAi nav route (NavProfiles\\" + (name.Length > 0 ? name : "name") + ".nav):\n" + "the walks as waypoints, portals as portal steps, recalls as recall steps.\n" + "RynthAi lists it in its Nav picker; /ra nav load " + (name.Length > 0 ? name : "") + " loads it."); NextLine(p, 26); @@ -735,7 +735,7 @@ internal sealed class RynthNavFace : IImGuiPanel dl.PopClipRect(); if (Button("##save_replace", "Replace", new Vector2(p.X + tw + 4, p.Y), new Vector2(rw, 22), Text, BtnFill, enabled: !st.SaveBusy, border: Amber)) RynthNavCommands.Command("saveroute " + name + " overwrite"); - ImGuiNET.ImGui.SetItemTooltip("Replace NavProfiles\\" + name + ".nav with this trip"); + SafeImGui.SetItemTooltip("Replace NavProfiles\\" + name + ".nav with this trip"); NextLine(p, 26); } if (st.SaveLast.Length > 0) @@ -781,7 +781,7 @@ internal sealed class RynthNavFace : IImGuiPanel _mode = Modes[i].Mode; PushQuery(); } - ImGuiNET.ImGui.SetItemTooltip(Modes[i].Tip); + SafeImGui.SetItemTooltip(Modes[i].Tip); } NextLine(p, 26); @@ -844,7 +844,7 @@ internal sealed class RynthNavFace : IImGuiPanel if (IconButton("##fav", PhosphorIcons.Star, starPos, new Vector2(btn, btn), r.Favorite ? Gold : Faded(Mute), r.Favorite ? Selected : PanelBg, enabled: r.OnMap, font: UiFont.Ui11)) RynthNavCommands.ToggleFavorite(r.Name, r.Ns, r.Ew); - ImGuiNET.ImGui.SetItemTooltip(r.Favorite ? "Remove from favorites" : "Add to favorites"); + SafeImGui.SetItemTooltip(r.Favorite ? "Remove from favorites" : "Add to favorites"); // Arrow / Go (right) var goPos = new Vector2(rp.X + w - btn - 2, rp.Y + 1); @@ -854,13 +854,13 @@ internal sealed class RynthNavFace : IImGuiPanel RynthNavCommands.Arrow(r.Name, r.Ns, r.Ew); _sel = r; } - ImGuiNET.ImGui.SetItemTooltip(r.OnMap ? "Point the arrow here" : "In a dungeon: no arrow"); + SafeImGui.SetItemTooltip(r.OnMap ? "Point the arrow here" : "In a dungeon: no arrow"); if (IconButton("##go", PhosphorIcons.Play, goPos, new Vector2(btn, btn), Green, BtnFill, enabled: r.OnMap, font: UiFont.Ui11)) { RynthNavCommands.Go(r.Name, r.Ns, r.Ew); _sel = r; } - ImGuiNET.ImGui.SetItemTooltip(r.OnMap ? "Go: RynthNav walks here" : "In a dungeon: RynthNav can't walk there"); + SafeImGui.SetItemTooltip(r.OnMap ? "Go: RynthNav walks here" : "In a dungeon: RynthNav can't walk there"); // Row body: click selects float bodyX = rp.X + btn + 4, bodyW = arPos.X - 4 - bodyX; diff --git a/src/RynthCore.Engine/ImGui/Panels/SenseFace.cs b/src/RynthCore.Engine/ImGui/Panels/SenseFace.cs index eb5fc01..5df5fe7 100644 --- a/src/RynthCore.Engine/ImGui/Panels/SenseFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/SenseFace.cs @@ -190,7 +190,7 @@ internal sealed class SenseFace : IImGuiPanel if (ImGuiNET.ImGui.InvisibleButton("##t", new Vector2(chipW - xW, ChipH))) toggle = i; bool hotT = ImGuiNET.ImGui.IsItemHovered(); if (hotT) - ImGuiNET.ImGui.SetItemTooltip(t.Enabled + SafeImGui.SetItemTooltip(t.Enabled ? (t.IsGlob ? "On: the whole name must match (wildcards). Click to switch off." : "On: names containing this match. Click to switch off.") : "Off. Click to switch on."); ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(x + chipW - xW, y)); diff --git a/src/RynthCore.Engine/ImGui/Panels/ServerPickSettingsUi.cs b/src/RynthCore.Engine/ImGui/Panels/ServerPickSettingsUi.cs new file mode 100644 index 0000000..334372e --- /dev/null +++ b/src/RynthCore.Engine/ImGui/Panels/ServerPickSettingsUi.cs @@ -0,0 +1,126 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/Panels/ServerPickSettingsUi.cs +// Settings > Diagnostics > Server: which server this character counts as. +// +// A picker (Auto, or one of the servers the engine knows: the built-in ones +// and every server a loaded plugin declares), what is active and why, and the +// full list: verdict, detection, this character's override, and the plugin +// the other plugins ask for that server's settings. Picking a server forces it +// on and every other server off for this character (ServerSelectionStore); +// the menus, the "servermenu" push and plugin API v85 follow on the next frame. +// Drawn by SettingsFace for the Diagnostics tab's ServerPick row, in its look. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Numerics; +using ImGuiNET; +using RynthCore.Engine.UI.Sections; + +namespace RynthCore.Engine.ImGuiBackend.Panels; + +internal static class ServerPickSettingsUi +{ + private static readonly Vector4 Teal = RynthTheme.Vec(0xFF26D9E6), Amber = RynthTheme.Vec(0xFFE8B333), + Mute = RynthTheme.Vec(0xFFB8C8D8), Good = RynthTheme.Vec(0xFF33FF33); + + // The last pick's outcome, shown under the picker until the next one. + private static string _message = string.Empty; + + /// The row: picker, active server, server table. Render thread. + public static void Draw(float width, string? tooltip) + { + SectionRegistry.Snapshot snap = SectionRegistry.Current; + IReadOnlyList servers = snap.Servers; + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + if (servers.Count == 0) + { + SafeImGui.TextDisabled("No servers known yet (the list fills in once a character is in game)."); + return; + } + + string? pick = ServerSelection.CurrentPick(servers); + DrawPicker(servers, pick, width, tooltip); + + ServerState? active = ServerSelection.ActiveServer(servers); + ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); + if (active == null) + SafeImGui.TextColored(Mute, "Active: none (no custom server matched; retail rules)."); + else + SafeImGui.TextColored(Teal, $"Active: {active.Name} ({active.Id}) - {active.Reason}"); + if (_message.Length > 0) SafeImGui.TextColored(Amber, _message); + + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + DrawTable(servers, snap.Manifests); + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + } + + private static void DrawPicker(IReadOnlyList servers, string? pick, float width, string? tooltip) + { + string preview = pick == null ? "Mixed (set per server with /rc server on|off)" + : pick == ServerSelection.Auto ? "Auto (detect)" + : Label(servers, pick); + + ImGuiNET.ImGui.AlignTextToFramePadding(); + SafeImGui.TextColored(Mute, "Server"); + if (tooltip != null) SafeImGui.SetItemTooltip(tooltip); + ImGuiNET.ImGui.SameLine(90); + ImGuiNET.ImGui.SetNextItemWidth(Math.Max(160, width - 96)); + if (ImGuiNET.ImGui.BeginCombo("##serverpick", preview)) + { + if (ImGuiNET.ImGui.Selectable("Auto (detect)##pick_auto", pick == ServerSelection.Auto)) + Pick(ServerSelection.Auto); + foreach (ServerState s in servers) + { + string marks = (s.Active ? " [active]" : string.Empty) + (s.Detected ? " [detected]" : string.Empty); + if (ImGuiNET.ImGui.Selectable(s.Name + " (" + s.Id + ")" + marks + "##pick_" + s.Id, + pick != null && pick.Equals(s.Id, StringComparison.OrdinalIgnoreCase))) + Pick(s.Id); + } + ImGuiNET.ImGui.EndCombo(); + } + if (tooltip != null) SafeImGui.SetItemTooltip(tooltip); + } + + private static void Pick(string id) + { + ServerSelectionStore.Apply(id, out string message); + _message = message; + } + + private static void DrawTable(IReadOnlyList servers, IReadOnlyList manifests) + { + const ImGuiTableFlags flags = ImGuiTableFlags.Borders | ImGuiTableFlags.RowBg | ImGuiTableFlags.SizingStretchProp; + if (!ImGuiNET.ImGui.BeginTable("##servers", 5, flags)) return; + ImGuiNET.ImGui.TableSetupColumn("Server", ImGuiTableColumnFlags.WidthStretch, 2.2f); + ImGuiNET.ImGui.TableSetupColumn("Active", ImGuiTableColumnFlags.WidthStretch, 0.9f); + ImGuiNET.ImGui.TableSetupColumn("Detected", ImGuiTableColumnFlags.WidthStretch, 1f); + ImGuiNET.ImGui.TableSetupColumn("Override", ImGuiTableColumnFlags.WidthStretch, 1f); + ImGuiNET.ImGui.TableSetupColumn("Settings from", ImGuiTableColumnFlags.WidthStretch, 1.6f); + ImGuiNET.ImGui.TableHeadersRow(); + foreach (ServerState s in servers) + { + ImGuiNET.ImGui.TableNextRow(); + ImGuiNET.ImGui.TableNextColumn(); + SafeImGui.TextColored(s.Active ? Teal : Mute, s.Name + " (" + s.Id + ")"); + if (!string.IsNullOrEmpty(s.Reason)) SafeImGui.SetItemTooltip(s.Reason); + ImGuiNET.ImGui.TableNextColumn(); + SafeImGui.TextColored(s.Active ? Good : Mute, s.Active ? "yes" : "no"); + ImGuiNET.ImGui.TableNextColumn(); + SafeImGui.TextColored(Mute, s.Detected ? "yes" : "no"); + ImGuiNET.ImGui.TableNextColumn(); + SafeImGui.TextColored(s.Force == ServerForce.Auto ? Mute : Amber, ServerForceText.Name(s.Force)); + ImGuiNET.ImGui.TableNextColumn(); + string owner = ServerSelection.OwnerPlugin(manifests, s.Id, SectionRegistry.EnginePlugin); + SafeImGui.TextColored(owner.Length > 0 ? Teal : Mute, owner.Length > 0 ? owner : "(no plugin loaded)"); + } + ImGuiNET.ImGui.EndTable(); + } + + private static string Label(IReadOnlyList servers, string id) + { + foreach (ServerState s in servers) + if (s.Id.Equals(id, StringComparison.OrdinalIgnoreCase)) return s.Name + " (" + s.Id + ")"; + return id; + } +} diff --git a/src/RynthCore.Engine/ImGui/Panels/SettingsFace.cs b/src/RynthCore.Engine/ImGui/Panels/SettingsFace.cs index 3883c0a..df2d85d 100644 --- a/src/RynthCore.Engine/ImGui/Panels/SettingsFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/SettingsFace.cs @@ -176,7 +176,7 @@ internal sealed class SettingsFace : IImGuiPanel ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); if (_tab >= SettingsSchema.Tabs.Length) _tab = 0; - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), Headers[_tab]); + SafeImGui.TextColored(RynthTheme.Vec(0xFF26D9E6), Headers[_tab]); ImGuiNET.ImGui.PopFont(); ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); Vector2 lp = ImGuiNET.ImGui.GetCursorScreenPos(); @@ -216,6 +216,7 @@ internal sealed class SettingsFace : IImGuiPanel case SettingKind.Text: TextRow(row, w); break; case SettingKind.Status: StatusRow(row, w); break; case SettingKind.Hotkeys: _editing |= _hotkeys.Draw(w); break; + case SettingKind.ServerPick: ServerPickSettingsUi.Draw(w, row.Tooltip); break; } } @@ -532,16 +533,16 @@ internal sealed class SettingsFace : IImGuiPanel private void CraftingStatus(SettingRow row) { ImGuiNET.ImGui.Dummy(new Vector2(0, 2)); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), row.Label); + SafeImGui.TextColored(RynthTheme.Vec(0xFFB8C8D8), row.Label); ImGuiNET.ImGui.SameLine(0, 6); ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); - ImGuiNET.ImGui.TextColored(RynthTheme.Vec(_data.MissileCraftingActive ? 0xFFE8B333 : 0xFFB8C8D8), _data.MissileCraftingState); + SafeImGui.TextColored(RynthTheme.Vec(_data.MissileCraftingActive ? 0xFFE8B333 : 0xFFB8C8D8), _data.MissileCraftingState); ImGuiNET.ImGui.PopFont(); if (!string.IsNullOrEmpty(_data.MissileCraftingStatus)) { ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.Ui10)); ImGuiNET.ImGui.PushStyleColor(ImGuiCol.Text, TextDim); - ImGuiNET.ImGui.TextWrapped(_data.MissileCraftingStatus); + SafeImGui.TextWrapped(_data.MissileCraftingStatus); ImGuiNET.ImGui.PopStyleColor(); ImGuiNET.ImGui.PopFont(); } @@ -590,7 +591,7 @@ internal sealed class SettingsFace : IImGuiPanel private static void Tooltip(SettingRow row) { - if (row.Tooltip != null) ImGuiNET.ImGui.SetItemTooltip(row.Tooltip); + if (row.Tooltip != null) SafeImGui.SetItemTooltip(row.Tooltip); } private static uint Lighten(uint abgr) => Scale(abgr, 1.25f, 12); diff --git a/src/RynthCore.Engine/ImGui/Panels/SkillsFace.Progression.cs b/src/RynthCore.Engine/ImGui/Panels/SkillsFace.Progression.cs index bb22d8f..eef4eff 100644 --- a/src/RynthCore.Engine/ImGui/Panels/SkillsFace.Progression.cs +++ b/src/RynthCore.Engine/ImGui/Panels/SkillsFace.Progression.cs @@ -1,12 +1,10 @@ // ============================================================================ // RynthCore.Engine - ImGui/Panels/SkillsFace.Progression.cs // The Skills panel's Progression tab, shown on ILT-like worlds only: -// - XP planner: exact XP for the next N raises of every attribute and vital, -// from the client's XP tables (raising stays on the Attributes & Vitals tab). -// - Attribute raiser: infinite attributes past the retail cap. RynthILT reads the -// server's costs ("/xp all") and raises with "/attr", by hand or on a timer from -// unassigned XP, in the order and mode set here. Laid out like UB's Leaftide XP -// tab: "+1 Level" / "+10 Levels" buttons labelled with their (projected) cost. +// - Attributes: one section - client XP-table planner for retail ranks, plus (when the +// server supports infinite attributes) the ILT raiser to auto-raise past the retail +// cap with "/xp all" + "/attr" (UB Leaftide XP tab layout). RynthILT reads the +// server's costs and raises, by hand or on a timer from unassigned XP. // - Augmentations: UB's Augs tab - Refresh current (/aug), Current / Target / Inc / // Luminance / Coins with a totals row, Reset targets, Copy Discord / In-Game. // - Augmentations / Enlightenment: the ILT Hub's planners (RynthILT's since @@ -100,15 +98,14 @@ internal sealed partial class SkillsFace ImGuiNET.ImGui.PushStyleVar(ImGuiStyleVar.ItemSpacing, new Vector2(6, 4)); try { - DrawXpPlanner(w); + // One Attributes section: retail XP planner + (when supported) infinite-attr raiser. + DrawAttributes(info?.Attr, w); ImGuiNET.ImGui.Dummy(new Vector2(0, 6)); if (info == null || !info.Available) { Message("Augmentations and Enlightenment need RynthILT's ILT features on an ILT world.", w); return; } - DrawAttrRaiser(info.Attr, w); - ImGuiNET.ImGui.Dummy(new Vector2(0, 6)); DrawAugPlanner(info.Aug, w); ImGuiNET.ImGui.Dummy(new Vector2(0, 6)); DrawEnlPlanner(info.Enl, w); @@ -120,15 +117,50 @@ internal sealed partial class SkillsFace } } - private void DrawXpPlanner(float w) + /// + /// Single Attributes section: client XP-table costs up to the retail cap, and - when the + /// server supports infinite attributes - the controls to auto-raise past that cap. + /// + private void DrawAttributes(AttrRaiser? a, float w) + { + Section("Attributes", w); + ImGuiNET.ImGui.Indent(8); + float wrap = ImGuiNET.ImGui.GetCursorPosX() + w - 24; + ImGuiNET.ImGui.PushTextWrapPos(wrap); + try + { + DrawRetailXpPlanner(w); + + // Infinite-attributes segment: only when RynthILT reports the server can raise past retail. + bool infiniteOk = a != null && !a.Off; + ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); + ImGuiNET.ImGui.Separator(); + Label(infiniteOk + ? "Infinite attributes (past retail max)" + : "Infinite attributes", + infiniteOk ? Amber : Mute); + if (a == null) + Label("Update RynthILT to raise attributes past the retail cap on this server.", Mute); + else if (a.Off) + Label(a.Reason.Length > 0 ? a.Reason : "This server does not support infinite attributes (/xp /attr).", Mute); + else + DrawInfiniteAttrControls(a, w); + } + finally + { + ImGuiNET.ImGui.PopTextWrapPos(); + ImGuiNET.ImGui.Unindent(8); + } + } + + /// Client XP tables for the next N retail raises (Attributes & Vitals tab still spends them). + private void DrawRetailXpPlanner(float w) { - Section("XP planner", w); if (_snap == null || _dat == null || _attributes.Count == 0) { Message("Waiting for your character's data...", w); return; } - ImGuiNET.ImGui.Indent(8); long have = _snap.UnassignedXp; Label($"Unassigned XP: {have:N0}", have > 0 ? Teal : Mute); ImGuiNET.ImGui.SetNextItemWidth(160); @@ -146,9 +178,7 @@ internal sealed partial class SkillsFace foreach (Row r in _vitals) PlannerRow(r, have); ImGuiNET.ImGui.EndTable(); } - Label("Exact costs from the client's XP tables. Raise on the Attributes & Vitals tab" - + (ProgressionTabVisible ? ", or past the cap with the Attribute raiser below." : "."), Dim); - ImGuiNET.ImGui.Unindent(8); + Label("Exact costs from the client's XP tables (up to the retail cap). Raise those on the Attributes & Vitals tab.", Dim); } private void PlannerRow(Row r, long have) @@ -180,89 +210,76 @@ internal sealed partial class SkillsFace private string? _attrKeepEdit; // reserve box being typed in (null = show RynthAi's value) private int? _attrEveryEdit; // interval box being typed in - private void DrawAttrRaiser(AttrRaiser? a, float w) + /// Infinite-attribute raiser controls (only drawn when the server supports /xp + /attr past retail). + private void DrawInfiniteAttrControls(AttrRaiser a, float w) { - Section("Attribute raiser (infinite attributes)", w); - ImGuiNET.ImGui.Indent(8); - float wrap = ImGuiNET.ImGui.GetCursorPosX() + w - 24; - ImGuiNET.ImGui.PushTextWrapPos(wrap); - try + Label(a.XpHeader.Length > 0 ? a.XpHeader : a.Unassigned, Teal); + if (a.XpHeader.Length > 0 && a.Unassigned.Contains("spendable", StringComparison.Ordinal)) Label(a.Unassigned, Dim); + Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); + if (a.Running) { - if (a == null) { Label("Update RynthAi to use the attribute raiser.", Mute); return; } - if (a.Off) { Label(a.Reason, Mute); return; } - - Label(a.XpHeader.Length > 0 ? a.XpHeader : a.Unassigned, Teal); - if (a.XpHeader.Length > 0 && a.Unassigned.Contains("spendable", StringComparison.Ordinal)) Label(a.Unassigned, Dim); - Vector2 p = ImGuiNET.ImGui.GetCursorScreenPos(); - if (a.Running) - { - if (Button("##attr_stop", "Stop", p, new Vector2(90, 24), Text, StopBg)) SendProg("attrstop"); - } - else if (Button("##attr_run", "Raise now", p, new Vector2(110, 24), Text, StartBg, border: Teal)) - SendProg("attrrun"); - if (Button("##attr_costs", "Refresh XP", new Vector2(p.X + 116, p.Y), new Vector2(100, 24), Text, BtnFill, enabled: !a.Running)) - SendProg("attrcosts"); - ImGuiNET.ImGui.SetItemTooltip("Re-reads every next-level cost with /xp all."); - if (a.Updated.Length > 0) - { - ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X + 224, p.Y + 4)); - Label("Last updated: " + a.Updated, Dim); - } - NextLine(p, 28); - if (a.Status.Length > 0) ImGuiNET.ImGui.TextWrapped(a.Status); - if (a.LastRun.Length > 0) Label("Last run: " + a.LastRun, Dim); - - ImGuiNET.ImGui.Separator(); - bool auto = a.Auto; - if (ImGuiNET.ImGui.Checkbox("Auto-raise from unassigned XP##attr_auto", ref auto)) - SendProg("attrauto " + (auto ? "on" : "off")); - ImGuiNET.ImGui.SameLine(); - // Commit on Enter, the +/- buttons or focus loss (not on every keystroke: each send - // restarts the auto-raise timer). - int every = _attrEveryEdit ?? a.Every; - ImGuiNET.ImGui.SetNextItemWidth(90); - bool everyCommit = ImGuiNET.ImGui.InputInt("every (min)##attr_every", ref every, 1, 10, ImGuiInputTextFlags.EnterReturnsTrue); - bool everyActive = ImGuiNET.ImGui.IsItemActive(); - if (everyCommit || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) - { - _attrEveryEdit = null; - if (every != a.Every) SendProg("attrevery " + Math.Clamp(every, 1, 1440).ToString(CultureInfo.InvariantCulture)); - } - else _attrEveryEdit = everyActive ? every : null; - if (a.Auto && a.Next.Length > 0) Label($"Next auto-raise: {a.Next}", Dim); - - int mode = Math.Clamp(a.Mode, 0, AttrModes.Length - 1); - ImGuiNET.ImGui.SetNextItemWidth(260); - if (ImGuiNET.ImGui.Combo("Raise order##attr_mode", ref mode, AttrModes, AttrModes.Length)) - SendProg("attrmode " + mode.ToString(CultureInfo.InvariantCulture)); - - // The box holds the exact reserve (KeepFull); it is sent only when the text changed, so an - // Enter on an untouched box can't round the reserve. - string shownKeep = a.KeepFull.Length > 0 ? a.KeepFull : a.Keep; - string keep = _attrKeepEdit ?? shownKeep; - ImGuiNET.ImGui.SetNextItemWidth(140); - bool enter = ImGuiNET.ImGui.InputTextWithHint("Keep in reserve (XP)##attr_keep", "0, 500m, 2b", ref keep, 32u, - ImGuiInputTextFlags.EnterReturnsTrue); - bool keepActive = ImGuiNET.ImGui.IsItemActive(); - if (enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) - { - _attrKeepEdit = null; - if (!string.Equals(keep.Trim(), shownKeep, StringComparison.Ordinal)) - SendProg("attrkeep " + keep.Replace(" ", "", StringComparison.Ordinal).Replace(",", "", StringComparison.Ordinal)); - } - else _attrKeepEdit = keepActive ? keep : null; - ImGuiNET.ImGui.SetItemTooltip("Unassigned XP the raiser never spends. Accepts k / m / b / t suffixes."); - - DrawAttrTable(a, w); - Label("Auto: the stats Raise now / auto-raise may spend on; arrows set the order. " - + "+1 / +10 raise by hand (red = not enough unassigned XP). " - + "+10 is an estimate (7.7% dearer per level); the server charges the real cost. " + a.CostsAge + ".", Dim); + if (Button("##attr_stop", "Stop", p, new Vector2(90, 24), Text, StopBg)) SendProg("attrstop"); } - finally + else if (Button("##attr_run", "Raise now", p, new Vector2(110, 24), Text, StartBg, border: Teal)) + SendProg("attrrun"); + if (Button("##attr_costs", "Refresh XP", new Vector2(p.X + 116, p.Y), new Vector2(100, 24), Text, BtnFill, enabled: !a.Running)) + SendProg("attrcosts"); + ImGuiNET.ImGui.SetItemTooltip("Re-reads every next-level cost with /xp all."); + if (a.Updated.Length > 0) { - ImGuiNET.ImGui.PopTextWrapPos(); - ImGuiNET.ImGui.Unindent(8); + ImGuiNET.ImGui.SetCursorScreenPos(new Vector2(p.X + 224, p.Y + 4)); + Label("Last updated: " + a.Updated, Dim); } + NextLine(p, 28); + if (a.Status.Length > 0) ImGuiNET.ImGui.TextWrapped(a.Status); + if (a.LastRun.Length > 0) Label("Last run: " + a.LastRun, Dim); + + ImGuiNET.ImGui.Separator(); + bool auto = a.Auto; + if (ImGuiNET.ImGui.Checkbox("Auto-raise past retail max##attr_auto", ref auto)) + SendProg("attrauto " + (auto ? "on" : "off")); + ImGuiNET.ImGui.SetItemTooltip("Spends unassigned XP with /attr past the retail attribute cap (server costs from /xp all)."); + ImGuiNET.ImGui.SameLine(); + // Commit on Enter, the +/- buttons or focus loss (not on every keystroke: each send + // restarts the auto-raise timer). + int every = _attrEveryEdit ?? a.Every; + ImGuiNET.ImGui.SetNextItemWidth(90); + bool everyCommit = ImGuiNET.ImGui.InputInt("every (min)##attr_every", ref every, 1, 10, ImGuiInputTextFlags.EnterReturnsTrue); + bool everyActive = ImGuiNET.ImGui.IsItemActive(); + if (everyCommit || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) + { + _attrEveryEdit = null; + if (every != a.Every) SendProg("attrevery " + Math.Clamp(every, 1, 1440).ToString(CultureInfo.InvariantCulture)); + } + else _attrEveryEdit = everyActive ? every : null; + if (a.Auto && a.Next.Length > 0) Label($"Next auto-raise: {a.Next}", Dim); + + int mode = Math.Clamp(a.Mode, 0, AttrModes.Length - 1); + ImGuiNET.ImGui.SetNextItemWidth(260); + if (ImGuiNET.ImGui.Combo("Raise order##attr_mode", ref mode, AttrModes, AttrModes.Length)) + SendProg("attrmode " + mode.ToString(CultureInfo.InvariantCulture)); + + // The box holds the exact reserve (KeepFull); it is sent only when the text changed, so an + // Enter on an untouched box can't round the reserve. + string shownKeep = a.KeepFull.Length > 0 ? a.KeepFull : a.Keep; + string keep = _attrKeepEdit ?? shownKeep; + ImGuiNET.ImGui.SetNextItemWidth(140); + bool enter = ImGuiNET.ImGui.InputTextWithHint("Keep in reserve (XP)##attr_keep", "0, 500m, 2b", ref keep, 32u, + ImGuiInputTextFlags.EnterReturnsTrue); + bool keepActive = ImGuiNET.ImGui.IsItemActive(); + if (enter || ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) + { + _attrKeepEdit = null; + if (!string.Equals(keep.Trim(), shownKeep, StringComparison.Ordinal)) + SendProg("attrkeep " + keep.Replace(" ", "", StringComparison.Ordinal).Replace(",", "", StringComparison.Ordinal)); + } + else _attrKeepEdit = keepActive ? keep : null; + ImGuiNET.ImGui.SetItemTooltip("Unassigned XP the raiser never spends. Accepts k / m / b / t suffixes."); + + DrawAttrTable(a, w); + Label("Auto: the stats Raise now / auto-raise may spend on; arrows set the order. " + + "+1 / +10 raise by hand (red = not enough unassigned XP). " + + "+10 is an estimate (7.7% dearer per level); the server charges the real cost. " + a.CostsAge + ".", Dim); } /// diff --git a/src/RynthCore.Engine/ImGui/Panels/SkillsFace.cs b/src/RynthCore.Engine/ImGui/Panels/SkillsFace.cs index beb9412..9c3f205 100644 --- a/src/RynthCore.Engine/ImGui/Panels/SkillsFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/SkillsFace.cs @@ -676,7 +676,7 @@ internal sealed partial class SkillsFace : IImGuiPanel dl.AddText(new Vector2(x, y), _summaryColors[i], _summary[i]); if (i == _radiancePart && _masteryTip.Length > 0 && ImGuiNET.ImGui.IsMouseHoveringRect(new Vector2(x, y), new Vector2(x + tw, y + lineH))) - ImGuiNET.ImGui.SetTooltip(_masteryTip); + SafeImGui.SetTooltip(_masteryTip); x += tw + 14; } long now = Environment.TickCount64; @@ -735,7 +735,7 @@ internal sealed partial class SkillsFace : IImGuiPanel _descending = !_descending; _orderDirty = true; } - ImGuiNET.ImGui.SetItemTooltip(_descending ? "Highest first" : "Lowest first"); + SafeImGui.SetItemTooltip(_descending ? "Highest first" : "Lowest first"); NextLine(p, 26); } @@ -910,7 +910,7 @@ internal sealed partial class SkillsFace : IImGuiPanel if (ImGuiNET.ImGui.IsItemHovered() && !expanded) dl.AddRect(p, p + new Vector2(w, RowH), BtnBord); if (r.MasteryText.Length > 0 && _masteryTip.Length > 0 && ImGuiNET.ImGui.IsMouseHoveringRect(badgeMin, badgeMax)) - ImGuiNET.ImGui.SetTooltip(r.MasteryHover); + SafeImGui.SetTooltip(r.MasteryHover); // The row's action buttons: "+1" (raise one rank now, no confirm) and a caret that // opens +10 / +100 / Max on trained rows, attributes and vitals; Train (skill @@ -923,13 +923,13 @@ internal sealed partial class SkillsFace : IImGuiPanel if (Button("##raise1", r.Max ? "max" : "+1", btnMin, oneSize, Teal, BtnFill, canRaise, border: canRaise ? Teal : 0) && _snap != null) SendRaise(r, _snap, 1); - ImGuiNET.ImGui.SetItemTooltip(why); + SafeImGui.SetItemTooltip(why); bool canMore = !r.Max && PlayerTraining.Available && !_pending; var caretMin = new Vector2(btnMin.X + oneSize.X + 2, btnMin.Y); if (IconButton("##raiseN", PhosphorIcons.CaretDown, caretMin, new Vector2(CaretW, RowH - 2), Teal, BtnFill, canMore, font: UiFont.Ui11)) OpenMulti(r, caretMin + new Vector2(CaretW - MultiW, RowH)); - ImGuiNET.ImGui.SetItemTooltip(canMore ? "Raise more: +10, +100 or Max" + SafeImGui.SetItemTooltip(canMore ? "Raise more: +10, +100 or Max" : r.Max ? "At the top rank" : _pending ? "Waiting for the last raise to land" : "Raising isn't available on this client build"); } @@ -938,7 +938,7 @@ internal sealed partial class SkillsFace : IImGuiPanel bool canTrain = CanTrain(r, out string why); if (Button("##train", "Train", btnMin, btnSize, Amber, BtnFill, canTrain, border: canTrain ? Amber : 0)) OpenConfirm(r, train: true); - ImGuiNET.ImGui.SetItemTooltip(why); + SafeImGui.SetItemTooltip(why); } ImGuiNET.ImGui.PopID(); NextLine(p, RowH); @@ -1063,7 +1063,7 @@ internal sealed partial class SkillsFace : IImGuiPanel { float tw = ImGuiNET.ImGui.CalcTextSize(r.MasteryLine).X; if (ImGuiNET.ImGui.IsMouseHoveringRect(new Vector2(x, y), new Vector2(x + 18 + tw, y + lineH))) - ImGuiNET.ImGui.SetTooltip(_masteryTip); + SafeImGui.SetTooltip(_masteryTip); } y += lineH; if (r.MasteryLine2.Length > 0) @@ -1083,7 +1083,7 @@ internal sealed partial class SkillsFace : IImGuiPanel if (Button("##mastery_raise", PhosphorIcons.Crown + " Raise mastery", new Vector2(x + 18, y), new Vector2(130, 22), MasteryColor, BtnFill, can, border: can ? MasteryColor : 0)) OpenMasteryConfirm(r); - ImGuiNET.ImGui.SetItemTooltip(can ? why + "\nAsks before it spends anything." : why); + SafeImGui.SetItemTooltip(can ? why + "\nAsks before it spends anything." : why); ImGuiNET.ImGui.PopID(); y += 26; } @@ -1263,7 +1263,7 @@ internal sealed partial class SkillsFace : IImGuiPanel SendRaise(r, s, n); ImGuiNET.ImGui.CloseCurrentPopup(); } - ImGuiNET.ImGui.SetItemTooltip(why); + SafeImGui.SetItemTooltip(why); var dl = ImGuiNET.ImGui.GetWindowDrawList(); float tw = ImGuiNET.ImGui.CalcTextSize(right).X; dl.AddText(new Vector2(x + size.X - 6 - tw, y + (h - ImGuiNET.ImGui.GetFontSize()) * 0.5f), ok ? Teal : Dim, right); diff --git a/src/RynthCore.Engine/ImGui/Panels/VisionFace.cs b/src/RynthCore.Engine/ImGui/Panels/VisionFace.cs index 9d029ed..49adaea 100644 --- a/src/RynthCore.Engine/ImGui/Panels/VisionFace.cs +++ b/src/RynthCore.Engine/ImGui/Panels/VisionFace.cs @@ -210,7 +210,7 @@ internal sealed class VisionFace : IImGuiPanel { ImGuiNET.ImGui.Dummy(new Vector2(0, 4)); ImGuiNET.ImGui.PushFont(ImGuiFonts.Get(UiFont.UiBold11)); - ImGuiNET.ImGui.TextColored(HeaderColor, text); + SafeImGui.TextColored(HeaderColor, text); ImGuiNET.ImGui.PopFont(); } @@ -251,7 +251,7 @@ internal sealed class VisionFace : IImGuiPanel WriteUtf8(hex, argb.ToString("X8")); } if (ImGuiNET.ImGui.IsItemDeactivatedAfterEdit()) Save(f.Key); - ImGuiNET.ImGui.SetItemTooltip("0% = invisible, 100% = solid. Ctrl+click to type a value"); + SafeImGui.SetItemTooltip("0% = invisible, 100% = solid. Ctrl+click to type a value"); return ImGuiNET.ImGui.IsItemActive(); } diff --git a/src/RynthCore.Engine/ImGui/RynthCoreShell.cs b/src/RynthCore.Engine/ImGui/RynthCoreShell.cs index 601f90a..f9d185d 100644 --- a/src/RynthCore.Engine/ImGui/RynthCoreShell.cs +++ b/src/RynthCore.Engine/ImGui/RynthCoreShell.cs @@ -259,7 +259,7 @@ internal static class RynthCoreShell UpdateBarPositionFromWindow(); bool auxReady = frameCount >= 120; - ImGui.TextColored(Win32Backend.IsUiCaptureEnabled() ? Good : TextMute, Win32Backend.IsUiCaptureEnabled() ? "UI" : "GAME"); + SafeImGui.TextColored(Win32Backend.IsUiCaptureEnabled() ? Good : TextMute, Win32Backend.IsUiCaptureEnabled() ? "UI" : "GAME"); ShowTooltip("Press Insert to toggle UI capture."); ImGui.SameLine(); @@ -708,7 +708,7 @@ internal static class RynthCoreShell string pluginDir = PluginManager.PluginDirectory; if (!string.IsNullOrEmpty(pluginDir)) { - ImGui.TextColored(TextMute, pluginDir); + SafeImGui.TextColored(TextMute, pluginDir); } if (_showPluginTips) @@ -741,16 +741,16 @@ internal static class RynthCoreShell string ver = string.IsNullOrEmpty(p.VersionString) ? "" : $" v{p.VersionString}"; ImGui.BulletText(""); ImGui.SameLine(); - ImGui.TextColored(Accent, p.DisplayName); + SafeImGui.TextColored(Accent, p.DisplayName); ImGui.SameLine(); - ImGui.TextColored(TextMute, ver); + SafeImGui.TextColored(TextMute, ver); ImGui.SameLine(300f); - ImGui.TextColored(statusColor, statusText); + SafeImGui.TextColored(statusColor, statusText); if (!string.IsNullOrEmpty(p.SourceFilePath)) { ImGui.SameLine(); - ImGui.TextColored(TextMute, $"<{p.FileName}>"); + SafeImGui.TextColored(TextMute, $"<{p.FileName}>"); } string caps = ""; @@ -761,7 +761,7 @@ internal static class RynthCoreShell if (caps.Length > 0) { ImGui.SameLine(); - ImGui.TextColored(TextMute, $"[{caps.Trim()}]"); + SafeImGui.TextColored(TextMute, $"[{caps.Trim()}]"); } ImGui.PopID(); @@ -796,7 +796,7 @@ internal static class RynthCoreShell _selectedPlugin = i; ImGui.SameLine(); - ImGui.TextColored(TextMute, PluginStatuses[i]); + SafeImGui.TextColored(TextMute, PluginStatuses[i]); ImGui.PopID(); } @@ -805,8 +805,8 @@ internal static class RynthCoreShell if (_selectedPlugin >= 0 && _selectedPlugin < PluginNames.Length) { - ImGui.TextColored(Gold, PluginNames[_selectedPlugin]); - ImGui.TextColored(TextMute, PluginStatuses[_selectedPlugin]); + SafeImGui.TextColored(Gold, PluginNames[_selectedPlugin]); + SafeImGui.TextColored(TextMute, PluginStatuses[_selectedPlugin]); } ImGui.EndChild(); @@ -819,7 +819,7 @@ internal static class RynthCoreShell // ── Loaded plugins ────────────────────────────────────────────────── var loadedPlugins = PluginManager.Plugins; - ImGui.TextColored(Accent, $"Loaded Plugins ({loadedPlugins.Count})"); + SafeImGui.TextColored(Accent, $"Loaded Plugins ({loadedPlugins.Count})"); ImGui.Separator(); if (loadedPlugins.Count == 0) @@ -838,12 +838,12 @@ internal static class RynthCoreShell string ver = string.IsNullOrEmpty(p.VersionString) ? "" : $" v{p.VersionString}"; ImGui.BulletText(""); ImGui.SameLine(); - ImGui.TextColored(Accent, p.DisplayName); + SafeImGui.TextColored(Accent, p.DisplayName); ImGui.SameLine(); - ImGui.TextColored(TextMute, ver); + SafeImGui.TextColored(TextMute, ver); ImGui.SameLine(280f); - ImGui.TextColored(statusColor, statusText); - ImGui.TextColored(TextMute, $" {p.SourceFilePath}"); + SafeImGui.TextColored(statusColor, statusText); + SafeImGui.TextColored(TextMute, $" {p.SourceFilePath}"); } } @@ -859,7 +859,7 @@ internal static class RynthCoreShell { ImGui.TextColored(TextMute, "Built-in directory:"); ImGui.SameLine(); - ImGui.TextColored(TextDim, builtInDir); + SafeImGui.TextColored(TextDim, builtInDir); } ImGui.Spacing(); @@ -877,9 +877,9 @@ internal static class RynthCoreShell { ImGui.PushID($"pluginpath_{i}"); bool exists = File.Exists(extraPaths[i]); - ImGui.TextColored(exists ? Good : Warn, exists ? " OK" : " ??"); + SafeImGui.TextColored(exists ? Good : Warn, exists ? " OK" : " ??"); ImGui.SameLine(); - ImGui.TextColored(TextDim, extraPaths[i]); + SafeImGui.TextColored(TextDim, extraPaths[i]); ImGui.SameLine(); if (ImGui.SmallButton("Remove")) removeIdx = i; @@ -946,34 +946,34 @@ internal static class RynthCoreShell ImGui.Spacing(); ImGui.TextColored(TextMute, "Combat"); - ImGui.TextWrapped($"Melee {OnOff(status.MeleeAvailable)} Missile {OnOff(status.MissileAvailable)} Mode {OnOff(status.ChangeCombatModeAvailable)} Cancel {OnOff(status.CancelAttackAvailable)} Health {OnOff(status.QueryHealthAvailable)}"); - ImGui.TextColored(TextMute, status.CombatStatus); + SafeImGui.TextWrapped($"Melee {OnOff(status.MeleeAvailable)} Missile {OnOff(status.MissileAvailable)} Mode {OnOff(status.ChangeCombatModeAvailable)} Cancel {OnOff(status.CancelAttackAvailable)} Health {OnOff(status.QueryHealthAvailable)}"); + SafeImGui.TextColored(TextMute, status.CombatStatus); ImGui.Spacing(); ImGui.TextColored(TextMute, "Movement"); - ImGui.TextWrapped($"Move {OnOff(status.DoMovementAvailable)} Stop {OnOff(status.StopMovementAvailable)} Jump {OnOff(status.JumpNonAutonomousAvailable)} Autonomy {OnOff(status.AutonomyLevelAvailable)}"); - ImGui.TextColored(TextMute, status.MovementStatus); + SafeImGui.TextWrapped($"Move {OnOff(status.DoMovementAvailable)} Stop {OnOff(status.StopMovementAvailable)} Jump {OnOff(status.JumpNonAutonomousAvailable)} Autonomy {OnOff(status.AutonomyLevelAvailable)}"); + SafeImGui.TextColored(TextMute, status.MovementStatus); ImGui.Spacing(); ImGui.TextColored(TextMute, "Local"); - ImGui.TextWrapped($"Autorun {OnOff(status.SetAutoRunAvailable)} TapJump {OnOff(status.TapJumpAvailable)}"); - ImGui.TextColored(TextMute, status.CommandInterpreterStatus); + SafeImGui.TextWrapped($"Autorun {OnOff(status.SetAutoRunAvailable)} TapJump {OnOff(status.TapJumpAvailable)}"); + SafeImGui.TextColored(TextMute, status.CommandInterpreterStatus); ImGui.Spacing(); ImGui.TextColored(TextMute, "UI"); - ImGui.TextColored(TextMute, UiLifecycleHooks.StatusMessage); + SafeImGui.TextColored(TextMute, UiLifecycleHooks.StatusMessage); ImGui.Spacing(); ImGui.TextColored(TextMute, "Chat"); - ImGui.TextColored(TextMute, ChatCallbackHooks.StatusMessage); + SafeImGui.TextColored(TextMute, ChatCallbackHooks.StatusMessage); ImGui.Spacing(); ImGui.TextColored(TextMute, "Multi-client"); - ImGui.TextColored(TextMute, MultiClientHooks.StatusMessage); + SafeImGui.TextColored(TextMute, MultiClientHooks.StatusMessage); ImGui.Spacing(); ImGui.TextColored(TextMute, "Lifecycle"); - ImGui.TextColored(TextMute, LoginLifecycleHooks.StatusMessage); + SafeImGui.TextColored(TextMute, LoginLifecycleHooks.StatusMessage); ImGui.EndChild(); } @@ -1032,8 +1032,8 @@ internal static class RynthCoreShell private static void DrawMetric(in ShellMetric metric) { ImGui.BeginChild($"{metric.Label}Card", new Vector2(0f, 76f), ImGuiChildFlags.Borders); - ImGui.TextColored(TextMute, metric.Label); - ImGui.TextColored(metric.Color, metric.Value); + SafeImGui.TextColored(TextMute, metric.Label); + SafeImGui.TextColored(metric.Color, metric.Value); ImGui.EndChild(); } @@ -1047,14 +1047,14 @@ internal static class RynthCoreShell drawList.AddRectFilled(pos, pos + new Vector2(size.X + 16f, size.Y + 8f), fill, 6f); drawList.AddRect(pos, pos + new Vector2(size.X + 16f, size.Y + 8f), stroke, 6f); ImGui.SetCursorScreenPos(pos + new Vector2(8f, 4f)); - ImGui.TextColored(color, text); + SafeImGui.TextColored(color, text); } private static void DrawFeatureLine(string name, string state, Vector4 color) { - ImGui.TextColored(TextDim, name); + SafeImGui.TextColored(TextDim, name); ImGui.SameLine(190f); - ImGui.TextColored(color, state); + SafeImGui.TextColored(color, state); } private static string OnOff(bool value) @@ -1073,16 +1073,16 @@ internal static class RynthCoreShell private static void DrawBulletRow(string label, string value) { - ImGui.BulletText($"{label}: {value}"); + SafeImGui.BulletText($"{label}: {value}"); } private static void DrawRoadmapStep(string index, string title, string body, Vector4 color) { ImGui.BeginChild($"Roadmap{index}", new Vector2(0f, 68f), ImGuiChildFlags.Borders); - ImGui.TextColored(color, $"Step {index}"); + SafeImGui.TextColored(color, $"Step {index}"); ImGui.SameLine(); - ImGui.TextColored(TextDim, title); - ImGui.TextWrapped(body); + SafeImGui.TextColored(TextDim, title); + SafeImGui.TextWrapped(body); ImGui.EndChild(); } @@ -1158,13 +1158,13 @@ internal static class RynthCoreShell ImGui.TableNextRow(); ImGui.TableSetColumnIndex(0); - ImGui.TextColored(isKnown ? TextMute : Accent, $"0x{opcode:X4}"); + SafeImGui.TextColored(isKnown ? TextMute : Accent, $"0x{opcode:X4}"); ImGui.TableSetColumnIndex(1); - ImGui.TextColored(TextDim, entry.Count.ToString()); + SafeImGui.TextColored(TextDim, entry.Count.ToString()); ImGui.TableSetColumnIndex(2); - ImGui.TextColored(TextDim, entry.LastPayloadLen.ToString()); + SafeImGui.TextColored(TextDim, entry.LastPayloadLen.ToString()); ImGui.TableSetColumnIndex(3); if (entry.LastSample is { Length: > 0 }) @@ -1176,7 +1176,7 @@ internal static class RynthCoreShell sb.Append(b.ToString("X2")); sb.Append(' '); } - ImGui.TextColored(TextMute, sb.ToString().TrimEnd()); + SafeImGui.TextColored(TextMute, sb.ToString().TrimEnd()); } } @@ -1186,7 +1186,7 @@ internal static class RynthCoreShell if (visibleCount == 0) { ImGui.Spacing(); - ImGui.TextColored(TextMute, snapshot.Length == 0 + SafeImGui.TextColored(TextMute, snapshot.Length == 0 ? "No packets captured yet — join a server and traffic will appear here." : "All captured opcodes filtered. Toggle 'Show Known' / 'Show Unknown' to see them."); } diff --git a/src/RynthCore.Engine/ImGui/SafeImGui.cs b/src/RynthCore.Engine/ImGui/SafeImGui.cs new file mode 100644 index 0000000..8fe452d --- /dev/null +++ b/src/RynthCore.Engine/ImGui/SafeImGui.cs @@ -0,0 +1,44 @@ +// ============================================================================ +// RynthCore.Engine - ImGui/SafeImGui.cs +// ImGui text calls for text that isn't a literal: chat lines, item, monster and +// player names, plugin and script text, server replies, interpolated strings. +// +// ImGui.NET passes the string of Text / TextColored / TextWrapped / +// TextDisabled / BulletText / SetTooltip / SetItemTooltip / LabelText to +// native ImGui as a printf format with no arguments, so a '%' in it reads +// arguments that were never passed (garbage, or a crash on %s / %n). These +// wrappers double every '%' so the text draws exactly as given. Same +// signatures as ImGui's, so a call site only changes "ImGui." to "SafeImGui.". +// In the root namespace so every engine namespace sees it. Render thread only. +// ============================================================================ + +using System.Numerics; + +namespace RynthCore.Engine; + +internal static class SafeImGui +{ + /// The text as a printf format that prints it unchanged ('%' doubled); null is empty. + internal static string Escape(string? text) + { + if (string.IsNullOrEmpty(text)) return string.Empty; + return text.IndexOf('%') < 0 ? text : text.Replace("%", "%%"); + } + + public static void Text(string? text) => ImGuiNET.ImGui.Text(Escape(text)); + + public static void TextColored(Vector4 color, string? text) => ImGuiNET.ImGui.TextColored(color, Escape(text)); + + public static void TextWrapped(string? text) => ImGuiNET.ImGui.TextWrapped(Escape(text)); + + public static void TextDisabled(string? text) => ImGuiNET.ImGui.TextDisabled(Escape(text)); + + public static void BulletText(string? text) => ImGuiNET.ImGui.BulletText(Escape(text)); + + public static void SetTooltip(string? text) => ImGuiNET.ImGui.SetTooltip(Escape(text)); + + public static void SetItemTooltip(string? text) => ImGuiNET.ImGui.SetItemTooltip(Escape(text)); + + /// The label is drawn as text, not used as a format; only the value is escaped. + public static void LabelText(string label, string? text) => ImGuiNET.ImGui.LabelText(label, Escape(text)); +} diff --git a/src/RynthCore.Engine/Net/AelrynthVaultWire.cs b/src/RynthCore.Engine/Net/AelrynthVaultWire.cs index dad5fe1..21f9383 100644 --- a/src/RynthCore.Engine/Net/AelrynthVaultWire.cs +++ b/src/RynthCore.Engine/Net/AelrynthVaultWire.cs @@ -10,7 +10,7 @@ // {"t":"mule","ready":false,"why":"loading"} (still loading on the server: never an empty vault) // // A field the reader does not know is ignored, so the mod can add fields. Pure code (no engine state); -// compiled into tools/NetMessageTests. +// compiled into tools/NetMessageTests (with Net/ChatOrigin.cs). // ============================================================================ using System; @@ -48,20 +48,26 @@ internal static class AelrynthVaultWire /// The command for a page (1 = the bare command). public static string PageCommand(int page) => page <= 1 ? Command : Command + " " + page.ToString(System.Globalization.CultureInfo.InvariantCulture); - /// A "~ael1" data line whose kind is "mule" (another mod's data line is not ours). + /// + /// A "~ael1" data line whose kind is "mule" (another mod's data line is not ours). The prefix + /// must start the line: a player's copy has their name in front (ChatOrigin). + /// public static bool IsMuleLine(string? line) { - if (string.IsNullOrEmpty(line)) return false; - int at = line.IndexOf(Prefix, StringComparison.Ordinal); - return at >= 0 && line.IndexOf("\"t\":\"mule\"", at, StringComparison.Ordinal) >= 0; + if (!ChatOrigin.StartsWithMarker(line, Prefix)) return false; + return line!.IndexOf("\"t\":\"mule\"", ChatOrigin.ContentStart(line), StringComparison.Ordinal) >= 0; } - /// ACE's reply to a command it does not have ("Unknown command: mule-data"). + /// + /// ACE's reply to a command it does not have, "Unknown command: mule-data" (GameActionTalk names + /// the bare command; a leading / or @ is allowed). Anchored at the line's start. + /// public static bool IsUnknownCommand(string? line) { - if (string.IsNullOrEmpty(line)) return false; - return line.IndexOf("Unknown command", StringComparison.OrdinalIgnoreCase) >= 0 - && line.IndexOf(CommandName, StringComparison.OrdinalIgnoreCase) >= 0; + const string marker = "Unknown command:"; + if (!ChatOrigin.StartsWithMarker(line, marker, StringComparison.OrdinalIgnoreCase)) return false; + string named = line!.Substring(ChatOrigin.ContentStart(line) + marker.Length).Trim().TrimStart('/', '@'); + return string.Equals(named, CommandName, StringComparison.OrdinalIgnoreCase); } /// The page in a mule line; false when it is not one or is too damaged to read. @@ -71,7 +77,7 @@ internal static class AelrynthVaultWire if (!IsMuleLine(line)) return false; try { - int at = line!.IndexOf(Prefix, StringComparison.Ordinal) + Prefix.Length; + int at = ChatOrigin.ContentStart(line!) + Prefix.Length; using JsonDocument doc = JsonDocument.Parse(line.AsMemory(at)); JsonElement root = doc.RootElement; if (root.ValueKind != JsonValueKind.Object) return false; diff --git a/src/RynthCore.Engine/Net/ChatOrigin.cs b/src/RynthCore.Engine/Net/ChatOrigin.cs new file mode 100644 index 0000000..d55b97d --- /dev/null +++ b/src/RynthCore.Engine/Net/ChatOrigin.cs @@ -0,0 +1,54 @@ +// ============================================================================ +// RynthCore.Engine - Net/ChatOrigin.cs +// Telling a server line from a player's imitation of one. +// +// The engine eats its own "~ael1 " data replies (/mastery-data, /mule-data) +// and ACE's "Unknown command: ..." refusals before AC draws them. Another +// player can type the same text, so the readers need both checks here: +// - the chat type is not one a player writes in (ACE ChatMessageType, which +// is the client's eChatTypes: ACE.Entity/Enum/ChatMessageType.cs); +// - the line STARTS with the marker. The client puts the speaker in front +// of player text ("Name says, ...", "Name tells you, ...", "Name waves"), +// so a player's copy never starts with it. +// Pure code (no engine state); compiled into tools/NetMessageTests. +// Plugins have the same rules in RynthSuite Plugins/Shared/ChatSource.cs. +// ============================================================================ + +using System; + +namespace RynthCore.Engine.Net; + +internal static class ChatOrigin +{ + // Chat types whose text another player writes. + public const uint Speech = 0x02; + public const uint Tell = 0x03; + public const uint OutgoingTell = 0x04; + public const uint Channel = 0x08; + public const uint ChannelSend = 0x09; + public const uint Social = 0x0A; + public const uint SocialSend = 0x0B; + public const uint Emote = 0x0C; + public const uint Allegiance = 0x12; + public const uint Fellowship = 0x13; + + /// True when a line of this chat type is a player's words. + public static bool IsPlayerAuthored(uint chatType) => chatType switch + { + Speech or Tell or OutgoingTell or Channel or ChannelSend + or Social or SocialSend or Emote or Allegiance or Fellowship => true, + _ => false, + }; + + /// The index just past 's leading whitespace. + public static int ContentStart(string line) + { + int i = 0; + while (i < line.Length && char.IsWhiteSpace(line[i])) i++; + return i; + } + + /// True when , past leading whitespace, starts with . + public static bool StartsWithMarker(string? line, string marker, StringComparison comparison = StringComparison.Ordinal) + => line != null && line.AsSpan(ContentStart(line)).StartsWith(marker.AsSpan(), comparison); +} diff --git a/src/RynthCore.Engine/Plugins/EngineSettings.cs b/src/RynthCore.Engine/Plugins/EngineSettings.cs index 96c79fc..1c72850 100644 --- a/src/RynthCore.Engine/Plugins/EngineSettings.cs +++ b/src/RynthCore.Engine/Plugins/EngineSettings.cs @@ -41,6 +41,8 @@ internal static class EngineSettings private static bool _serverMessageStream = true; private static bool _flightRecorder = true; private static bool _insertReleasesUi; + // "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; // "IltServerNames" / "IltHosts": what counts as Infinite Leaftide (Compatibility/IltInfo.cs). @@ -110,6 +112,21 @@ internal static class EngineSettings } } + /// + /// True: every installed server plugin (RynthColdeve, RynthILT, ...) loads, whatever server the + /// client connects to; each still shows only on its own server. Default false: the connect host + /// picks the one plugin for this server (PluginManifestGate.SelectServerPlugins). Set + /// "LoadAllServerPlugins": true in engine.json by hand (testing a plugin with /rc server ... on). + /// + public static bool LoadAllServerPlugins + { + get + { + EnsureLoaded(); + return _loadAllServerPlugins; + } + } + /// When false, AvaloniaOverlay.Start() is skipped so the Avalonia STA thread, /// the offscreen overlay window, and all OverlayHost-registered panels never instantiate. /// Eliminates the entire Avalonia/Skia surface from the process. Compatibility hooks and @@ -425,7 +442,8 @@ internal static class EngineSettings /// "IltServerNames" in engine.json: world-name patterns ('*' wildcard, case-insensitive) /// treated as Infinite Leaftide; null when the file has none (IltDetect.DefaultServerNames). - /// An empty array turns the world-name signal off. Read only: edited in the file. + /// An empty array turns the world-name signal off. Edited in the file, or with + /// "/rc server names ilt add|remove" (EditIltServerName). public static IReadOnlyList? IltServerNames { get @@ -435,6 +453,31 @@ internal static class EngineSettings } } + /// Longest world-name pattern EditIltServerName takes. + public const int MaxIltServerNameLength = 64; + + /// + /// Adds () or removes a world-name pattern in "IltServerNames" and saves + /// engine.json. With none in the file the list starts from IltDetect.DefaultServerNames, so + /// adding one keeps the defaults. False when nothing changed (already there, not there, or + /// an empty / too long pattern). + /// + public static bool EditIltServerName(string pattern, bool add) + { + EnsureLoaded(); + string p = (pattern ?? string.Empty).Trim(); + if (p.Length == 0 || p.Length > MaxIltServerNameLength) return false; + var list = new List(_iltServerNames ?? (IEnumerable)Compatibility.IltDetect.DefaultServerNames); + int at = list.FindIndex(x => x.Equals(p, StringComparison.OrdinalIgnoreCase)); + if (add == (at >= 0)) return false; + if (add) list.Add(p); + else list.RemoveAt(at); + // Replaced, never edited in place: IltInfo reads the old list on other threads. + _iltServerNames = list; + Save(); + return true; + } + /// "IltHosts" in engine.json: launch hosts (a domain covers its subdomains, '*' allowed) /// treated as Infinite Leaftide; null when the file has none (IltDetect.DefaultHosts). public static IReadOnlyList? IltHosts @@ -538,6 +581,12 @@ internal static class EngineSettings _enableLargeAddressAlignmentFix = laaEl.GetBoolean(); } + if (doc.RootElement.TryGetProperty("LoadAllServerPlugins", out var lasEl) && + (lasEl.ValueKind == JsonValueKind.True || lasEl.ValueKind == JsonValueKind.False)) + { + _loadAllServerPlugins = lasEl.GetBoolean(); + } + if (doc.RootElement.TryGetProperty("EnableAvaloniaOverlay", out var avEl) && (avEl.ValueKind == JsonValueKind.True || avEl.ValueKind == JsonValueKind.False)) { @@ -694,6 +743,7 @@ internal static class EngineSettings "DecalInGameImGui", "DecalStandDown", "DisabledUiHooks", "ServerMessageStream", "FlightRecorder", "InsertReleasesUi", "IltServerNames", "IltHosts", "EnableLargeAddressAlignmentFix", "MaxHotReloads", "ReportEndpoint", "CloseOnServerDisconnect", "AutoIdMode", "EnablePluginOverlayWindows", "LoggingLevel", + "LoadAllServerPlugins", }; private static void Save() @@ -747,6 +797,8 @@ internal static class EngineSettings w.WriteBoolean("InsertReleasesUi", true); if (!_closeOnServerDisconnect) // default true: leave the file as it was w.WriteBoolean("CloseOnServerDisconnect", 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 (_reportEndpoint != null) // only a hand-set value is written diff --git a/src/RynthCore.Engine/Plugins/LoadedPlugin.cs b/src/RynthCore.Engine/Plugins/LoadedPlugin.cs index 0ce3f41..7301ee8 100644 --- a/src/RynthCore.Engine/Plugins/LoadedPlugin.cs +++ b/src/RynthCore.Engine/Plugins/LoadedPlugin.cs @@ -67,6 +67,13 @@ internal sealed class LoadedPlugin /// public IntPtr RenderEmbedPtr { get; set; } + /// + /// Optional const char* RynthPluginGetSectionsJson(void), Cdecl: the plugin's Mini + /// Remote sections manifest, UTF-8 JSON (UI/Sections/SectionManifest.cs). The buffer is the + /// plugin's, valid until its next call. Zeroed after it throws. + /// + public IntPtr SectionsJsonPtr { get; set; } + // ─── v77 UI exports (resolved lazily by PluginManager.ResolveUiExports) ─── public bool UiExportsResolved { get; set; } public IntPtr OnScreenChangedPtr { get; set; } @@ -137,5 +144,6 @@ internal sealed class LoadedPlugin Render = null; RenderOverlay = null; RenderEmbedPtr = IntPtr.Zero; + SectionsJsonPtr = IntPtr.Zero; } } diff --git a/src/RynthCore.Engine/Plugins/PluginContract.cs b/src/RynthCore.Engine/Plugins/PluginContract.cs index 34dd2ff..c73c4f0 100644 --- a/src/RynthCore.Engine/Plugins/PluginContract.cs +++ b/src/RynthCore.Engine/Plugins/PluginContract.cs @@ -922,6 +922,28 @@ internal struct RynthCoreAPI /// Off AC's main thread a walk of the object's qualities tables is requested for the next tick /// (flag QualitiesPending): ask again a moment later for the full set. Any thread. Requires API v84+. public IntPtr GetObjectPropertiesFn; + + /// v85: int ArmConfirmation(uint type, int minPercent, int timeoutMs): answer + /// the next server yes/no prompt (ConfirmationRequest 0x0274) of this type within timeoutMs, + /// without the client opening its dialog: Yes when the server's "N percent" is at least + /// minPercent (or minPercent is 0), else No. One-shot. timeoutMs <= 0 disarms. + /// 1 armed/disarmed, 0 sender or game-event hook unavailable, -3 bad arguments + /// (type 0, minPercent outside 0-100, timeout over 120 s). Any thread. Requires API v85+. + public IntPtr ArmConfirmationFn; + + /// v85: int GetLastConfirmation(uint* type, uint* contextId, int* percent, int* outcome, int* ageMs): + /// the last prompt the server sent: returns its sequence number (0 = none yet); percent -1 + /// when the text has none; outcome 1 shown to the player, 2 answered Yes, 3 answered No, + /// 4 the send failed (shown). Any out pointer may be null. Any thread. Requires API v85+. + public IntPtr GetLastConfirmationFn; + + /// v86: int GetServerStateJson(byte* buffer, int capacity): which server this is, + /// for every plugin: each server the engine knows (built in, or declared by a loaded plugin) + /// with its verdict, this character's override, why, and the plugin that owns its settings; + /// plus the active server and the Diagnostics pick (UI/Sections/ServerStateJson.cs has the + /// schema). Copies NUL-terminated UTF-8 JSON when it fits and returns its byte length either + /// way (length >= capacity: call again with a bigger buffer). Any thread. Requires API v86+. + public IntPtr GetServerStateJsonFn; } /// v79 bits. @@ -1717,6 +1739,12 @@ internal unsafe delegate int GetVendorTradeStatusCallbackDelegate(VendorTradeSta [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal unsafe delegate int GetMergeStackResultCallbackDelegate(uint sourceObjectId, uint targetObjectId, int* amount, int* ageMs); +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal delegate int ArmConfirmationCallbackDelegate(uint type, int minPercent, int timeoutMs); + +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate int GetLastConfirmationCallbackDelegate(uint* type, uint* contextId, int* percent, int* outcome, int* ageMs); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal unsafe delegate int GetVTankStateCallbackDelegate(int* sequence); @@ -1726,6 +1754,9 @@ internal unsafe delegate int GetCharacterTitlesCallbackDelegate(uint* ids, int m [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal unsafe delegate int GetServerInfoCallbackDelegate(byte* worldName, int capacity); +[UnmanagedFunctionPointer(CallingConvention.Cdecl)] +internal unsafe delegate int GetServerStateJsonCallbackDelegate(byte* buffer, int capacity); + [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate int CloseContainerCallbackDelegate(uint containerId); diff --git a/src/RynthCore.Engine/Plugins/PluginContractVersion.cs b/src/RynthCore.Engine/Plugins/PluginContractVersion.cs index 0c3bb68..c3b4392 100644 --- a/src/RynthCore.Engine/Plugins/PluginContractVersion.cs +++ b/src/RynthCore.Engine/Plugins/PluginContractVersion.cs @@ -19,5 +19,8 @@ internal static class PluginContractVersion // v82: SalvageDirect (salvage without the salvage panel; was v81 on feature/salvage-direct). // v83: GetObjectServerAge and RemoveClientObject (ghost creatures, 2026-10-12). // v84: GetObjectProperties (every property of an object, for /ub propertydump; 2026-10-13). - public const uint Current = 84; + // v85: ArmConfirmation and GetLastConfirmation (answer the craft-chance prompt for a plugin; + // was v81, then v84 on build-comp-10-11, renumbered after upstream's v81-v84). + // v86: GetServerStateJson (the server list, active server and owning plugins for every plugin). + public const uint Current = 86; } diff --git a/src/RynthCore.Engine/Plugins/PluginLoader.cs b/src/RynthCore.Engine/Plugins/PluginLoader.cs index b77b53e..8ee26e7 100644 --- a/src/RynthCore.Engine/Plugins/PluginLoader.cs +++ b/src/RynthCore.Engine/Plugins/PluginLoader.cs @@ -515,6 +515,7 @@ internal static class PluginLoader // Called through a function pointer (PluginManager.RenderEmbed), so no delegate here. plugin.RenderEmbedPtr = GetProcAddress(handle, "RynthPluginRenderEmbed"); + plugin.SectionsJsonPtr = GetProcAddress(handle, "RynthPluginGetSectionsJson"); // Read name/version from the plugin if available if (plugin.GetName != null) diff --git a/src/RynthCore.Engine/Plugins/PluginManager.ServerPlugins.cs b/src/RynthCore.Engine/Plugins/PluginManager.ServerPlugins.cs new file mode 100644 index 0000000..e5b2160 --- /dev/null +++ b/src/RynthCore.Engine/Plugins/PluginManager.ServerPlugins.cs @@ -0,0 +1,153 @@ +// ============================================================================ +// RynthCore.Engine - Plugins/PluginManager.ServerPlugins.cs +// Server plugins the connect host left out (PluginManifestGate.SelectServerPlugins): +// kept with their manifests so Options > Diagnostics lists their servers, and +// loaded one at a time when a server is forced On (the Diagnostics picker, +// "/rc server on", or a character's saved override), without a rescan. +// +// Threads: the list is published as an immutable array (any thread reads it); +// a load request is queued from any thread and served on the pump thread +// (ProcessPendingActions), where every other plugin load happens. +// ============================================================================ + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using RynthCore.Engine.Compatibility; +using RynthCore.PluginSdk.Manifest; + +namespace RynthCore.Engine.Plugins; + +/// An installed server plugin that is not loaded because the client connects to another server. +internal sealed record SkippedServerPlugin(string Path, RynthPluginManifest Manifest) +{ + public string ServerId => Manifest.Server!.Id; + public string ServerName => Manifest.Server!.Name; + public string PluginName => Manifest.Name; +} + +internal static partial class PluginManager +{ + private static SkippedServerPlugin[] _skippedServerPlugins = Array.Empty(); + private static readonly ConcurrentQueue _serverPluginLoadRequests = new(); + + /// Installed server plugins not loaded for this connect host. Any thread. + public static IReadOnlyList SkippedServerPlugins => System.Threading.Volatile.Read(ref _skippedServerPlugins); + + /// The skipped server plugin for , or null. Any thread. + public static SkippedServerPlugin? FindSkippedServerPlugin(string serverId) + { + foreach (SkippedServerPlugin s in SkippedServerPlugins) + if (s.ServerId.Equals(serverId, StringComparison.OrdinalIgnoreCase)) return s; + return null; + } + + /// + /// Loads the plugin for on the next pump tick, if the connect host + /// left it out. Nothing happens for a server whose plugin is loaded already. Any thread. + /// + public static void RequestServerPluginLoad(string serverId) + { + if (string.IsNullOrWhiteSpace(serverId) || FindSkippedServerPlugin(serverId) == null) return; + _serverPluginLoadRequests.Enqueue(serverId.Trim()); + } + + /// LoadPluginsFromDisk: the gate's skipped server plugins (replaces the list). Pump thread. + private static void RememberSkippedServerPlugins(List<(string Path, RynthPluginManifest Manifest)> skipped) + { + var list = new List(skipped.Count); + foreach ((string path, RynthPluginManifest manifest) in skipped) + if (manifest.Server != null) list.Add(new SkippedServerPlugin(path, manifest)); + System.Threading.Volatile.Write(ref _skippedServerPlugins, list.ToArray()); + } + + /// Serves the queued requests (ProcessPendingActions). Pump thread. + private static void LoadRequestedServerPlugins() + { + while (_serverPluginLoadRequests.TryDequeue(out string? serverId)) + { + SkippedServerPlugin? s = FindSkippedServerPlugin(serverId); + if (s == null) continue; // loaded by an earlier request, or a rescan changed the list + SkippedServerPlugin[] rest = Array.FindAll(System.Threading.Volatile.Read(ref _skippedServerPlugins), x => !ReferenceEquals(x, s)); + System.Threading.Volatile.Write(ref _skippedServerPlugins, rest); + LoadSkippedServerPlugin(s); + } + } + + /// Loads, starts and catches up one server plugin, as if it had loaded with the others. Pump thread. + private static void LoadSkippedServerPlugin(SkippedServerPlugin s) + { + string file = Path.GetFileName(s.Path); + if (FindPlugin(s.PluginName) != null) return; + if (!File.Exists(s.Path)) + { + RynthLog.Warn($"PluginManager: {file} for {s.ServerName} is gone from disk - not loaded."); + return; + } + + // The checks the gate skipped for it: engine API and required plugins. + PluginResolution res = PluginManifestResolver.Resolve( + new[] { new PluginCandidate(s.Path, s.Manifest, RawFileVersion(s.Path)) }, PluginContractVersion.Current); + foreach (PluginRefusal refusal in res.Refused) + { + RefusePlugin(file, refusal.Reason); + return; + } + + RynthLog.Plugin($"PluginManager: {s.ServerName} ({s.ServerId}) forced On - loading {file} (va before: {Compatibility.AddressSpace.Describe()})"); + LoadedPlugin? plugin = PluginLoader.LoadSingle(s.Path, _shadowRootDir, _loadGeneration); + RynthLog.Plugin($"PluginManager: loaded {file}{(plugin == null ? " (FAILED)" : "")} (va after: {Compatibility.AddressSpace.Describe()})"); + if (plugin == null) + { + AcMainThreadQueue.EnqueueWriteToChat($"[RynthCore] {s.PluginName} for {s.ServerName} failed to load - see the RynthCore log.", 1); + return; + } + + plugin.Manifest = s.Manifest; + _plugins.Add(plugin); + PublishPluginsRenderSnapshot(); + EnsureHostCallbacks(); + InitializePlugin(plugin); + DispatchLifecycleToLatePlugin(plugin); + UI.Sections.SectionRegistry.RefreshManifests(); + + if (plugin.Initialized && !plugin.Failed) + AcMainThreadQueue.EnqueueWriteToChat($"[RynthCore] Loaded {s.PluginName} for {s.ServerName} (forced On in Options > Diagnostics).", 1); + } + + /// + /// OnUIInitialized and OnLoginComplete for one plugin started after the others, when the engine + /// has seen them. Unlike the full dispatchers it leaves the other plugins and the login-time + /// engine work (self-identify, combat mode and target sync) alone. Pump thread. + /// + private static void DispatchLifecycleToLatePlugin(LoadedPlugin plugin) + { + if (!plugin.Initialized || plugin.Failed) return; + LoadedPlugin? outer = EnterDispatch(plugin); + try + { + if (_uiInitializedObserved && plugin.OnUIInitialized != null && !plugin.UIInitializedDispatched) + { + plugin.OnUIInitialized(); + plugin.UIInitializedDispatched = true; + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} received OnUIInitialized (late load)."); + } + if (_loginCompleteObserved && plugin.OnLoginComplete != null && !plugin.LoginCompleteDispatched) + { + plugin.OnLoginComplete(); + plugin.LoginCompleteDispatched = true; + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} received OnLoginComplete (late load)."); + } + } + catch (Exception ex) + { + plugin.Failed = true; + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} lifecycle (late load) threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); + } + finally + { + LeaveDispatch(outer); + } + } +} \ No newline at end of file diff --git a/src/RynthCore.Engine/Plugins/PluginManager.cs b/src/RynthCore.Engine/Plugins/PluginManager.cs index 07de43d..2283e9d 100644 --- a/src/RynthCore.Engine/Plugins/PluginManager.cs +++ b/src/RynthCore.Engine/Plugins/PluginManager.cs @@ -276,6 +276,9 @@ internal static partial class PluginManager private static VendorSellCallbackDelegate? _vendorSellCallback; private static GetVendorTradeStatusCallbackDelegate? _getVendorTradeStatusCallback; private static GetMergeStackResultCallbackDelegate? _getMergeStackResultCallback; + private static ArmConfirmationCallbackDelegate? _armConfirmationCallback; // v85 + private static GetLastConfirmationCallbackDelegate? _getLastConfirmationCallback; // v85 + private static GetServerStateJsonCallbackDelegate? _getServerStateJsonCallback; // v86 private static ForceResetBusyCountCallbackDelegate? _forceResetBusyCountCallback; private static GetObjectSpellIdsCallbackDelegate? _getObjectSpellIdsCallback; private static GetObjectSkillLevelCallbackDelegate? _getObjectSkillBuffedCallback; @@ -587,6 +590,10 @@ internal static partial class PluginManager RescanPlugins(imguiContext, d3dDevice, gameHwnd); } + // A server forced On whose plugin the connect host left out: load just that plugin. + if (_initialized) + LoadRequestedServerPlugins(); + if (_uiDispatchPending && _initialized) DispatchUIInitializedToLoadedPlugins(); @@ -656,6 +663,8 @@ internal static partial class PluginManager ImGuiBackend.Hud.HudFeed.OnChat(text); // Who to /reply and /retell to (ChatCommandDispatcher rewrites those to a /tell). Compatibility.TellMemory.Shared.OnChatLine(text); + // Luminance deposited into ACECustom's bank isn't session income (SessionRates). + Compatibility.EngineStatusMetrics.OnChatLine(text); if (!_initialized || _plugins.Count == 0) return false; @@ -1344,30 +1353,69 @@ internal static partial class PluginManager { want = System.Numerics.Vector2.Zero; LoadedPlugin[] plugins = System.Threading.Volatile.Read(ref _pluginsRenderSnapshot); + LoadedPlugin? p = FindRenderPlugin(plugins, pluginName); + if (p == null) return EmbedNoPlugin; + IntPtr fn = p.RenderEmbedPtr; + if (fn == IntPtr.Zero) return EmbedNoPlugin; + float w = 0, h = 0; + try + { + int r; + fixed (byte* s = surfaceUtf8) + r = ((delegate* unmanaged[Cdecl])fn)(s, size.X, size.Y, &w, &h); + want = new System.Numerics.Vector2(float.IsFinite(w) ? MathF.Max(0, w) : 0, float.IsFinite(h) ? MathF.Max(0, h) : 0); + return r == 1 ? EmbedDrawn : EmbedNotReady; + } + catch (Exception ex) + { + p.RenderEmbedPtr = IntPtr.Zero; + RynthLog.Error($"PluginManager: {p.DisplayName} RenderEmbed threw {ex.GetType().Name}: {ex.Message} - embedded surfaces off for this session (plugin keeps running)."); + return EmbedFailed; + } + } + + /// A running plugin in the render snapshot by name: exact first (see ResolvePluginExport), else contains. + private static LoadedPlugin? FindRenderPlugin(LoadedPlugin[] plugins, string pluginName) + { + for (int pass = 0; pass < 2; pass++) + for (int i = 0; i < plugins.Length; i++) + { + LoadedPlugin p = plugins[i]; + if (p.Initialized && !p.Failed && NameMatches(p.DisplayName, pluginName, exact: pass == 0)) + return p; + } + return null; + } + + /// + /// Each running plugin's Mini Remote sections manifest (its optional + /// RynthPluginGetSectionsJson export), copied out as (display name, JSON). A plugin whose + /// export throws has it switched off for the session. Render thread (UI/Sections). + /// + internal static unsafe List<(string Plugin, string Json)> CollectSectionManifests() + { + var result = new List<(string, string)>(); + if (!_loginCompleteObserved) return result; // plugins build these from in-world state + LoadedPlugin[] plugins = System.Threading.Volatile.Read(ref _pluginsRenderSnapshot); for (int i = 0; i < plugins.Length; i++) { LoadedPlugin p = plugins[i]; - if (!p.Initialized || p.Failed || !p.DisplayName.Contains(pluginName, StringComparison.OrdinalIgnoreCase)) - continue; - IntPtr fn = p.RenderEmbedPtr; - if (fn == IntPtr.Zero) return EmbedNoPlugin; - float w = 0, h = 0; + IntPtr fn = p.SectionsJsonPtr; + if (!p.Initialized || p.Failed || fn == IntPtr.Zero) continue; try { - int r; - fixed (byte* s = surfaceUtf8) - r = ((delegate* unmanaged[Cdecl])fn)(s, size.X, size.Y, &w, &h); - want = new System.Numerics.Vector2(float.IsFinite(w) ? MathF.Max(0, w) : 0, float.IsFinite(h) ? MathF.Max(0, h) : 0); - return r == 1 ? EmbedDrawn : EmbedNotReady; + IntPtr text = ((delegate* unmanaged[Cdecl])fn)(); + if (text == IntPtr.Zero) continue; + string? json = Marshal.PtrToStringUTF8(text); + if (!string.IsNullOrEmpty(json)) result.Add((p.DisplayName, json)); } catch (Exception ex) { - p.RenderEmbedPtr = IntPtr.Zero; - RynthLog.Error($"PluginManager: {p.DisplayName} RenderEmbed threw {ex.GetType().Name}: {ex.Message} - embedded surfaces off for this session (plugin keeps running)."); - return EmbedFailed; + p.SectionsJsonPtr = IntPtr.Zero; + RynthLog.Error($"PluginManager: {p.DisplayName} RynthPluginGetSectionsJson threw {ex.GetType().Name}: {ex.Message} - its sections are off for this session."); } } - return EmbedNoPlugin; + return result; } public static void ShutdownAll() @@ -1458,18 +1506,27 @@ internal static partial class PluginManager if (string.IsNullOrEmpty(pluginName) || string.IsNullOrEmpty(exportName)) return IntPtr.Zero; - for (int i = 0; i < _plugins.Count; i++) + // Exact name first: "RynthLeafDawn" is inside "RynthLeafdawning". + for (int pass = 0; pass < 2; pass++) { - var p = _plugins[i]; - if (p.ModuleHandle == IntPtr.Zero || !p.Initialized || p.Failed) - continue; - if (!p.DisplayName.Contains(pluginName, StringComparison.OrdinalIgnoreCase)) - continue; - return GetProcAddress(p.ModuleHandle, exportName); + for (int i = 0; i < _plugins.Count; i++) + { + var p = _plugins[i]; + if (p.ModuleHandle == IntPtr.Zero || !p.Initialized || p.Failed) + continue; + if (!NameMatches(p.DisplayName, pluginName, exact: pass == 0)) + continue; + return GetProcAddress(p.ModuleHandle, exportName); + } } return IntPtr.Zero; } + /// The plugin-name test of the by-name lookups: exact (any case), else "display name contains it". + private static bool NameMatches(string displayName, string pluginName, bool exact) => + exact ? string.Equals(displayName, pluginName, StringComparison.OrdinalIgnoreCase) + : displayName.Contains(pluginName, StringComparison.OrdinalIgnoreCase); + /// /// Reload deferral (2026-10-05, ReloadDeferral): asks every running plugin's optional /// const char* RynthPluginReloadBlocker(void) export whether a hot reload now would @@ -2606,10 +2663,15 @@ internal static partial class PluginManager // Manifests (embedded in the DLLs, read without loading them): refuse a plugin that needs // a newer engine API or a missing plugin, and put required plugins first. Without - // manifests the list loads exactly as before. - PluginManifestGate.LoadPlan plan = PluginManifestGate.Plan(candidates, PluginContractVersion.Current, RawFileVersion); + // manifests the list loads exactly as before. Server plugins: the connect host picks this + // server's (the others stay unloaded; their runtimes would only take address space). + PluginManifestGate.LoadPlan plan = PluginManifestGate.Plan(candidates, PluginContractVersion.Current, RawFileVersion, + Compatibility.ServerInfo.LaunchHost, EngineSettings.LoadAllServerPlugins); foreach (string line in plan.Log) RynthLog.Plugin($"PluginManager: {line}"); + if (plan.SkippedForServer.Count > 0) + RynthLog.Info($"PluginManager: {plan.SkippedForServer.Count} server plugin(s) for other servers not loaded (host {Compatibility.ServerInfo.HostDescription})."); + RememberSkippedServerPlugins(plan.SkippedServerPlugins); foreach (PluginRefusal refusal in plan.Refused) RefusePlugin(Path.GetFileName(refusal.Plugin.Key), refusal.Reason); @@ -2731,50 +2793,7 @@ internal static partial class PluginManager RynthLog.Plugin($"PluginManager: Initializing {_plugins.Count} plugin(s)..."); for (int i = 0; i < _plugins.Count; i++) - { - var plugin = _plugins[i]; - - // Manifest: a plugin whose required plugin didn't start isn't started either (they - // come first: LoadPluginsFromDisk ordered them). No manifest, no check. - string? blocked = PluginManifestGate.CheckRequiredStarted(plugin.Manifest, name => - FindPlugin(name) is { } dep ? dep.Initialized && !dep.Failed : null); - if (blocked != null) - { - plugin.Failed = true; - plugin.NotStartedReason = blocked; - RefusePlugin(plugin.FileName, blocked); - continue; - } - plugin.NotStartedReason = ""; - - LoadedPlugin? outer = EnterDispatch(plugin); - try - { - int result = plugin.Init!(ref _api); - if (result == 0) - { - plugin.Initialized = true; - plugin.Failed = false; - plugin.UIInitializedDispatched = false; - plugin.LoginCompleteDispatched = false; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} initialized OK (api v{PluginContractVersion.Current})."); - } - else - { - plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} Init returned {result} - marked as failed. (engine api version={PluginContractVersion.Current})"); - } - } - catch (Exception ex) - { - plugin.Failed = true; - RynthLog.Plugin($"PluginManager: {plugin.DisplayName} Init threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); - } - finally - { - LeaveDispatch(outer); - } - } + InitializePlugin(_plugins[i]); if (!_uiInitializedObserved) RynthLog.Plugin("PluginManager: Waiting for OnUIInitialized before starting UI-gated plugins."); @@ -2783,6 +2802,51 @@ internal static partial class PluginManager RynthLog.Plugin("PluginManager: Waiting for OnLoginComplete before starting login-gated plugins."); } + /// Calls one loaded plugin's Init (after checking its required plugins started). Pump thread. + private static void InitializePlugin(LoadedPlugin plugin) + { + // Manifest: a plugin whose required plugin didn't start isn't started either (they + // come first: LoadPluginsFromDisk ordered them). No manifest, no check. + string? blocked = PluginManifestGate.CheckRequiredStarted(plugin.Manifest, name => + FindPlugin(name) is { } dep ? dep.Initialized && !dep.Failed : null); + if (blocked != null) + { + plugin.Failed = true; + plugin.NotStartedReason = blocked; + RefusePlugin(plugin.FileName, blocked); + return; + } + plugin.NotStartedReason = ""; + + LoadedPlugin? outer = EnterDispatch(plugin); + try + { + int result = plugin.Init!(ref _api); + if (result == 0) + { + plugin.Initialized = true; + plugin.Failed = false; + plugin.UIInitializedDispatched = false; + plugin.LoginCompleteDispatched = false; + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} initialized OK (api v{PluginContractVersion.Current})."); + } + else + { + plugin.Failed = true; + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} Init returned {result} - marked as failed. (engine api version={PluginContractVersion.Current})"); + } + } + catch (Exception ex) + { + plugin.Failed = true; + RynthLog.Plugin($"PluginManager: {plugin.DisplayName} Init threw {ex.GetType().Name}: {ex.Message}{PluginTrace(ex)}"); + } + finally + { + LeaveDispatch(outer); + } + } + private static void UnloadAllPlugins() { for (int i = _plugins.Count - 1; i >= 0; i--) @@ -3064,6 +3128,9 @@ internal static partial class PluginManager _vendorSellCallback ??= VendorSellAction; _getVendorTradeStatusCallback ??= GetVendorTradeStatusAction; _getMergeStackResultCallback ??= GetMergeStackResultAction; + _armConfirmationCallback ??= ArmConfirmationAction; + unsafe { _getLastConfirmationCallback ??= GetLastConfirmationAction; } + unsafe { _getServerStateJsonCallback ??= GetServerStateJsonAction; } _api.Version = PluginContractVersion.Current; _api.LogFn = Marshal.GetFunctionPointerForDelegate(_logCallback); @@ -3214,6 +3281,9 @@ internal static partial class PluginManager _api.VendorSellFn = Marshal.GetFunctionPointerForDelegate(_vendorSellCallback); _api.GetVendorTradeStatusFn = Marshal.GetFunctionPointerForDelegate(_getVendorTradeStatusCallback); _api.GetMergeStackResultFn = Marshal.GetFunctionPointerForDelegate(_getMergeStackResultCallback); + _api.ArmConfirmationFn = Marshal.GetFunctionPointerForDelegate(_armConfirmationCallback); + _api.GetLastConfirmationFn = Marshal.GetFunctionPointerForDelegate(_getLastConfirmationCallback); + _api.GetServerStateJsonFn = Marshal.GetFunctionPointerForDelegate(_getServerStateJsonCallback); RouteApiThroughLoader(); } @@ -3407,6 +3477,25 @@ internal static partial class PluginManager } } + /// + /// v86: the server list as JSON (UI/Sections/ServerStateJson.cs) from the published snapshot. + /// Any thread: the snapshot is immutable and the strings are volatile reads. -1 on failure. + /// + private static unsafe int GetServerStateJsonAction(byte* buffer, int capacity) + { + try + { + UI.Sections.SectionRegistry.Snapshot snap = UI.Sections.SectionRegistry.Current; + string json = UI.Sections.ServerStateJson.Build(snap.Servers, snap.Manifests, snap.Revision, + ServerInfo.LaunchHost, AccountHooks.AnnouncedWorldName, UI.Sections.SectionRegistry.EnginePlugin); + return UI.Sections.ServerStateJson.Write(json, buffer, capacity); + } + catch + { + return -1; + } + } + private static unsafe int GetServerInfoAction(byte* worldName, int capacity) { try @@ -3956,6 +4045,32 @@ internal static partial class PluginManager } } + // v81: arm one answer for the next server yes/no prompt (ConfirmationResponder). + private static int ArmConfirmationAction(uint type, int minPercent, int timeoutMs) + { + try { return ConfirmationResponder.Arm(type, minPercent, timeoutMs); } + catch { return 0; } + } + + // v81: the last server yes/no prompt and what happened to it. + private static unsafe int GetLastConfirmationAction(uint* type, uint* contextId, int* percent, int* outcome, int* ageMs) + { + try + { + int seq = ConfirmationResponder.GetLast(out uint t, out uint ctx, out int pct, out int oc, out int age); + if (type != null) *type = t; + if (contextId != null) *contextId = ctx; + if (percent != null) *percent = pct; + if (outcome != null) *outcome = oc; + if (ageMs != null) *ageMs = age; + return seq; + } + catch + { + return 0; + } + } + private static int GiveObjectTo(uint objectId, uint targetId, int amount) { Compatibility.AcActionTrace.Record("GiveObjectTo", objectId, targetId); @@ -4564,6 +4679,33 @@ internal static partial class PluginManager return ToAbiBool(ClientHelperHooks.WieldItem(objectId, equipMask)); } + /// + /// The engine's own (action, value) to a loaded plugin's optional RynthPluginApplyRemoteCommand + /// (the plugin copies the strings and queues them). False when the plugin isn't loaded and + /// ready or has no such export. Same thread rules as ResolvePluginExport. + /// + internal static unsafe bool SendPluginCommand(string pluginName, string action, string value) + { + IntPtr export = ResolvePluginExport(pluginName, "RynthPluginApplyRemoteCommand"); + if (export == IntPtr.Zero || string.IsNullOrEmpty(action)) return false; + IntPtr a = Marshal.StringToHGlobalAnsi(action); + IntPtr v = Marshal.StringToHGlobalAnsi(value ?? string.Empty); + try + { + ((delegate* unmanaged[Cdecl])export)(a, v); + return true; + } + catch + { + return false; + } + finally + { + Marshal.FreeHGlobal(a); + Marshal.FreeHGlobal(v); + } + } + private static unsafe int SendPluginCommandAction(IntPtr pluginNameAnsi, IntPtr actionAnsi, IntPtr valueAnsi) { try diff --git a/src/RynthCore.Engine/Plugins/PluginManifestGate.cs b/src/RynthCore.Engine/Plugins/PluginManifestGate.cs index fa23acb..66d272f 100644 --- a/src/RynthCore.Engine/Plugins/PluginManifestGate.cs +++ b/src/RynthCore.Engine/Plugins/PluginManifestGate.cs @@ -29,14 +29,25 @@ internal static class PluginManifestGate public List Refused { get; } = new(); /// Log lines: manifests found, broken manifests, notes. public List Log { get; } = new(); + /// Server plugins for another server, left out on purpose (logged, never said in chat). + public List SkippedForServer { get; } = new(); + /// + /// The same plugins with their manifests (each has a Server): Options > Diagnostics lists + /// their servers, and forcing one On loads its plugin (PluginManager.RequestServerPluginLoad). + /// + public List<(string Path, RynthPluginManifest Manifest)> SkippedServerPlugins { get; } = new(); } /// /// Reads the manifests of and resolves them against /// . gives a DLL's version resource /// (for dependency versions of plugins whose manifest has none); null skips it. + /// (the client's -h host, "" when unknown) picks which server + /// plugins load (); + /// (engine.json LoadAllServerPlugins) turns that off. /// - public static LoadPlan Plan(IReadOnlyList paths, uint engineApi, Func? fileVersion = null) + public static LoadPlan Plan(IReadOnlyList paths, uint engineApi, Func? fileVersion = null, + string? connectHost = null, bool loadAllServerPlugins = false) { var plan = new LoadPlan(); var candidates = new List(paths.Count); @@ -71,6 +82,16 @@ internal static class PluginManifestGate candidates.Add(new PluginCandidate(path, manifest, fv)); } + HashSet skip = SelectServerPlugins(candidates, connectHost, loadAllServerPlugins, plan.Log); + if (skip.Count > 0) + { + foreach (PluginCandidate c in candidates) + if (skip.Contains(c.Key) && c.Manifest?.Server != null) + plan.SkippedServerPlugins.Add((c.Key, c.Manifest)); + candidates.RemoveAll(c => skip.Contains(c.Key)); + plan.SkippedForServer.AddRange(skip); + } + PluginResolution res = PluginManifestResolver.Resolve(candidates, engineApi); foreach (PluginCandidate c in res.Order) plan.Load.Add((c.Key, c.Manifest)); @@ -82,6 +103,51 @@ internal static class PluginManifestGate return plan; } + /// + /// The server plugins to leave out (their paths). Fail-open: a server plugin is left out only + /// when is known and another installed server plugin claims it, + /// so a server that moved to a new host still gets its plugin (all of them load, each shows + /// only on its own server). Nothing is left out when is set. + /// + internal static HashSet SelectServerPlugins(IReadOnlyList candidates, string? connectHost, + bool loadAll, List log) + { + var skip = new HashSet(StringComparer.OrdinalIgnoreCase); + var servers = new List(); + foreach (PluginCandidate c in candidates) + if (c.Manifest?.Server != null) servers.Add(c); + if (servers.Count == 0) return skip; + if (loadAll) + { + log.Add($"{servers.Count} server plugin(s): all load (engine.json LoadAllServerPlugins)."); + return skip; + } + string host = (connectHost ?? "").Trim(); + if (host.Length == 0) + { + log.Add($"{servers.Count} server plugin(s): no connect host on the command line, so all load (each shows only on its own server)."); + return skip; + } + + var claimants = new List(); + foreach (PluginCandidate c in servers) + if (c.Manifest!.Server!.MatchesHost(host, out string hit)) + claimants.Add($"{c.Manifest.Name} ({c.Manifest.Server.Id}, \"{hit}\")"); + if (claimants.Count == 0) + { + log.Add($"{servers.Count} server plugin(s): none lists host {host}, so all load (each shows only on its own server)."); + return skip; + } + + foreach (PluginCandidate c in servers) + { + if (c.Manifest!.Server!.MatchesHost(host, out _)) continue; + skip.Add(c.Key); + log.Add($"{Path.GetFileName(c.Key)}: not loaded - it is for {c.Manifest.Server.Name}, and host {host} is {string.Join(", ", claimants)}."); + } + return skip; + } + /// /// Null when every plugin requires has started; otherwise why not. /// answers by plugin name: true started, false loaded but not @@ -114,6 +180,7 @@ internal static class PluginManifestGate parts.Add(d.Name + (d.MinVersion.Length > 0 ? " " + d.MinVersion + "+" : "") + (d.Optional ? " (optional)" : "")); s += ", needs " + string.Join(", ", parts); } + if (m.Server != null) s += $", server {m.Server.Id}"; return s; } } diff --git a/src/RynthCore.Engine/RynthLog.cs b/src/RynthCore.Engine/RynthLog.cs index a6fd341..af84ef8 100644 --- a/src/RynthCore.Engine/RynthLog.cs +++ b/src/RynthCore.Engine/RynthLog.cs @@ -42,6 +42,17 @@ internal static class RynthLog /// Same as . internal static void Warning(string msg) => Warn(msg); + /// + /// INFO line for a rare state change a support log must show (the server verdicts): written + /// whenever the global LoggingLevel allows Info, whatever the categories' emit levels say. + /// A category set to Trace under a global Info level would otherwise drop it. + /// + internal static void Milestone(string msg) + { + if (EntryPoint.ShouldLog(EntryPoint.EngineLogLevel.Info)) + EntryPoint.LogTagged("engine", msg, "INF"); + } + // Most recent WRN/ERR text + when, surfaced via the GetEngineStatusJson host bridge so a stuck box // can be diagnosed remotely without reading the PC log. Recorded even when the line is filtered. internal static volatile string? LastIssue; diff --git a/src/RynthCore.Engine/UI/Data/DamageData.cs b/src/RynthCore.Engine/UI/Data/DamageData.cs index de9a9c4..e6d839f 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; } // a name rule's own choices, kept + if (from != null) { clone.OffhandId = from.OffhandId; clone.PetDamage = from.PetDamage; clone.AttackPower = from.AttackPower; } // 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 and pet are - /// left on "follow Default" (0 / PAuto) 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 and attack + /// power are left on "follow Default" (0 / PAuto / Default) 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", + ExVuln = s.ExVuln, PetDamage = "PAuto", AttackPower = "Default", 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, @@ -790,6 +790,10 @@ 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.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/SettingsData.cs b/src/RynthCore.Engine/UI/Data/SettingsData.cs index 7135154..3a98cf6 100644 --- a/src/RynthCore.Engine/UI/Data/SettingsData.cs +++ b/src/RynthCore.Engine/UI/Data/SettingsData.cs @@ -117,6 +117,17 @@ internal sealed class RynthAiSettings public bool UseNativeAttack { get; set; } = true; public bool SummonPets { get; set; } public int PetMinMonsters { get; set; } = 1; + // RynthAi 0.5.47 (2026-10-12): Variable attack power and the environment-impact throttle. + // Nullable in RynthAi's payload: an older RynthAi omits them and these defaults show. + public int VariablePowerMin { get; set; } = 50; + public int VariablePowerMax { get; set; } = 100; + public int MissileEnvironmentResponse { get; set; } + public int MagicEnvironmentResponse { get; set; } + public int EnvironmentImpactLimit { get; set; } = 2; + public int EnvironmentImpactWindowSec { get; set; } = 20; + public int EnvironmentApproachMeters { get; set; } = 6; + public int EnvironmentMinDistance { get; set; } = 3; + public int EnvironmentSkipSec { get; set; } = 30; // Spell Combat public int SpellCastIntervalMs { get; set; } = 400; public int AttackSpellIntervalMs { get; set; } = 1500; @@ -322,7 +333,13 @@ internal static unsafe class SettingsCommands internal enum SettingKind { Bool, Int, Float, Double, Combo, Section, Spacer, Note, CraftingStatus, Button, TraceCategories, Text, Status, /// The user hotkeys editor (ImGui/Panels/HotkeysSettingsUi.cs; stored by the engine, not RynthAi). - Hotkeys } + Hotkeys, + /// + /// The server picker and the server list (Diagnostics): which server this character counts + /// as, from the servers the engine and the loaded plugins know (UI/Sections/ServerSelection.cs). + /// Stored by the engine per character (server_force.txt), not RynthAi. + /// + ServerPick } /// /// Reads and edits ("Name=Level,..."). The category @@ -442,6 +459,8 @@ 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" }; 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" }; @@ -804,6 +823,30 @@ 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)"), + Int("Variable Min %", s => s.VariablePowerMin, (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%)."), + Int("Variable Max %", s => s.VariablePowerMax, (s, v) => s.VariablePowerMax = v, 0, 100, 5), + Spacer(), + Section("Hitting the Environment"), + Combo("Missile Response", EnvironmentResponses, s => s.MissileEnvironmentResponse, (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. Magic: Spell Combat tab."), + Int("Hits to trip", s => s.EnvironmentImpactLimit, (s, v) => s.EnvironmentImpactLimit = v, 1, 10, 1, + "Environment hits on one target, within the window, before combat reacts (missiles and magic)."), + Int("Window (s)", s => s.EnvironmentImpactWindowSec, (s, v) => s.EnvironmentImpactWindowSec = v, 5, 120, 5), + Int("Move closer by (m)", s => s.EnvironmentApproachMeters, (s, v) => s.EnvironmentApproachMeters = v, 1, 30, 1), + Int("Closest (m)", s => s.EnvironmentMinDistance, (s, v) => s.EnvironmentMinDistance = v, 1, 30, 1, + "Never moves nearer than this. Already this close, a new target is picked instead."), + Int("Skip target (s)", s => s.EnvironmentSkipSec, (s, v) => s.EnvironmentSkipSec = v, 5, 300, 5), + Spacer(), 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(), @@ -835,6 +878,16 @@ 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"), + Combo("Magic Response", EnvironmentResponses, s => s.MagicEnvironmentResponse, (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.\n" + + "Hits to trip, the window, distances and the skip time: Melee Combat tab."), + Spacer(), Section("Spell Difficulty (Min Buffed Skill)"), Tiers( new Func[] { s => s.MinSkillLevelTier1, s => s.MinSkillLevelTier2, s => s.MinSkillLevelTier3, s => s.MinSkillLevelTier4, @@ -1081,6 +1134,13 @@ internal static class SettingsSchema "Ticked categories write their trace lines to Trace\\_.txt (/ra trace on|off)."), Note("+log = the category is at Info: its trace lines also go to the normal log. The launcher's Logging page sets Off, Trace or Info."), Note("Exceptions always go to exceptions_.txt with full stack traces (throttled). Settings here are for this PC, not the profile."), + Spacer(), + Section("Server"), + new SettingRow(SettingKind.ServerPick, "Server", + "Which server this character counts as. Auto detects it (the connect host, the world name the server announces, RynthILT).\n" + + "Picking a server forces it on and every other server off, for this character; every plugin follows at once.\n" + + "Also: /rc server pick |auto, and /rc server for the list."), + Note("The list is every server the engine knows: the built-in ones and those declared by the loaded server plugins. \"Settings from\" is the plugin the others ask for that server's settings."), }), }; } diff --git a/src/RynthCore.Engine/UI/Panels/MonstersPanel.cs b/src/RynthCore.Engine/UI/Panels/MonstersPanel.cs index d7435ce..c9238b5 100644 --- a/src/RynthCore.Engine/UI/Panels/MonstersPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/MonstersPanel.cs @@ -127,6 +127,10 @@ 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"; public bool GetToggle(string field) => field switch { @@ -1016,6 +1020,7 @@ 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.ExVuln != y.ExVuln || x.PetDamage != y.PetDamage + || (x.AttackPower ?? "") != (y.AttackPower ?? "") || 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/RynthAiPanel.cs b/src/RynthCore.Engine/UI/Panels/RynthAiPanel.cs index eb0ea9d..310943c 100644 --- a/src/RynthCore.Engine/UI/Panels/RynthAiPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/RynthAiPanel.cs @@ -598,19 +598,13 @@ internal static partial class RynthAiPanel ClosePicker(); RynthAiCommands.ApplyRemoteCommand("hub", "show"); }); - ToolTip.SetTip(charBtn, "Open the Mini Remote (/ra hub show)."); - - // Hub: the Mini Remote and the Inventory HUDs setup are ImGui windows inside RynthAi. - var hudBtn = AddLauncher(launcherGrid, 2, 1, "Hub", "▣", - onClick: () => - { - ClosePicker(); - RynthAiCommands.ApplyRemoteCommand("remote", "toggle"); - }); - ToolTip.SetTip(hudBtn, "Left-click: show/hide the Mini Remote (/ra remote). Right-click: Inventory HUDs setup (/ra huds)."); - hudBtn.PointerPressed += (_, e) => + ToolTip.SetTip(charBtn, "Left-click: open the Mini Remote (/ra hub show). Right-click: Inventory HUDs setup (/ra huds)."); + // The separate Hub launcher (the same Mini Remote again) was removed 2026-10-13, as on the + // ImGui dashboard; its right-click, the Inventory HUDs setup (an ImGui window inside + // RynthAi), moved to Char. + charBtn.PointerPressed += (_, e) => { - if (e.GetCurrentPoint(hudBtn).Properties.IsRightButtonPressed) + if (e.GetCurrentPoint(charBtn).Properties.IsRightButtonPressed) { e.Handled = true; ClosePicker(); diff --git a/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs b/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs index e5abf9d..3303fa4 100644 --- a/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs +++ b/src/RynthCore.Engine/UI/Panels/SettingsPanel.cs @@ -337,6 +337,20 @@ internal static class SettingsPanel return ButtonRow(row.Label, row.ButtonText ?? row.Label, () => row.Click?.Invoke(), row.Tooltip); case SettingKind.TraceCategories: return TraceCategoriesRow(state, row); + case SettingKind.ServerPick: + { + // The picker itself is the ImGui face's; here, what is picked and how to change it. + var snap = UI.Sections.SectionRegistry.Current; + string pick = UI.Sections.ServerSelection.CurrentPick(snap.Servers) ?? "mixed"; + var active = UI.Sections.ServerSelection.ActiveServer(snap.Servers); + return new TextBlock + { + Text = $"Server: {(active == null ? "none active" : active.Name + " (" + active.Id + ")")}, pick {pick}. " + + "Change it with /rc server pick |auto (the ImGui panel has a picker).", + Foreground = ColTeal, FontSize = 11, + TextWrapping = Avalonia.Media.TextWrapping.Wrap, Margin = new Thickness(0, 2, 0, 2), + }; + } case SettingKind.Text: return TextRow(row.Label, row.GetText?.Invoke(d) ?? string.Empty, row.Hint, v => { diff --git a/src/RynthCore.Engine/UI/ScriptWindows/ScriptWindowRegistry.cs b/src/RynthCore.Engine/UI/ScriptWindows/ScriptWindowRegistry.cs index 26a3015..c91be84 100644 --- a/src/RynthCore.Engine/UI/ScriptWindows/ScriptWindowRegistry.cs +++ b/src/RynthCore.Engine/UI/ScriptWindows/ScriptWindowRegistry.cs @@ -790,6 +790,38 @@ internal static class ScriptWindowRegistry else ImGuiPanelHost.Close(w.PanelKey); } + /// + /// Opens or closes a plugin's script window by its key ("RynthOracle/Oracle"), as the bar + /// does (the owner gets a Visibility event, reason 2). False when no live window has the + /// key (the plugin isn't loaded or hasn't submitted it yet). Any thread. + /// + public static bool PlayerSetVisible(string key, bool visible) + { + ScriptWindow? w = Find(key); + if (w == null) return false; + PlayerSetVisible(w, visible); + return true; + } + + /// Whether a plugin has submitted a script window with this key (and it is still live). Any thread. + public static bool Has(string key) => Find(key) != null; + + /// Whether a plugin's script window (by key) is open; false when there is none. Any thread. + public static bool IsOpen(string key) + { + ScriptWindow? w = Find(key); + return w != null && ImGuiPanelHost.IsOpen(w.PanelKey); + } + + /// The live window with a plugin key, or null. + private static ScriptWindow? Find(string key) + { + if (string.IsNullOrWhiteSpace(key)) return null; + ScriptWindow? w; + lock (Sync) ByPanelKey.TryGetValue(PanelKeyPrefix + SanitizeKey(key), out w); + return w == null || w.Removed ? null : w; + } + /// /// SetNextWindowSize / SetNextWindowPos (§3.2): a request is passed to the panel host /// when its value changed since the last one applied, when the window was re-recorded diff --git a/src/RynthCore.Engine/UI/Sections/NotLoadedServers.cs b/src/RynthCore.Engine/UI/Sections/NotLoadedServers.cs new file mode 100644 index 0000000..a42f706 --- /dev/null +++ b/src/RynthCore.Engine/UI/Sections/NotLoadedServers.cs @@ -0,0 +1,48 @@ +// ============================================================================ +// RynthCore.Engine - UI/Sections/NotLoadedServers.cs +// Servers whose plugin is installed but not loaded: the connect host belongs to +// another server, so PluginManifestGate left the plugin out. They still go in +// the server list (Options > Diagnostics, GetServerStateJson), so a server can +// be picked there; a server forced On gets its plugin loaded +// (PluginManager.RequestServerPluginLoad). +// +// Pure (no AC, no engine state, no I/O): tools/SectionsTests compiles it. +// ============================================================================ + +using System; +using System.Collections.Generic; + +namespace RynthCore.Engine.UI.Sections; + +/// An installed server plugin that is not loaded: its server and the plugin's name. +internal readonly record struct NotLoadedServer(string Id, string Name, string Plugin); + +internal static class NotLoadedServers +{ + /// + /// Adds each not-loaded server whose id isn't in yet (a loaded plugin's + /// declaration or a built-in server wins). Not detected (the host is another server's); active + /// only when this character forces it On. + /// + public static void Append(List list, IReadOnlyList notLoaded, Func force) + { + foreach (NotLoadedServer s in notLoaded) + { + if (s.Id.Length == 0 || list.Exists(x => x.Id.Equals(s.Id, StringComparison.OrdinalIgnoreCase))) continue; + ServerForce f = force(s.Id); + string reason = f == ServerForce.On + ? $"forced On: loading {s.Plugin}" + : $"{s.Plugin} is installed but not loaded (this host is another server's); pick it to load it"; + list.Add(new ServerState(s.Id, s.Name, ServerForceText.Apply(f, false), false, f, false, reason)); + } + } + + /// The not-loaded servers this character forces On: their plugins should load now. + public static List ForcedOn(IReadOnlyList notLoaded, Func force) + { + var ids = new List(); + foreach (NotLoadedServer s in notLoaded) + if (s.Id.Length > 0 && force(s.Id) == ServerForce.On) ids.Add(s.Id); + return ids; + } +} diff --git a/src/RynthCore.Engine/UI/Sections/SectionCatalog.cs b/src/RynthCore.Engine/UI/Sections/SectionCatalog.cs new file mode 100644 index 0000000..236829a --- /dev/null +++ b/src/RynthCore.Engine/UI/Sections/SectionCatalog.cs @@ -0,0 +1,226 @@ +// ============================================================================ +// RynthCore.Engine - UI/Sections/SectionCatalog.cs +// The Mini Remote's sections: the twelve core ones every world has, and what +// installed plugins add, laid out for the servers that are active now. +// +// Pure (no AC, no ImGui, no engine state): tools/SectionsTests compiles it. +// SectionRegistry.cs feeds it the plugins' manifests, the engine panels that +// exist and the server verdicts; MiniRemoteFace draws the result. +// +// A section's body, top to bottom: +// panes what fills it: the engine's core panels for it (embedded whole), +// the Session Stats overview (dropped once a plugin's universal +// primary surface fills that section, e.g. RynthAi's session +// stats), and plugins' primary surfaces. More than one pane = a +// row of sub-tabs. +// groups "Server: " for each active server with items here, then +// "Plugins" for items every world gets: inline plugin surfaces +// (options and configuration) and command buttons. +// Core sections always show (with a note when nothing fills them); a plugin's +// own section shows only while something in it applies to this world. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Linq; +using RynthCore.Engine.Compatibility; + +namespace RynthCore.Engine.UI.Sections; + +/// A core section: always on the rail. +internal sealed record CoreSection(string Id, string Label, string[] Panels, bool Overview = false); + +/// A server and whether it is active for this character now. +internal sealed record ServerState(string Id, string Name, bool Active, bool Detected, ServerForce Force, bool BuiltIn, string Reason); + +internal enum SectionPaneKind +{ + /// The Session Stats section's engine overview (XP / luminance this session), when no plugin fills it. + Overview, + /// An engine panel embedded whole. + CorePanel, + /// A plugin surface (RynthPluginRenderEmbed). + Surface, +} + +/// One sub-tab of a section's body. +internal sealed record SectionPane(SectionPaneKind Kind, string Title, string Panel, SectionContribution? Contribution); + +/// A titled group of a section's items: one active server, or "Plugins" (every world). +internal sealed record SectionGroup(string Title, ServerState? Server, SectionContribution[] Items); + +/// One section as it should be drawn now. +internal sealed record SectionView(string Id, string Label, bool Core, int Order, SectionPane[] Panes, SectionGroup[] Groups) +{ + public bool HasContent => Panes.Length > 0 || Groups.Length > 0; +} + +internal static class SectionCatalog +{ + /// The rail entry for the remote itself (RynthAi's remote, or the engine's slot grid). + public const string RemoteId = "remote"; + + /// The "char" section's label: the session's XP, luminance and kills. + public const string SessionStatsLabel = "Session Stats"; + + /// + /// The core sections, in rail order, with the engine panels that fill each (the first + /// that exists is the default sub-tab). Sections without panels are filled by plugins. + /// + public static readonly CoreSection[] Core = + { + // Session Stats (was "Char" until 2026.10.5.54; the id stays "char" so saved rail picks, + // "/rc miniremote section char" and plugin manifests keep working). Character details + // live in RynthOracle's Character tab now, server picks in Options > Diagnostics. + new("char", SessionStatsLabel, Array.Empty(), Overview: true), + new("map", "Map", new[] { "Radar", "Dungeon Map" }), + new("skills", "Skills", new[] { "Skills" }), + new("combat", "Combat", new[] { "Damage", "Monsters" }), + new("nav", "Nav", new[] { "Nav", "RynthNav" }), + new("inventory", "Inventory", new[] { "Inventory", "Item Count", "Items" }), + new("crafting", "Crafting", Array.Empty()), + new("spells", "Spells", Array.Empty()), + new("chat", "Chat", new[] { "Chat" }), + new("friends", "Friends", Array.Empty()), + new("fellowship", "Fellowship", Array.Empty()), + new("pets", "Pets", Array.Empty()), + }; + + /// Plugin sections sort after the core ones unless they ask for a smaller order. + private const int CoreOrderStep = 100; + + public static CoreSection? FindCore(string id) + { + foreach (CoreSection c in Core) + if (c.Id.Equals(id, StringComparison.OrdinalIgnoreCase)) return c; + return null; + } + + /// + /// A plugin-declared server's own detection: its launch host or announced world name + /// matches one of its lists (the same matching as Infinite Leaftide's). + /// + public static bool DetectDeclared(SectionServerDecl server, string? host, string? world, out string reason) + { + if (IltDetect.HostMatches(host, server.Hosts, out string hostHit)) + { + reason = $"host matches \"{hostHit}\""; + return true; + } + if (IltDetect.WorldNameMatches(world, server.WorldNames, out string worldHit)) + { + reason = $"world name matches \"{worldHit}\""; + return true; + } + reason = server.Hosts.Length + server.WorldNames.Length == 0 ? "no host or world-name list" : "no host or world name matches"; + return false; + } + + /// + /// Every section to show now, in rail order (the remote entry is not included). + /// says whether an engine panel is registered. + /// + public static List Build(IReadOnlyList manifests, Func panelExists, + IReadOnlyList servers) + { + var activeServers = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (ServerState s in servers) + if (s.Active) activeServers[s.Id] = s; + + // Contributions that apply to this world, by section. + var bySection = new Dictionary>(StringComparer.OrdinalIgnoreCase); + foreach (SectionManifest m in manifests) + foreach (SectionContribution c in m.Contributions) + { + if (!c.IsUniversal && !activeServers.ContainsKey(c.Server)) continue; + if (!bySection.TryGetValue(c.Section, out var list)) bySection[c.Section] = list = new List(); + list.Add(c); + } + + var views = new List(); + for (int i = 0; i < Core.Length; i++) + { + CoreSection core = Core[i]; + bySection.TryGetValue(core.Id, out var items); + views.Add(BuildOne(core.Id, core.Label, true, i * CoreOrderStep, core, items, panelExists, servers)); + } + + // Plugin sections: the first declaration of an id wins; never one of the core ids. + var declared = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (SectionManifest m in manifests) + foreach (SectionDecl d in m.Sections) + if (FindCore(d.Id) == null && !d.Id.Equals(RemoteId, StringComparison.OrdinalIgnoreCase)) + declared.TryAdd(d.Id, d); + foreach (SectionDecl d in declared.Values) + { + if (!bySection.TryGetValue(d.Id, out var items)) continue; // nothing for this world + SectionView v = BuildOne(d.Id, d.Label, false, d.Order, null, items, panelExists, servers); + if (v.HasContent) views.Add(v); + } + // Stable: equal orders keep core before plugin sections, then plugin sections by id. + return views.OrderBy(v => v.Order).ThenBy(v => v.Core ? 0 : 1).ThenBy(v => v.Id, StringComparer.Ordinal).ToList(); + } + + private static SectionView BuildOne(string id, string label, bool isCore, int order, CoreSection? core, + List? items, Func panelExists, + IReadOnlyList servers) + { + var panes = new List(); + if (core != null) + { + if (core.Overview) panes.Add(new SectionPane(SectionPaneKind.Overview, label, string.Empty, null)); + foreach (string panel in core.Panels) + if (SafeExists(panelExists, panel)) panes.Add(new SectionPane(SectionPaneKind.CorePanel, panel, panel, null)); + } + + var universal = new List(); + var perServer = new Dictionary>(StringComparer.OrdinalIgnoreCase); + if (items != null) + { + items.Sort(CompareItems); + foreach (SectionContribution c in items) + { + if (c.Primary && c.IsSurface) + { + panes.Add(new SectionPane(SectionPaneKind.Surface, c.Label, string.Empty, c)); + continue; + } + if (c.IsUniversal) universal.Add(c); + else + { + if (!perServer.TryGetValue(c.Server, out var list)) perServer[c.Server] = list = new List(); + list.Add(c); + } + } + } + + // One session on screen: the engine's own Session Stats overview is a stand-in, dropped + // when a plugin fills the section with an every-world view of its own (RynthAi's session + // stats, which RynthTracker, RynthOracle and RynthILT follow too). + if (core is { Overview: true } && panes.Exists(p => p.Kind == SectionPaneKind.Surface && p.Contribution!.IsUniversal)) + panes.RemoveAll(p => p.Kind == SectionPaneKind.Overview); + + var groups = new List(); + foreach (ServerState s in servers) // the servers' own order: built-in first + if (s.Active && perServer.TryGetValue(s.Id, out var list)) + groups.Add(new SectionGroup("Server: " + s.Name, s, list.ToArray())); + if (universal.Count > 0) groups.Add(new SectionGroup("Plugins", null, universal.ToArray())); + + return new SectionView(id, label, isCore, order, panes.ToArray(), groups.ToArray()); + } + + /// Order, then server-agnostic first, then label: the same list always draws the same way. + private static int CompareItems(SectionContribution a, SectionContribution b) + { + if (a.Order != b.Order) return a.Order.CompareTo(b.Order); + if (a.IsUniversal != b.IsUniversal) return a.IsUniversal ? -1 : 1; + int byLabel = string.Compare(a.Label, b.Label, StringComparison.OrdinalIgnoreCase); + return byLabel != 0 ? byLabel : string.CompareOrdinal(a.Plugin, b.Plugin); + } + + private static bool SafeExists(Func panelExists, string panel) + { + try { return panelExists(panel); } + catch { return false; } + } +} diff --git a/src/RynthCore.Engine/UI/Sections/SectionManifest.cs b/src/RynthCore.Engine/UI/Sections/SectionManifest.cs new file mode 100644 index 0000000..b6f9379 --- /dev/null +++ b/src/RynthCore.Engine/UI/Sections/SectionManifest.cs @@ -0,0 +1,253 @@ +// ============================================================================ +// RynthCore.Engine - UI/Sections/SectionManifest.cs +// What a plugin adds to the Mini Remote's sections, read from its optional +// export const char* RynthPluginGetSectionsJson(void) (UTF-8 JSON, the same +// parameterless JSON-getter convention as RynthPluginGetSnapshotJson). +// +// Pure (no AC, no engine state): tools/SectionsTests compiles this file as is. +// +// Schema (version 1; unknown keys are ignored, so later versions only add): +// { +// "version": 1, +// "servers": [ { "id": "ilt", "name": "Infinite Leaftide", +// "worldNames": ["*Leaftide*"], "hosts": ["infiniteleaftide.online"] } ], +// "sections": [ { "id": "quests", "label": "Quests", "order": 150 } ], +// "contributions": [ +// { "section": "pets", "server": "", "label": "Pets", "surface": "section:pets", +// "primary": true, "width": 560, "height": 580 }, +// { "section": "skills", "server": "ilt", "label": "Progression", +// "command": "/rc progression", "tooltip": "...", "enabled": true, "note": "" } ] +// } +// servers servers the plugin knows. A built-in id (ilt, aelrynth) keeps the +// engine's own detection; a new id is detected from its lists. +// sections extra sections (beyond the core twelve) the plugin adds. +// contributions what the plugin puts in a section: "server" "" = every world, else +// only while that server is active (detected or forced). "surface" +// = drawn inline through RynthPluginRenderEmbed; "command" = a button +// that runs it. "primary" = the section's main view when the engine +// has no core panel for it (Pets, Crafting, Spells, ...). +// +// Everything from a plugin is checked here: ids are short lower-case words, +// text is capped, a command must be a single "/..." chat command, and the lists +// are capped, so a damaged or hostile manifest can't flood the UI. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; + +namespace RynthCore.Engine.UI.Sections; + +/// A server a plugin declares (detected by the engine from its lists unless the id is built in). +internal sealed record SectionServerDecl(string Id, string Name, string[] WorldNames, string[] Hosts); + +/// An extra section a plugin adds. +internal sealed record SectionDecl(string Id, string Label, int Order); + +/// One thing a plugin puts in a section. +internal sealed record SectionContribution( + string Plugin, + string Section, + string Server, + string Label, + string Surface, + string Command, + string Tooltip, + bool Primary, + bool Enabled, + string Note, + float Width, + float Height, + int Order) +{ + /// Drawn inline (a plugin surface), not a button. + public bool IsSurface => Surface.Length > 0; + /// For every world, not one server. + public bool IsUniversal => Server.Length == 0; +} + +/// One plugin's parsed manifest. +internal sealed record SectionManifest( + string Plugin, + SectionServerDecl[] Servers, + SectionDecl[] Sections, + SectionContribution[] Contributions) +{ + public static readonly SectionManifest Empty = + new("", Array.Empty(), Array.Empty(), Array.Empty()); +} + +internal static class SectionManifestParser +{ + public const int SupportedVersion = 1; + public const int MaxServers = 16; + public const int MaxSections = 32; + public const int MaxContributions = 128; + public const int MaxPatterns = 32; + public const int MaxIdLength = 32; + public const int MaxLabelLength = 48; + public const int MaxTextLength = 300; + public const int MaxCommandLength = 200; + public const int MaxSurfaceLength = 64; + public const float MaxSurfaceSize = 4096f; + /// Largest manifest read at all (a manifest is a few KB). + public const int MaxJsonLength = 256 * 1024; + + /// + /// Parses from plugin . Never throws: + /// a malformed document gives and the reason in + /// ; a bad entry is skipped. + /// + public static SectionManifest Parse(string plugin, string? json, out string error) + { + error = string.Empty; + if (string.IsNullOrWhiteSpace(json)) { error = "empty"; return SectionManifest.Empty with { Plugin = plugin }; } + if (json.Length > MaxJsonLength) { error = $"too large ({json.Length} chars)"; return SectionManifest.Empty with { Plugin = plugin }; } + try + { + using JsonDocument doc = JsonDocument.Parse(json, new JsonDocumentOptions { MaxDepth = 16 }); + JsonElement root = doc.RootElement; + if (root.ValueKind != JsonValueKind.Object) { error = "not a JSON object"; return SectionManifest.Empty with { Plugin = plugin }; } + int version = root.TryGetProperty("version", out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out int n) ? n : 1; + if (version < 1) { error = $"version {version}"; return SectionManifest.Empty with { Plugin = plugin }; } + + var servers = new List(); + foreach (JsonElement e in Array(root, "servers")) + { + if (servers.Count >= MaxServers) break; + string id = Id(Str(e, "id")); + if (id.Length == 0 || servers.Exists(s => s.Id == id)) continue; + string name = Text(Str(e, "name"), MaxLabelLength); + servers.Add(new SectionServerDecl(id, name.Length > 0 ? name : id, Patterns(e, "worldNames"), Patterns(e, "hosts"))); + } + + var sections = new List(); + foreach (JsonElement e in Array(root, "sections")) + { + if (sections.Count >= MaxSections) break; + string id = Id(Str(e, "id")); + string label = Text(Str(e, "label"), MaxLabelLength); + if (id.Length == 0 || label.Length == 0 || sections.Exists(s => s.Id == id)) continue; + sections.Add(new SectionDecl(id, label, Int(e, "order", 1000))); + } + + var contributions = new List(); + foreach (JsonElement e in Array(root, "contributions")) + { + if (contributions.Count >= MaxContributions) break; + string section = Id(Str(e, "section")); + string label = Text(Str(e, "label"), MaxLabelLength); + if (section.Length == 0 || label.Length == 0) continue; + string rawServer = Str(e, "server"); + string server = rawServer.Length == 0 ? string.Empty : Id(rawServer); + if (rawServer.Length > 0 && server.Length == 0) continue; // a server id that isn't one + string surface = Surface(Str(e, "surface")); + string command = Command(Str(e, "command")); + if (surface.Length == 0 && command.Length == 0) continue; // nothing to draw or run + contributions.Add(new SectionContribution( + plugin, section, server, label, surface, command, + Text(Str(e, "tooltip"), MaxTextLength, multiline: true), + Bool(e, "primary", false), + Bool(e, "enabled", true), + Text(Str(e, "note"), MaxTextLength, multiline: true), + Size(e, "width"), Size(e, "height"), + Int(e, "order", 1000))); + } + + return new SectionManifest(plugin, servers.ToArray(), sections.ToArray(), contributions.ToArray()); + } + catch (JsonException ex) + { + error = "bad JSON: " + ex.Message; + return SectionManifest.Empty with { Plugin = plugin }; + } + } + + // ── Field rules ───────────────────────────────────────────────────── + + /// A lower-case id of letters, digits, '-' and '_' (at most MaxIdLength), else "". + public static string Id(string? text) + { + string t = (text ?? string.Empty).Trim().ToLowerInvariant(); + if (t.Length == 0 || t.Length > MaxIdLength) return string.Empty; + foreach (char c in t) + if (!(c is >= 'a' and <= 'z' or >= '0' and <= '9' or '-' or '_')) return string.Empty; + return t; + } + + /// + /// Display text: control characters become spaces (line breaks too, unless + /// : tooltips and notes), trimmed, capped. + /// + public static string Text(string? text, int max, bool multiline = false) + { + if (string.IsNullOrEmpty(text)) return string.Empty; + var chars = text.ToCharArray(); + for (int i = 0; i < chars.Length; i++) + if (char.IsControl(chars[i]) && !(multiline && chars[i] == '\n')) chars[i] = ' '; + string t = new string(chars).Trim(); + return t.Length <= max ? t : t[..max]; + } + + /// A plugin surface name: letters, digits and ":_.-", not the engine's ":popout" suffix. + public static string Surface(string? text) + { + string t = (text ?? string.Empty).Trim(); + if (t.Length == 0 || t.Length > MaxSurfaceLength || t.EndsWith(":popout", StringComparison.OrdinalIgnoreCase)) return string.Empty; + foreach (char c in t) + if (!(char.IsAsciiLetterOrDigit(c) || c is ':' or '_' or '.' or '-')) return string.Empty; + return t; + } + + /// One chat command ("/rc progression"): starts with '/', one line, capped; else "". + public static string Command(string? text) + { + string t = (text ?? string.Empty).Trim(); + if (t.Length < 2 || t.Length > MaxCommandLength || t[0] != '/') return string.Empty; + foreach (char c in t) + if (char.IsControl(c)) return string.Empty; + return t; + } + + private static IEnumerable Array(JsonElement root, string name) + { + if (!root.TryGetProperty(name, out JsonElement a) || a.ValueKind != JsonValueKind.Array) yield break; + foreach (JsonElement e in a.EnumerateArray()) + if (e.ValueKind == JsonValueKind.Object) yield return e; + } + + private static string Str(JsonElement e, string name) + => e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? string.Empty : string.Empty; + + private static bool Bool(JsonElement e, string name, bool fallback) + => e.TryGetProperty(name, out JsonElement v) ? v.ValueKind switch + { + JsonValueKind.True => true, + JsonValueKind.False => false, + _ => fallback, + } : fallback; + + private static int Int(JsonElement e, string name, int fallback) + => e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetInt32(out int n) + ? Math.Clamp(n, -100_000, 100_000) : fallback; + + /// A surface's preferred width or height in pixels (0 = not given). + private static float Size(JsonElement e, string name) + => e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number && v.TryGetDouble(out double d) + && d > 0 && !double.IsNaN(d) ? (float)Math.Min(d, MaxSurfaceSize) : 0f; + + private static string[] Patterns(JsonElement e, string name) + { + var list = new List(); + if (!e.TryGetProperty(name, out JsonElement a) || a.ValueKind != JsonValueKind.Array) return list.ToArray(); + foreach (JsonElement p in a.EnumerateArray()) + { + if (list.Count >= MaxPatterns) break; + if (p.ValueKind != JsonValueKind.String) continue; + string t = Text(p.GetString(), MaxLabelLength); + if (t.Length > 0 && !list.Contains(t, StringComparer.OrdinalIgnoreCase)) list.Add(t); + } + return list.ToArray(); + } +} diff --git a/src/RynthCore.Engine/UI/Sections/SectionRegistry.cs b/src/RynthCore.Engine/UI/Sections/SectionRegistry.cs new file mode 100644 index 0000000..fe547b2 --- /dev/null +++ b/src/RynthCore.Engine/UI/Sections/SectionRegistry.cs @@ -0,0 +1,277 @@ +// ============================================================================ +// RynthCore.Engine - UI/Sections/SectionRegistry.cs +// The live state behind the Mini Remote's sections: which servers are active +// (one world check for the engine and every plugin), what the installed +// plugins add (their RynthPluginGetSectionsJson manifests), and the section +// layout SectionCatalog builds from those. +// +// Servers: +// built in Infinite Leaftide (IltInfo) and Aelrynth (ServerInfo): the engine's +// own detection, with the per-character override (ServerForceStore). +// declared any other id a plugin's manifest names: detected from its host / +// world-name lists, with the same per-character override. +// not loaded installed server plugins the connect host left out (NotLoadedServers): +// listed so Options > Diagnostics can pick them; forced On, the plugin loads. +// RynthAi follows these verdicts (ServerMenus pushes them), so the engine and +// RynthAi can't disagree about which world this is. +// +// The engine's own contributions (Bounties, Guardian, Progression) are a +// manifest like a plugin's, added at init by which plugins are installed. +// +// Threads: Tick runs on AC's render thread (ImGuiController frame); readers +// on any thread get the last published snapshot (volatile, immutable). +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Threading; +using RynthCore.Engine.Compatibility; + +namespace RynthCore.Engine.UI.Sections; + +internal static class SectionRegistry +{ + /// The engine's own entry in the manifests (its contributions' "plugin"). + public const string EnginePlugin = "RynthCore"; + + /// How often the plugins' manifests are read again (they change with server features). + private const long ManifestPollMs = 2_000; + /// How often the server verdicts and the layout are rebuilt. + private const long RebuildMs = 1_000; + + private sealed record BuiltInServer(string Id, string Name, Func Active, Func<(bool Detected, string Reason)> Detect); + + /// Everything the UI reads, published together. + internal sealed record Snapshot( + IReadOnlyList Servers, + IReadOnlyList Sections, + IReadOnlyList Manifests, + int Revision) + { + public static readonly Snapshot Empty = + new(Array.Empty(), Array.Empty(), Array.Empty(), 0); + + public SectionView? Find(string id) + { + foreach (SectionView v in Sections) + if (v.Id.Equals(id, StringComparison.OrdinalIgnoreCase)) return v; + return null; + } + + public ServerState? Server(string id) + { + foreach (ServerState s in Servers) + if (s.Id.Equals(id, StringComparison.OrdinalIgnoreCase)) return s; + return null; + } + } + + private static readonly BuiltInServer[] BuiltIns = + { + new(IltInfo.ServerId, "Infinite Leaftide", static () => IltInfo.IsIlt, static () => + { + IltVerdict v = IltInfo.Detected; + return (v.IsIlt, v.Reason); + }), + new(ServerInfo.ServerId, "Aelrynth", static () => ServerInfo.IsAelrynth, static () => + { + ServerVerdict v = ServerInfo.Detected; + return (v.IsAelrynth, v.Reason); + }), + }; + + private static readonly object Gate = new(); + /// The engine's items; Unless = a plugin whose own manifest replaces the item ("" = always). + private static readonly List<(SectionContribution Item, string Unless)> EngineItems = new(); // under Gate + private static readonly Dictionary PluginManifests = + new(StringComparer.OrdinalIgnoreCase); // render thread only + + private static volatile Snapshot _snapshot = Snapshot.Empty; + private static long _nextPollMs, _nextRebuildMs; + private static int _lastForceVersion = -1; + private static int _revision; + private static string _lastSignature = string.Empty; + + /// The current servers and sections. Any thread. + public static Snapshot Current => _snapshot; + + /// True for an id the engine detects itself. + public static bool IsBuiltInServer(string id) + { + foreach (BuiltInServer b in BuiltIns) + if (b.Id.Equals(id, StringComparison.OrdinalIgnoreCase)) return true; + return false; + } + + /// + /// An engine contribution (an engine panel or /rc command for a section), added at init. + /// Same rules as a plugin's: the command is checked by SectionManifestParser. With + /// , the item is left out while that plugin publishes a + /// manifest of its own (a stand-in for plugins too old to describe themselves). + /// + public static void AddEngineItem(string section, string server, string label, string command, string tooltip, + int order = 1000, string unlessPlugin = "") + { + string cmd = SectionManifestParser.Command(command); + string sec = SectionManifestParser.Id(section); + if (cmd.Length == 0 || sec.Length == 0) return; + var item = new SectionContribution(EnginePlugin, sec, SectionManifestParser.Id(server), label, string.Empty, + cmd, tooltip, Primary: false, Enabled: true, Note: string.Empty, Width: 0, Height: 0, Order: order); + lock (Gate) EngineItems.Add((item, unlessPlugin)); + Invalidate(); + } + + /// True when a plugin whose name contains publishes a manifest. Render thread. + private static bool HasManifestFrom(string plugin) + { + foreach (string name in PluginManifests.Keys) + if (name.Contains(plugin, StringComparison.OrdinalIgnoreCase)) return true; + return false; + } + + /// Rebuilds on the next Tick (an override or the character changed). Any thread. + public static void Invalidate() + { + Volatile.Write(ref _nextRebuildMs, 0); + IltInfo.Invalidate(); + ServerInfo.Invalidate(); + } + + /// Reads the manifests again on the next Tick. Any thread. + public static void RefreshManifests() => Volatile.Write(ref _nextPollMs, 0); + + /// Render thread, every frame: cheap until a poll or rebuild is due. + public static void Tick() + { + long now = Environment.TickCount64; + bool changed = false; + if (now >= Volatile.Read(ref _nextPollMs)) + { + Volatile.Write(ref _nextPollMs, now + ManifestPollMs); + changed |= PollManifests(); + } + int forceVersion = ServerForceStore.Version; + if (forceVersion != _lastForceVersion) + { + _lastForceVersion = forceVersion; + IltInfo.Invalidate(); + ServerInfo.Invalidate(); + changed = true; + } + if (!changed && now < Volatile.Read(ref _nextRebuildMs)) return; + Volatile.Write(ref _nextRebuildMs, now + RebuildMs); + Rebuild(); + } + + /// Reads every plugin's manifest; re-parses only the ones whose text changed. + private static bool PollManifests() + { + bool changed = false; + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach ((string plugin, string json) in Plugins.PluginManager.CollectSectionManifests()) + { + seen.Add(plugin); + if (PluginManifests.TryGetValue(plugin, out var old) && old.Json == json) continue; + SectionManifest m = SectionManifestParser.Parse(plugin, json, out string error); + if (error.Length > 0) RynthLog.UI($"Sections: {plugin}'s manifest was not read - {error}."); + PluginManifests[plugin] = (json, m); + changed = true; + } + // A plugin that unloaded (or stopped answering) takes its sections with it. + var gone = new List(); + foreach (string plugin in PluginManifests.Keys) + if (!seen.Contains(plugin)) gone.Add(plugin); + foreach (string plugin in gone) { PluginManifests.Remove(plugin); changed = true; } + return changed; + } + + private static void Rebuild() + { + var manifests = new List(); + var engineItems = new List(); + lock (Gate) + foreach ((SectionContribution item, string unless) in EngineItems) + if (unless.Length == 0 || !HasManifestFrom(unless)) engineItems.Add(item); + manifests.Add(new SectionManifest(EnginePlugin, Array.Empty(), Array.Empty(), engineItems.ToArray())); + foreach (var entry in PluginManifests.Values) manifests.Add(entry.Manifest); + + List servers = BuildServers(manifests); + + // Installed server plugins the connect host left out: listed so they can be picked, and + // loaded as soon as this character forces their server On (picker, chat or saved override). + List notLoaded = NotLoadedServerPlugins(); + NotLoadedServers.Append(servers, notLoaded, ServerForceStore.Get); + foreach (string id in NotLoadedServers.ForcedOn(notLoaded, ServerForceStore.Get)) + Plugins.PluginManager.RequestServerPluginLoad(id); + + List sections = SectionCatalog.Build(manifests, ImGuiBackend.ImGuiPanelHost.CanEmbed, servers); + + // Bump the revision only when what the UI shows changed, so the menus and the push stay quiet. + string signature = Signature(servers, sections); + if (signature != _lastSignature) + { + _lastSignature = signature; + _revision++; + } + _snapshot = new Snapshot(servers, sections, manifests, _revision); + } + + /// The built-in servers, then every server a manifest declares with a new id. + private static List BuildServers(List manifests) + { + var list = new List(); + foreach (BuiltInServer b in BuiltIns) + { + bool active = false, detected = false; + string reason = string.Empty; + try + { + active = b.Active(); + (detected, reason) = b.Detect(); + } + catch (Exception ex) { reason = "check failed: " + ex.Message; } + list.Add(new ServerState(b.Id, b.Name, active, detected, ServerForceStore.Get(b.Id), true, reason)); + } + + string host = ServerInfo.LaunchHost; + string? world = AccountHooks.AnnouncedWorldName; + foreach (SectionManifest m in manifests) + foreach (SectionServerDecl d in m.Servers) + { + if (IsBuiltInServer(d.Id) || list.Exists(s => s.Id.Equals(d.Id, StringComparison.OrdinalIgnoreCase))) continue; + bool detected = SectionCatalog.DetectDeclared(d, host, world, out string reason); + ServerForce force = ServerForceStore.Get(d.Id); + list.Add(new ServerState(d.Id, d.Name, ServerForceText.Apply(force, detected), detected, force, false, + $"{reason} (declared by {m.Plugin})")); + } + return list; + } + + /// PluginManager's skipped server plugins, as the pure list NotLoadedServers takes. + private static List NotLoadedServerPlugins() + { + IReadOnlyList skipped = Plugins.PluginManager.SkippedServerPlugins; + var list = new List(skipped.Count); + foreach (Plugins.SkippedServerPlugin s in skipped) + list.Add(new NotLoadedServer(SectionManifestParser.Id(s.ServerId), s.ServerName, s.PluginName)); + return list; + } + + /// A compact text of what the menus and the rail show, to detect a change. + private static string Signature(List servers, List sections) + { + var sb = new System.Text.StringBuilder(256); + foreach (ServerState s in servers) + sb.Append(s.Id).Append(s.Active ? '+' : '-').Append((int)s.Force).Append(';'); + foreach (SectionView v in sections) + { + sb.Append('|').Append(v.Id).Append(':'); + foreach (SectionPane p in v.Panes) + sb.Append(p.Title).Append(p.Contribution?.Enabled == false ? '0' : '1').Append('/'); + foreach (SectionGroup g in v.Groups) + foreach (SectionContribution c in g.Items) + sb.Append(',').Append(c.Label).Append(c.Enabled ? '1' : '0'); + } + return sb.ToString(); + } +} diff --git a/src/RynthCore.Engine/UI/Sections/ServerForce.cs b/src/RynthCore.Engine/UI/Sections/ServerForce.cs new file mode 100644 index 0000000..5630c87 --- /dev/null +++ b/src/RynthCore.Engine/UI/Sections/ServerForce.cs @@ -0,0 +1,134 @@ +// ============================================================================ +// RynthCore.Engine - UI/Sections/ServerForce.cs +// The per-character server override: Auto (detect), On (treat this world as +// the server) or Off (never treat it as the server), one per server id. +// +// Pure (no AC, no engine state, no I/O): the offline tests (tools/SectionsTests) +// compile this file as is. ServerForceStore.cs holds the loaded file and saves it. +// +// File (server_force.txt, one line per override, tab-separated): +// \t \t on|off +// Auto is the absence of a line. Blank lines and lines starting with '#' are +// skipped; a malformed line is dropped, never thrown. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.Text; + +namespace RynthCore.Engine.UI.Sections; + +/// How a server's detection is overridden for one character. +internal enum ServerForce +{ + /// Detect it (launch host, announced world name, the configured lists). + Auto, + /// Treat this world as the server, whatever detection says. + On, + /// Never treat this world as the server. + Off, +} + +internal static class ServerForceText +{ + /// "on" / "off" / "auto" (and the older /rc words) to a mode; false for anything else. + public static bool TryParse(string? text, out ServerForce mode) + { + switch ((text ?? string.Empty).Trim().ToLowerInvariant()) + { + case "auto": case "detect": mode = ServerForce.Auto; return true; + case "on": case "force": case "yes": case "true": mode = ServerForce.On; return true; + case "off": case "never": case "no": case "false": mode = ServerForce.Off; return true; + default: mode = ServerForce.Auto; return false; + } + } + + public static string Name(ServerForce mode) => mode switch + { + ServerForce.On => "on", + ServerForce.Off => "off", + _ => "auto", + }; + + /// Applies an override to a detected verdict. + public static bool Apply(ServerForce mode, bool detected) => mode switch + { + ServerForce.On => true, + ServerForce.Off => false, + _ => detected, + }; +} + +/// server_force.txt contents: character key -> server id -> On / Off. Not thread-safe (the store locks). +internal sealed class ServerForceFile +{ + /// Longest character key or server id kept (anything longer is a damaged line). + public const int MaxFieldLength = 128; + + private readonly Dictionary> _byCharacter = + new(StringComparer.OrdinalIgnoreCase); + + /// The character's override for (Auto when none). + public ServerForce Get(string characterKey, string serverId) + => _byCharacter.TryGetValue(characterKey, out var map) && map.TryGetValue(serverId, out ServerForce m) ? m : ServerForce.Auto; + + /// Every override saved for the character (a copy). + public Dictionary For(string characterKey) + => _byCharacter.TryGetValue(characterKey, out var map) + ? new Dictionary(map, StringComparer.OrdinalIgnoreCase) + : new Dictionary(StringComparer.OrdinalIgnoreCase); + + /// Sets (or with Auto, removes) one override. True when the contents changed. + public bool Set(string characterKey, string serverId, ServerForce mode) + { + if (!ValidField(characterKey) || !ValidField(serverId)) return false; + if (mode == ServerForce.Auto) + { + if (!_byCharacter.TryGetValue(characterKey, out var existing) || !existing.Remove(serverId)) return false; + if (existing.Count == 0) _byCharacter.Remove(characterKey); + return true; + } + if (!_byCharacter.TryGetValue(characterKey, out var map)) + _byCharacter[characterKey] = map = new Dictionary(StringComparer.OrdinalIgnoreCase); + if (map.TryGetValue(serverId, out ServerForce old) && old == mode) return false; + map[serverId] = mode; + return true; + } + + public static ServerForceFile Parse(IEnumerable? lines) + { + var file = new ServerForceFile(); + if (lines == null) return file; + foreach (string raw in lines) + { + if (string.IsNullOrWhiteSpace(raw)) continue; + string line = raw.TrimEnd('\r', '\n'); + if (line.TrimStart().StartsWith('#')) continue; + string[] f = line.Split('\t'); + if (f.Length < 3) continue; + string key = f[0].Trim(), server = f[1].Trim(); + if (!ServerForceText.TryParse(f[2], out ServerForce mode) || mode == ServerForce.Auto) continue; + file.Set(key, server, mode); + } + return file; + } + + public string Write() + { + var sb = new StringBuilder(); + sb.Append("# RynthCore per-character server overrides: character key, server id, on|off (auto = no line).\n"); + foreach (var (key, map) in _byCharacter) + foreach (var (server, mode) in map) + sb.Append(key).Append('\t').Append(server).Append('\t').Append(ServerForceText.Name(mode)).Append('\n'); + return sb.ToString(); + } + + /// No tab or line break (the file's separators), not empty, not overlong. + private static bool ValidField(string? text) + { + if (string.IsNullOrWhiteSpace(text) || text.Length > MaxFieldLength) return false; + foreach (char c in text) + if (c is '\t' or '\n' or '\r') return false; + return true; + } +} diff --git a/src/RynthCore.Engine/UI/Sections/ServerForceStore.cs b/src/RynthCore.Engine/UI/Sections/ServerForceStore.cs new file mode 100644 index 0000000..7f732c3 --- /dev/null +++ b/src/RynthCore.Engine/UI/Sections/ServerForceStore.cs @@ -0,0 +1,160 @@ +// ============================================================================ +// RynthCore.Engine - UI/Sections/ServerForceStore.cs +// server_force.txt: each character's Auto / On / Off override per server +// (ServerForce.cs has the format). IltInfo and ServerInfo read their override +// here, so "/rc ilt on", "/rc server aelrynth" and the Mini Remote's Char +// section all set the same saved value. +// +// Before a character is logged in there is no key to save under: an override +// set then holds for this session only (until a character logs in). +// +// Threads: reads from any thread are a volatile snapshot (a lock only when the +// character changes); a change locks briefly and queues the save on +// UiBackgroundWriter, never AC's render thread. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading; +using RynthCore.Engine.Compatibility; + +namespace RynthCore.Engine.UI.Sections; + +internal static class ServerForceStore +{ + private static readonly object Sync = new(); + private static ServerForceFile _file = new(); // under Sync + private static readonly Dictionary Session = // under Sync: no character yet + new(StringComparer.OrdinalIgnoreCase); + private static volatile bool _loaded; + private static bool _loadQueued; + + private sealed record Snap(string Key, Dictionary Map); + private static Snap? _snap; + + /// Bumped on every change, so callers can re-read cheaply. + private static int _version; + public static int Version => Volatile.Read(ref _version); + + private static string FilePath => + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "server_force.txt"); + + /// A character is logged in: overrides are saved for it. + public static bool HasCharacter => SessionStateRegistry.LastCharacterName.Length > 0; + + private static string CharacterKey => + D3D9.VideoPatchPolicy.CharacterKey(SessionStateRegistry.LastServerName, SessionStateRegistry.LastCharacterName); + + /// Queues the one-time read off the calling thread. Any thread; cheap after the first call. + public static void EnsureLoadQueued() + { + if (_loaded) return; + lock (Sync) + { + if (_loadQueued) return; + _loadQueued = true; + } + UiBackgroundWriter.Enqueue("server overrides (load)", LoadNow); + } + + private static void LoadNow() + { + ServerForceFile file; + try + { + string path = FilePath; + file = File.Exists(path) ? ServerForceFile.Parse(File.ReadAllLines(path)) : new ServerForceFile(); + } + catch (Exception ex) + { + RynthLog.UI($"ServerForce: reading server_force.txt failed - {ex.GetType().Name}: {ex.Message}"); + file = new ServerForceFile(); + } + lock (Sync) + { + _file = file; + Volatile.Write(ref _snap, null); + _loaded = true; + } + Interlocked.Increment(ref _version); + } + + /// + /// The override for : the logged-in character's saved one, or + /// before login the session's. Auto until the file is read. Any thread. + /// + public static ServerForce Get(string serverId) + { + EnsureLoadQueued(); + if (!HasCharacter) + { + lock (Sync) return Session.TryGetValue(serverId, out ServerForce m) ? m : ServerForce.Auto; + } + if (!_loaded) return ServerForce.Auto; + string key = CharacterKey; + Snap? s = Volatile.Read(ref _snap); + if (s == null || !string.Equals(s.Key, key, StringComparison.OrdinalIgnoreCase)) + { + lock (Sync) + { + s = new Snap(key, _file.For(key)); + Volatile.Write(ref _snap, s); + } + } + return s.Map.TryGetValue(serverId, out ServerForce mode) ? mode : ServerForce.Auto; + } + + /// + /// Sets the override. Saved for the logged-in character; before login it holds for this + /// session. False (with the reason) before the file is read. Any thread. + /// + public static bool Set(string serverId, ServerForce mode, out string where) + { + EnsureLoadQueued(); + if (!HasCharacter) + { + lock (Sync) + { + if (mode == ServerForce.Auto) Session.Remove(serverId); + else Session[serverId] = mode; + } + Interlocked.Increment(ref _version); + where = "this session (log in a character to save it for that character)"; + return true; + } + if (!_loaded) { where = "not yet: still reading the saved overrides, try again in a moment"; return false; } + + string key = CharacterKey; + string? text = null; + lock (Sync) + { + if (_file.Set(key, serverId, mode)) + { + Volatile.Write(ref _snap, new Snap(key, _file.For(key))); + text = _file.Write(); + } + } + Interlocked.Increment(ref _version); + if (text != null) UiBackgroundWriter.Enqueue("server overrides", () => SaveNow(text)); + where = "saved for " + SessionStateRegistry.LastCharacterName; + return true; + } + + private static void SaveNow(string text) + { + try + { + string path = FilePath; + string? dir = Path.GetDirectoryName(path); + if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); + string tmp = path + ".tmp"; + File.WriteAllText(tmp, text); + File.Move(tmp, path, overwrite: true); + } + catch (Exception ex) + { + RynthLog.UI($"ServerForce: writing server_force.txt failed - {ex.GetType().Name}: {ex.Message}"); + } + } +} diff --git a/src/RynthCore.Engine/UI/Sections/ServerSelection.cs b/src/RynthCore.Engine/UI/Sections/ServerSelection.cs new file mode 100644 index 0000000..e6f6953 --- /dev/null +++ b/src/RynthCore.Engine/UI/Sections/ServerSelection.cs @@ -0,0 +1,131 @@ +// ============================================================================ +// RynthCore.Engine - UI/Sections/ServerSelection.cs +// "Which server is this?" as one choice, on top of the per-server overrides +// (ServerForce): the Diagnostics page's server picker and "/rc server pick". +// +// pick that server forced On, every other server forced Off, so +// exactly one server is active whatever detection says; +// pick auto every override back to Auto (detection decides again). +// +// Also the questions every reader of the server list asks the same way: which +// server is the active one, and which plugin owns a server (the one plugins +// ask for its settings, RynthServerPack's "RynthServer.Profile"). +// +// Pure (no AC, no engine state, no I/O): tools/SectionsTests compiles it. +// ServerSelectionStore.cs applies a plan to ServerForceStore. +// ============================================================================ + +using System; +using System.Collections.Generic; + +namespace RynthCore.Engine.UI.Sections; + +internal static class ServerSelection +{ + /// The pick that hands the choice back to detection. + public const string Auto = "auto"; + + /// + /// The override each server gets for : Auto for all with + /// (or ""), else On for the picked id and Off for the rest. Null when the + /// pick names no server in . + /// + public static List<(string Id, ServerForce Force)>? Plan(IReadOnlyList servers, string? pick) + { + string id = (pick ?? string.Empty).Trim(); + bool auto = id.Length == 0 || id.Equals(Auto, StringComparison.OrdinalIgnoreCase); + if (!auto && Find(servers, id) == null) return null; + + var plan = new List<(string, ServerForce)>(servers.Count); + foreach (ServerState s in servers) + { + ServerForce force = auto ? ServerForce.Auto + : s.Id.Equals(id, StringComparison.OrdinalIgnoreCase) ? ServerForce.On : ServerForce.Off; + plan.Add((s.Id, force)); + } + return plan; + } + + /// + /// The current pick: when no override is set, a server id when exactly that + /// server is forced On and none other is On, or null for any other mix (overrides set one by + /// one with "/rc server <id> on|off"). + /// + public static string? CurrentPick(IReadOnlyList servers) + { + string? on = null; + bool anyForced = false; + foreach (ServerState s in servers) + { + if (s.Force == ServerForce.Auto) continue; + anyForced = true; + if (s.Force != ServerForce.On) continue; + if (on != null) return null; + on = s.Id; + } + if (!anyForced) return Auto; + if (on == null) return null; + // A pick forces every other server Off; one left on Auto is a hand-made mix. + foreach (ServerState s in servers) + if (!s.Id.Equals(on, StringComparison.OrdinalIgnoreCase) && s.Force == ServerForce.Auto) return null; + return on; + } + + /// + /// The server this world counts as: the first active one forced On (an override beats + /// detection), else the first active one (built-in servers come first). Null when none is. + /// + public static ServerState? ActiveServer(IReadOnlyList servers) + { + ServerState? first = null; + foreach (ServerState s in servers) + { + if (!s.Active) continue; + if (s.Force == ServerForce.On) return s; + first ??= s; + } + return first; + } + + /// + /// The plugin that owns : the first manifest that declares it, else + /// the plugin with the most contributions for it (RynthILT for the built-in "ilt"; ties go to + /// the name that sorts first). "" when no plugin has anything for it. + /// (the engine's own manifest) never owns a server. + /// + public static string OwnerPlugin(IReadOnlyList manifests, string serverId, string enginePlugin) + { + foreach (SectionManifest m in manifests) + { + if (IsEngine(m, enginePlugin)) continue; + foreach (SectionServerDecl d in m.Servers) + if (d.Id.Equals(serverId, StringComparison.OrdinalIgnoreCase)) return m.Plugin; + } + + string best = string.Empty; + int bestCount = 0; + foreach (SectionManifest m in manifests) + { + if (IsEngine(m, enginePlugin)) continue; + int n = 0; + foreach (SectionContribution c in m.Contributions) + if (c.Server.Equals(serverId, StringComparison.OrdinalIgnoreCase)) n++; + if (n > bestCount || (n == bestCount && n > 0 && string.Compare(m.Plugin, best, StringComparison.OrdinalIgnoreCase) < 0)) + { + best = m.Plugin; + bestCount = n; + } + } + return best; + } + + private static bool IsEngine(SectionManifest m, string enginePlugin) + => m.Plugin.Length == 0 || m.Plugin.Equals(enginePlugin, StringComparison.OrdinalIgnoreCase); + + private static ServerState? Find(IReadOnlyList servers, string id) + { + foreach (ServerState s in servers) + if (s.Id.Equals(id, StringComparison.OrdinalIgnoreCase)) return s; + return null; + } +} diff --git a/src/RynthCore.Engine/UI/Sections/ServerSelectionStore.cs b/src/RynthCore.Engine/UI/Sections/ServerSelectionStore.cs new file mode 100644 index 0000000..20930b7 --- /dev/null +++ b/src/RynthCore.Engine/UI/Sections/ServerSelectionStore.cs @@ -0,0 +1,53 @@ +// ============================================================================ +// RynthCore.Engine - UI/Sections/ServerSelectionStore.cs +// Applies a server pick (ServerSelection.Plan) to the saved per-character +// overrides (ServerForceStore) and rebuilds the verdicts, so the menus, the +// "servermenu" push and plugin API v86 (GetServerStateJson) follow at once. +// Used by the Diagnostics page's server picker and "/rc server pick". +// +// Threads: any (ServerForceStore locks; the rebuild runs on the next frame). +// ============================================================================ + +using System.Collections.Generic; + +namespace RynthCore.Engine.UI.Sections; + +internal static class ServerSelectionStore +{ + /// + /// Picks (a server id, or ). + /// says what happened, for chat. False when the pick names no + /// known server or an override couldn't be saved. + /// + public static bool Apply(string? pick, out string message) + { + IReadOnlyList servers = SectionRegistry.Current.Servers; + List<(string Id, ServerForce Force)>? plan = ServerSelection.Plan(servers, pick); + if (plan == null) + { + message = $"No server called '{pick}'. /rc server lists them."; + return false; + } + + string where = string.Empty; + foreach ((string id, ServerForce force) in plan) + { + if (ServerForceStore.Get(id) == force) continue; + if (!ServerForceStore.Set(id, force, out where)) + { + message = $"Server pick not saved: {where}."; + SectionRegistry.Invalidate(); + return false; + } + } + SectionRegistry.Invalidate(); + + bool auto = string.IsNullOrWhiteSpace(pick) || pick.Trim().Equals(ServerSelection.Auto, System.StringComparison.OrdinalIgnoreCase); + string saved = where.Length > 0 ? $" ({where})" : string.Empty; + message = auto + ? "Server: detected again (every override back to auto)" + saved + "." + : $"Server: '{pick!.Trim()}' picked for this character; every other server off" + saved + "."; + RynthLog.Milestone("ServerSelection: " + message); + return true; + } +} diff --git a/src/RynthCore.Engine/UI/Sections/ServerStateJson.cs b/src/RynthCore.Engine/UI/Sections/ServerStateJson.cs new file mode 100644 index 0000000..fcf1125 --- /dev/null +++ b/src/RynthCore.Engine/UI/Sections/ServerStateJson.cs @@ -0,0 +1,89 @@ +// ============================================================================ +// RynthCore.Engine - UI/Sections/ServerStateJson.cs +// The server list as JSON for plugins (plugin API v86, GetServerStateJson): +// one answer to "which server is this, and which plugin has its settings", +// the same verdicts the Mini Remote, the menus and the "servermenu" push use. +// +// { +// "schema": 1, "revision": 12, +// "host": "infiniteleaftide.online", "world": "InfiniteLeaftide", +// "pick": "auto" | "" | "mixed", +// "active": "ilt", "activeName": "Infinite Leaftide", "activePlugin": "RynthILT", +// "servers": [ { "id", "name", "active", "detected", "force": "auto|on|off", +// "builtIn", "plugin", "reason" }, ... ] +// } +// "world" is what the server announced at login ("" before, or when the hook +// isn't there); "active" is "" when no server is active (a retail-like world). +// "plugin" is the server's owner (ServerSelection.OwnerPlugin): the plugin to +// ask for the server's settings ("RynthServer.Profile", or RynthILT's +// "RynthILT.Server"); "" when none is loaded. +// +// Pure (BCL only): tools/SectionsTests compiles it. +// ============================================================================ + +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Text.Json; + +namespace RynthCore.Engine.UI.Sections; + +internal static class ServerStateJson +{ + public const int Schema = 1; + + /// The JSON for (from ), UTF-8 text. + public static string Build(IReadOnlyList servers, IReadOnlyList manifests, + int revision, string? host, string? world, string enginePlugin) + { + ServerState? active = ServerSelection.ActiveServer(servers); + string pick = ServerSelection.CurrentPick(servers) ?? "mixed"; + + using var stream = new MemoryStream(512); + using (var w = new Utf8JsonWriter(stream)) + { + w.WriteStartObject(); + w.WriteNumber("schema", Schema); + w.WriteNumber("revision", revision); + w.WriteString("host", host ?? string.Empty); + w.WriteString("world", world ?? string.Empty); + w.WriteString("pick", pick); + w.WriteString("active", active?.Id ?? string.Empty); + w.WriteString("activeName", active?.Name ?? string.Empty); + w.WriteString("activePlugin", active == null ? string.Empty : ServerSelection.OwnerPlugin(manifests, active.Id, enginePlugin)); + w.WriteStartArray("servers"); + foreach (ServerState s in servers) + { + w.WriteStartObject(); + w.WriteString("id", s.Id); + w.WriteString("name", s.Name); + w.WriteBoolean("active", s.Active); + w.WriteBoolean("detected", s.Detected); + w.WriteString("force", ServerForceText.Name(s.Force)); + w.WriteBoolean("builtIn", s.BuiltIn); + w.WriteString("plugin", ServerSelection.OwnerPlugin(manifests, s.Id, enginePlugin)); + w.WriteString("reason", s.Reason ?? string.Empty); + w.WriteEndObject(); + } + w.WriteEndArray(); + w.WriteEndObject(); + } + return Encoding.UTF8.GetString(stream.ToArray()); + } + + /// + /// Copies as NUL-terminated UTF-8 into the caller's buffer when it + /// fits and returns its byte length either way (length >= capacity: too small, nothing + /// written). The plugin API's convention for text it hands out. + /// + public static unsafe int Write(string json, byte* buffer, int capacity) + { + int length = Encoding.UTF8.GetByteCount(json); + if (buffer == null || capacity <= length) return length; + fixed (char* src = json) + Encoding.UTF8.GetBytes(src, json.Length, buffer, capacity); + buffer[length] = 0; + return length; + } +} diff --git a/src/RynthCore.Engine/UI/ServerMenus.cs b/src/RynthCore.Engine/UI/ServerMenus.cs index 1a36385..8b81bdc 100644 --- a/src/RynthCore.Engine/UI/ServerMenus.cs +++ b/src/RynthCore.Engine/UI/ServerMenus.cs @@ -1,164 +1,213 @@ // ============================================================================ // RynthCore.Engine - UI/ServerMenus.cs -// Server sections: the bottom half of the RynthAi dashboard's Char menu and of -// the Mini Remote's right-click menu (the top half, "Character", is the -// windows every server has). +// The servers and sections, as menus: the bottom half of the RynthAi +// dashboard's Char menu and of the Mini Remote's right-click menu (the top +// half, "Character", is the windows every server has), and the "servermenu" +// push that gives RynthAi the same list for its own menus. // -// A server (Infinite Leaftide today) is defined once: how to tell the client -// is on it, and the command that forces it. Each installed plugin with windows -// for that server adds its items (EntryPoint, by which plugin DLLs exist). A -// section shows only while its server is detected or forced, and only with at -// least one item, so it appears exactly when you are on that server with one -// of its plugins installed. A new server or server plugin is one DefineServer -// plus its AddItem calls; neither menu changes. +// Everything comes from UI/Sections/SectionRegistry: the servers (built in or +// declared by a plugin), whether each is active (detected or forced for this +// character), and what the engine and the installed plugins add for each. A +// server's group shows only while it is active and has items. // -// Items are "/rc" chat commands: the engine runs them itself -// (RynthCoreChatCommands) and RynthAi runs them through InvokeChatParser. -// RynthAi learns the sections from the "servermenu" remote command this file -// pushes (Tick: when they change, and every ResendMs in case it missed one). -// Payload: one line per section ("S", id, name, active 0/1, force command) -// followed by its items ("I", label, command, tooltip, feature), tab-separated. +// Items run "/rc" commands through the engine's dispatcher (any other command +// goes through the chat dispatcher, as if typed); a plugin surface opens its +// section in the Mini Remote ("/rc miniremote section "). +// +// Push (Tick: when it changes, and every ResendMs in case RynthAi missed one), +// tab-separated lines: +// V id name active 0/1 force auto|on|off detected 0/1 reason every server +// X id label every section, rail order +// S id name active 0/1 force command a server with items +// I label command tooltip feature its items +// N id pattern default|engine.json a server's world names +// RynthAi 0.5.54 and older read only S and I (unknown kinds and extra fields are +// skipped); a "section:" feature is a surface it may show in its own Mini Remote. +// RynthILT (0.1.1+) gets the same push for its copy of the ILT settings (V and N), +// and so does every server plugin whose sections manifest declares a server +// (RynthColdeve, RynthAelrynth, ...: their server card's verdict and override). // ============================================================================ using System; using System.Collections.Generic; using System.Text; using RynthCore.Engine.UI.Data; +using RynthCore.Engine.UI.Sections; namespace RynthCore.Engine.UI; -/// -/// One menu item of a server section. is an optional key RynthAi -/// checks before enabling it ("tab:quests": that Mini Remote tab is available). -/// -internal sealed record ServerMenuItem(string Label, string Command, string Tooltip, string Feature = ""); - -/// A server's menu section: detection, force command and the installed plugins' items. -internal sealed class ServerMenuSection -{ - public ServerMenuSection(string id, string name, Func isActive, string forceCommand) - { - Id = id; - Name = name; - IsActiveFn = isActive; - ForceCommand = forceCommand; - } - - public string Id { get; } - public string Name { get; } - public string ForceCommand { get; } - internal Func IsActiveFn { get; } - internal List ItemList { get; } = new(); - public IReadOnlyList Items => ItemList; - - /// On this server (detected or forced). A failing check counts as not active. - public bool IsActive - { - get - { - try { return IsActiveFn(); } - catch { return false; } - } - } -} - internal static class ServerMenus { - /// How often RynthAi gets the sections again even when nothing changed. + /// How often RynthAi gets the list again even when nothing changed. private const long ResendMs = 30_000; /// How often the payload is rebuilt to look for a change. private const long CheckMs = 1_000; - private static readonly object Gate = new(); - private static readonly List Defined = new(); - // Copy-on-write view for the render thread (definitions only change during engine init). - private static volatile ServerMenuSection[] _sections = Array.Empty(); + /// Feature prefix of an item that is a plugin surface (its section in the Mini Remote). + public const string SectionFeaturePrefix = "section:"; + + /// How often RynthILT gets the list again: it may load (or hot-reload) after the last change. + private const long IltResendMs = 10_000; + + /// The plugin that keeps a copy of the ILT settings. + private const string RynthIltPlugin = "RynthILT"; private static long _nextCheckMs; private static long _lastPushMs; private static string _lastPayload = string.Empty; + private static long _lastIltPushMs; + private static string _lastIltPayload = string.Empty; + // Server plugins (sections manifests that declare a server): the last payload each took, and when. + private static readonly Dictionary _serverPluginPushes = new(StringComparer.OrdinalIgnoreCase); - /// RynthAi is installed: Tick pushes it the sections. + /// RynthAi is installed: Tick pushes it the list. public static bool PushToRynthAi { get; set; } - /// Every defined server, in definition order (with or without items). - public static IReadOnlyList All => _sections; + /// RynthILT is installed: Tick pushes it the list too (its ILT settings view). + public static bool PushToRynthIlt { get; set; } + + /// One menu item: a command, with the section it belongs to. + internal sealed record MenuItem(string Label, string Command, string Tooltip, string Feature, bool Enabled, string Note); + + /// A server's items for the menus: every section's, surfaces as "open the section". + internal sealed record MenuGroup(ServerState Server, MenuItem[] Items); /// - /// Defines a server (once; a second call with the same id is ignored). - /// runs on the render thread, so it must be cheap. + /// Runs an item's command: an engine "/rc" command directly, anything else through the + /// chat dispatcher (plugins' commands, as if typed). Render thread. /// - public static void DefineServer(string id, string name, Func isActive, string forceCommand) - { - lock (Gate) - { - if (Find(id) != null) return; - Defined.Add(new ServerMenuSection(id, name, isActive, forceCommand)); - _sections = Defined.ToArray(); - } - } - - /// An installed plugin's window for server (ignored for an unknown server). - public static void AddItem(string serverId, ServerMenuItem item) - { - lock (Gate) - { - ServerMenuSection? section = Find(serverId); - if (section == null) - { - RynthLog.UI($"ServerMenus: item '{item.Label}' names unknown server '{serverId}'; ignored."); - return; - } - section.ItemList.Add(item); - _sections = Defined.ToArray(); - } - } - - private static ServerMenuSection? Find(string id) - { - foreach (ServerMenuSection s in Defined) - if (s.Id.Equals(id, StringComparison.OrdinalIgnoreCase)) return s; - return null; - } - - /// Runs an item's command through the engine's /rc dispatcher. public static void Run(string command) { - if (!Compatibility.RynthCoreChatCommands.TryHandle(command)) - RynthLog.UI($"ServerMenus: '{command}' is not an engine command."); + string cmd = SectionManifestParser.Command(command); + if (cmd.Length == 0) return; + if (Compatibility.RynthCoreChatCommands.TryHandle(cmd)) return; + if (cmd.StartsWith("/rc ", StringComparison.OrdinalIgnoreCase)) + { + RynthLog.UI($"ServerMenus: '{cmd}' is not an engine command."); + return; + } + Compatibility.ChatCommandDispatcher.Dispatch(cmd); + } + + /// The command that opens section in the Mini Remote. + public static string OpenSectionCommand(string sectionId) => "/rc miniremote section " + sectionId; + + /// The command that forces on for this character. + public static string ForceCommand(string serverId) => "/rc server " + serverId + " on"; + + /// Every server that has items (active or not), with them. Any thread. + public static List Groups(SectionRegistry.Snapshot snap) + { + var byServer = new Dictionary>(StringComparer.OrdinalIgnoreCase); + foreach (SectionManifest m in snap.Manifests) + foreach (SectionContribution c in m.Contributions) + { + if (c.IsUniversal) continue; + if (!byServer.TryGetValue(c.Server, out var list)) byServer[c.Server] = list = new List(); + list.Add(c.IsSurface + ? new MenuItem(c.Label, OpenSectionCommand(c.Section), c.Tooltip, SectionFeaturePrefix + c.Section, c.Enabled, c.Note) + : new MenuItem(c.Label, c.Command, c.Tooltip, string.Empty, c.Enabled, c.Note)); + } + var groups = new List(); + foreach (ServerState s in snap.Servers) + if (byServer.TryGetValue(s.Id, out var items)) + groups.Add(new MenuGroup(s, items.ToArray())); + return groups; } // ── RynthAi push ─────────────────────────────────────────────────── /// - /// Render thread, every frame: sends RynthAi the sections when they changed (a server - /// detected or forced, or not any more) and every . + /// Render thread, every frame: sends RynthAi the list when it changed (a server + /// detected or forced, or not any more; a plugin's sections) and every . /// public static void Tick() { - if (!PushToRynthAi) return; + SectionRegistry.Tick(); + SectionRegistry.Snapshot snap = SectionRegistry.Current; + List serverPlugins = ServerPluginTargets(snap); + if (!PushToRynthAi && !PushToRynthIlt && serverPlugins.Count == 0) return; long now = Environment.TickCount64; if (now < _nextCheckMs) return; _nextCheckMs = now + CheckMs; - string payload = BuildPayload(); - if (payload == _lastPayload && now - _lastPushMs < ResendMs) return; - _lastPayload = payload; - _lastPushMs = now; - RynthAiCommands.ApplyRemoteCommand("servermenu", payload); + string payload = BuildPayload(snap, IltWorldNames()); + // Same resend rule as RynthILT's: a plugin may (re)load after the last change. + foreach (string plugin in serverPlugins) + { + bool due = !_serverPluginPushes.TryGetValue(plugin, out var last) + || last.Payload != payload || now - last.AtMs >= IltResendMs; + if (due && Plugins.PluginManager.SendPluginCommand(plugin, "servermenu", payload)) + _serverPluginPushes[plugin] = (payload, now); + } + if (PushToRynthAi && (payload != _lastPayload || now - _lastPushMs >= ResendMs)) + { + _lastPayload = payload; + _lastPushMs = now; + RynthAiCommands.ApplyRemoteCommand("servermenu", payload); + } + // Not delivered (RynthILT not loaded yet, or an older one without the export): try again next check. + if (PushToRynthIlt && (payload != _lastIltPayload || now - _lastIltPushMs >= IltResendMs) + && Plugins.PluginManager.SendPluginCommand(RynthIltPlugin, "servermenu", payload)) + { + _lastIltPayload = payload; + _lastIltPushMs = now; + } } - private static string BuildPayload() + /// + /// The plugins to push to besides RynthAi and RynthILT (they have their own paths): each one + /// whose sections manifest declares a server. Pure apart from reading . + /// + internal static List ServerPluginTargets(SectionRegistry.Snapshot snap) { - var sb = new StringBuilder(256); - foreach (ServerMenuSection s in _sections) + var list = new List(); + foreach (SectionManifest m in snap.Manifests) { - if (s.Items.Count == 0) continue; // no plugin for it is installed - sb.Append('S').Append('\t').Append(Clean(s.Id)).Append('\t').Append(Clean(s.Name)).Append('\t') - .Append(s.IsActive ? '1' : '0').Append('\t').Append(Clean(s.ForceCommand)).Append('\n'); - foreach (ServerMenuItem i in s.Items) + if (m.Servers.Length == 0 || m.Plugin.Length == 0) continue; + if (m.Plugin.Equals("RynthAi", StringComparison.OrdinalIgnoreCase) + || (PushToRynthIlt && m.Plugin.Equals(RynthIltPlugin, StringComparison.OrdinalIgnoreCase))) + continue; + if (!list.Exists(p => p.Equals(m.Plugin, StringComparison.OrdinalIgnoreCase))) list.Add(m.Plugin); + } + return list; + } + + /// The ILT world-name patterns in force, and whether they are the built-in defaults. + private static (string Server, string Pattern, bool Default)[] IltWorldNames() + { + IReadOnlyList? names = Plugins.EngineSettings.IltServerNames; + IReadOnlyList list = names ?? Compatibility.IltDetect.DefaultServerNames; + var result = new (string, string, bool)[list.Count]; + for (int i = 0; i < list.Count; i++) result[i] = ("ilt", list[i], names == null); + return result; + } + + /// + /// The push text for and the servers' . + /// Pure apart from reading them. + /// + internal static string BuildPayload(SectionRegistry.Snapshot snap, + IReadOnlyList<(string Server, string Pattern, bool Default)>? worldNames = null) + { + var sb = new StringBuilder(512); + foreach (ServerState s in snap.Servers) + sb.Append('V').Append('\t').Append(Clean(s.Id)).Append('\t').Append(Clean(s.Name)).Append('\t') + .Append(s.Active ? '1' : '0').Append('\t').Append(ServerForceText.Name(s.Force)).Append('\t') + .Append(s.Detected ? '1' : '0').Append('\t').Append(Clean(s.Reason ?? string.Empty)).Append('\n'); + if (worldNames != null) + foreach (var n in worldNames) + sb.Append('N').Append('\t').Append(Clean(n.Server)).Append('\t').Append(Clean(n.Pattern)).Append('\t') + .Append(n.Default ? "default" : "engine.json").Append('\n'); + foreach (SectionView v in snap.Sections) + sb.Append('X').Append('\t').Append(Clean(v.Id)).Append('\t').Append(Clean(v.Label)).Append('\n'); + foreach (MenuGroup g in Groups(snap)) + { + sb.Append('S').Append('\t').Append(Clean(g.Server.Id)).Append('\t').Append(Clean(g.Server.Name)).Append('\t') + .Append(g.Server.Active ? '1' : '0').Append('\t').Append(Clean(ForceCommand(g.Server.Id))).Append('\n'); + foreach (MenuItem i in g.Items) sb.Append('I').Append('\t').Append(Clean(i.Label)).Append('\t').Append(Clean(i.Command)).Append('\t') - .Append(Clean(i.Tooltip)).Append('\t').Append(Clean(i.Feature)).Append('\n'); + .Append(Clean(i.Note.Length > 0 && !i.Enabled ? i.Note : i.Tooltip)).Append('\t').Append(Clean(i.Feature)).Append('\n'); } return sb.ToString(); } @@ -172,43 +221,64 @@ internal static class ServerMenus return sb.ToString(); } - // ── ImGui menu ───────────────────────────────────────────────────── + // ── ImGui menus ──────────────────────────────────────────────────── /// - /// The server half of an ImGui popup menu: each active section's name and items. With - /// sections installed but none active, a note and one "Treat this world as ..." item per - /// installed server. Draws nothing (not even 's separator) - /// when no server plugin is installed. Returns true when it drew something. + /// The server half of an ImGui popup menu: each active server's name and items. With + /// servers that have items but none active, a note and one "Treat this world as ..." item + /// each (saved for this character). Draws nothing (not even 's + /// separator) when no server has items. Returns true when it drew something. /// public static bool DrawImGuiMenu(bool separatorFirst = false) { - ServerMenuSection[] sections = _sections; - bool any = false, installed = false; - foreach (ServerMenuSection s in sections) + List groups = Groups(SectionRegistry.Current); + if (groups.Count == 0) return false; + if (separatorFirst) ImGuiNET.ImGui.Separator(); + + bool any = false; + foreach (MenuGroup g in groups) { - if (s.Items.Count == 0) continue; - if (!installed && separatorFirst) ImGuiNET.ImGui.Separator(); - installed = true; - if (!s.IsActive) continue; + if (!g.Server.Active) continue; any = true; - ImGuiNET.ImGui.TextDisabled("Server: " + s.Name); - foreach (ServerMenuItem item in s.Items) + SafeImGui.TextDisabled("Server: " + g.Server.Name); + foreach (MenuItem item in g.Items) { - if (ImGuiNET.ImGui.MenuItem(item.Label + "##srv_" + s.Id, item.Command)) + if (ImGuiNET.ImGui.MenuItem(item.Label + "##srv_" + g.Server.Id + "_" + item.Command, "", false, item.Enabled)) Run(item.Command); - if (item.Tooltip.Length > 0) ImGuiNET.ImGui.SetItemTooltip(item.Tooltip); + string tip = item.Enabled || item.Note.Length == 0 ? item.Tooltip : item.Note; + if (tip.Length > 0) SafeImGui.SetItemTooltip(tip); } } - if (any || !installed) return any; + if (any) return true; ImGuiNET.ImGui.TextDisabled("Server: no installed server plugin matches this world"); - foreach (ServerMenuSection s in sections) + foreach (MenuGroup g in groups) { - if (s.Items.Count == 0 || s.ForceCommand.Length == 0) continue; - if (ImGuiNET.ImGui.MenuItem("Treat this world as " + s.Name + "##srvforce_" + s.Id, s.ForceCommand)) - Run(s.ForceCommand); - ImGuiNET.ImGui.SetItemTooltip("For this session only (testing); the world check goes back to automatic on restart."); + if (ImGuiNET.ImGui.MenuItem("Treat this world as " + g.Server.Name + "##srvforce_" + g.Server.Id)) + Run(ForceCommand(g.Server.Id)); + ImGuiNET.ImGui.SetItemTooltip("Saved for this character. Undo with /rc server " + g.Server.Id + " auto, or in the Mini Remote's Char section."); } return true; } + + /// + /// A "Sections" submenu: every Mini Remote section, opening it there. Returns true when + /// one was picked. + /// + public static bool DrawSectionsMenu(string label = "Sections") + { + SectionRegistry.Snapshot snap = SectionRegistry.Current; + if (snap.Sections.Count == 0 || !ImGuiNET.ImGui.BeginMenu(label)) return false; + bool picked = false; + foreach (SectionView v in snap.Sections) + { + if (ImGuiNET.ImGui.MenuItem(v.Label + "##sec_" + v.Id, "", false, v.HasContent || v.Core)) + { + Run(OpenSectionCommand(v.Id)); + picked = true; + } + } + ImGuiNET.ImGui.EndMenu(); + return picked; + } } diff --git a/src/RynthCore.PluginSdk/Manifest/RynthPluginManifest.cs b/src/RynthCore.PluginSdk/Manifest/RynthPluginManifest.cs index 868c7bb..951d422 100644 --- a/src/RynthCore.PluginSdk/Manifest/RynthPluginManifest.cs +++ b/src/RynthCore.PluginSdk/Manifest/RynthPluginManifest.cs @@ -29,6 +29,74 @@ public sealed class RynthPluginDependency public bool Optional { get; set; } } +/// +/// The one game server a server plugin is for (RynthColdeve, RynthILT, ...). The engine loads such a +/// plugin only where the client's connect host is this server's, or where no installed server +/// plugin claims the host (PluginManifestGate). Older engines and launchers ignore it. +/// +public sealed class RynthPluginServer +{ + /// Lower-case id, the same one the plugin's Mini Remote sections use ("coldeve", "ilt"). + public string Id { get; set; } = ""; + public string Name { get; set; } = ""; + /// Connect hosts: a name also matches hosts under it; an IP address matches only itself; '*' wildcards. + public List Hosts { get; set; } = new(); + /// World names the server announces ('*' wildcards, case-insensitive). + public List WorldNames { get; set; } = new(); + + /// + /// True when is one of : the same name, a host under + /// it ("game.infiniteleaftide.online" for "infiniteleaftide.online"), or a '*' pattern match. An + /// IP address matches only itself. Case and a trailing dot are ignored (the engine's IltDetect + /// rules, kept BCL-only here for the manifest gate). + /// + public bool MatchesHost(string? host, out string matched) + { + matched = ""; + if (string.IsNullOrWhiteSpace(host)) return false; + string h = host.Trim().TrimEnd('.').ToLowerInvariant(); + foreach (string raw in Hosts) + { + string p = raw.Trim().TrimEnd('.').ToLowerInvariant(); + if (p.Length == 0) continue; + bool hit = p.Contains('*') + ? Glob(h, p) + : h == p || (!IsIpv4(p) && h.EndsWith("." + p, StringComparison.Ordinal)); + if (!hit) continue; + matched = raw.Trim(); + return true; + } + return false; + } + + private static bool IsIpv4(string text) => + System.Net.IPAddress.TryParse(text, out System.Net.IPAddress? ip) && ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork; + + /// Case-insensitive match where '*' stands for any run of characters. + private static bool Glob(string text, string pattern) + { + string[] parts = pattern.Split('*'); + int pos = 0; + for (int i = 0; i < parts.Length; i++) + { + string part = parts[i]; + if (part.Length == 0) continue; + if (i == 0) + { + if (!text.StartsWith(part, StringComparison.OrdinalIgnoreCase)) return false; + pos = part.Length; + continue; + } + if (i == parts.Length - 1) + return text.Length - pos >= part.Length && text.EndsWith(part, StringComparison.OrdinalIgnoreCase); + int at = text.IndexOf(part, pos, StringComparison.OrdinalIgnoreCase); + if (at < 0) return false; + pos = at + part.Length; + } + return true; + } +} + /// A plugin's manifest (schema 1). Unknown JSON fields are ignored, so later schemas can add fields. public sealed class RynthPluginManifest { @@ -50,6 +118,11 @@ public sealed class RynthPluginManifest public string Description { get; set; } = ""; public string Homepage { get; set; } = ""; public string License { get; set; } = ""; + /// Set for a server plugin (one game server's features); null for every other plugin. + public RynthPluginServer? Server { get; set; } + + /// Most hosts or world names a server block may list (a manifest is read before every load). + public const int MaxServerPatterns = 16; /// Parses a manifest; throws with the reason when it isn't one. public static RynthPluginManifest Parse(string json) @@ -118,10 +191,50 @@ public sealed class RynthPluginManifest m.Dependencies.Add(dep); } } + + if (r.TryGetProperty("server", out JsonElement srv) && srv.ValueKind != JsonValueKind.Null) + m.Server = ParseServer(srv); return m; } } + /// The "server" block: an object with an id; hosts and worldNames are string arrays. + private static RynthPluginServer ParseServer(JsonElement srv) + { + if (srv.ValueKind != JsonValueKind.Object) + throw new InvalidDataException("the plugin manifest's server is not an object"); + var s = new RynthPluginServer + { + Id = Str(srv, "id").Trim().ToLowerInvariant(), + Name = Str(srv, "name").Trim(), + }; + if (s.Id.Length == 0 || s.Id.Length > 32) + throw new InvalidDataException("the plugin manifest's server has no id (or one over 32 characters)"); + foreach (char c in s.Id) + if (!(c is >= 'a' and <= 'z' || c is >= '0' and <= '9' || c == '-')) + throw new InvalidDataException($"the plugin manifest's server id '{s.Id}' may only have a-z, 0-9 and '-'"); + if (s.Name.Length == 0) s.Name = s.Id; + s.Hosts = Patterns(srv, "hosts"); + s.WorldNames = Patterns(srv, "worldNames"); + return s; + } + + private static List Patterns(JsonElement o, string name) + { + var list = new List(); + if (!o.TryGetProperty(name, out JsonElement a) || a.ValueKind == JsonValueKind.Null) return list; + if (a.ValueKind != JsonValueKind.Array) + throw new InvalidDataException($"the plugin manifest's server {name} is not an array"); + foreach (JsonElement e in a.EnumerateArray()) + { + string p = e.ValueKind == JsonValueKind.String ? (e.GetString() ?? "").Trim() : ""; + if (p.Length == 0 || p.Length > 128) continue; + if (list.Count >= MaxServerPatterns) break; + list.Add(p); + } + return list; + } + /// Parses, or returns null with the reason in . public static RynthPluginManifest? TryParse(string json, out string error) { @@ -155,6 +268,19 @@ public sealed class RynthPluginManifest if (Description.Length > 0) w.WriteString("description", Description); if (Homepage.Length > 0) w.WriteString("homepage", Homepage); if (License.Length > 0) w.WriteString("license", License); + if (Server != null) + { + w.WriteStartObject("server"); + w.WriteString("id", Server.Id); + w.WriteString("name", Server.Name); + w.WriteStartArray("hosts"); + foreach (string h in Server.Hosts) w.WriteStringValue(h); + w.WriteEndArray(); + w.WriteStartArray("worldNames"); + foreach (string n in Server.WorldNames) w.WriteStringValue(n); + w.WriteEndArray(); + w.WriteEndObject(); + } w.WriteEndObject(); } return Encoding.UTF8.GetString(ms.ToArray()); diff --git a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs index 6dfa0e0..eb4b39c 100644 --- a/src/RynthCore.PluginSdk/RynthCoreApiNative.cs +++ b/src/RynthCore.PluginSdk/RynthCoreApiNative.cs @@ -174,6 +174,11 @@ public struct RynthCoreApiNative public IntPtr RemoveClientObjectFn; // int RemoveClientObject(uint id) -> 1 removed, 2 queued, 0 refused, -1 unbound // v84: every property of an object (/ub propertydump), one record (ObjectProperties.TryParse) public IntPtr GetObjectPropertiesFn; // int GetObjectProperties(uint id, byte* buf, int size) -> record size (copied if <= size), 0 unknown, -1 bad args + // v85: answer the server's yes/no prompt (craft chance) without the client's dialog + public IntPtr ArmConfirmationFn; // int ArmConfirmation(uint type, int minPercent, int timeoutMs) -> 1 armed, 0 unavailable, -3 bad args + public IntPtr GetLastConfirmationFn; // int GetLastConfirmation(uint* type, uint* ctx, int* percent, int* outcome, int* ageMs) -> seq + // v86: which server this is, for every plugin (servers, verdicts, overrides, owning plugins) + public IntPtr GetServerStateJsonFn; // int GetServerStateJson(byte* buffer, int capacity) -> UTF-8 byte length (>= capacity: too small) } /// diff --git a/src/RynthCore.PluginSdk/RynthCoreHost.cs b/src/RynthCore.PluginSdk/RynthCoreHost.cs index c8bf994..9da7c4a 100644 --- a/src/RynthCore.PluginSdk/RynthCoreHost.cs +++ b/src/RynthCore.PluginSdk/RynthCoreHost.cs @@ -142,6 +142,8 @@ public readonly unsafe struct RynthCoreHost public bool HasGetCharacterTitles => _api.Version >= 75 && _api.GetCharacterTitlesFn != IntPtr.Zero; /// v75: (which server this is). public bool HasGetServerInfo => _api.Version >= 75 && _api.GetServerInfoFn != IntPtr.Zero; + /// v86: (the server list for every plugin). + public bool HasGetServerStateJson => _api.Version >= 86 && _api.GetServerStateJsonFn != IntPtr.Zero; /// v76: (close a corpse or chest like the client's window close). public bool HasCloseContainer => _api.Version >= 76 && _api.CloseContainerFn != IntPtr.Zero; /// v77: , and the UI callbacks @@ -182,6 +184,8 @@ public readonly unsafe struct RynthCoreHost public bool HasGetPluginExportJson => _api.Version >= 66 && _api.GetPluginExportJsonFn != IntPtr.Zero; // Version-checked first: on an older engine the field lies past the end of its API table. public bool HasGetMergeStackResult => _api.Version >= 81 && _api.GetMergeStackResultFn != IntPtr.Zero; + /// v85: and . + public bool HasConfirmationAnswers => _api.Version >= 85 && _api.ArmConfirmationFn != IntPtr.Zero && _api.GetLastConfirmationFn != IntPtr.Zero; public bool HasGetPluginInterface => _api.Version >= 68 && _api.GetPluginInterfaceFn != IntPtr.Zero; public bool HasGetLiveObjectIds => _api.Version >= 69 && _api.GetLiveObjectIdsFn != IntPtr.Zero; public bool HasGetLastUseDone => _api.Version >= 70 && _api.GetLastUseDoneFn != IntPtr.Zero; @@ -619,6 +623,60 @@ public readonly unsafe struct RynthCoreHost return status; } + /// Server yes/no prompt types (ConfirmationRequest 0x0274). + public static class ConfirmationKind + { + public const uint SwearAllegiance = 1; + public const uint AlterSkill = 2; + public const uint AlterAttribute = 3; + public const uint Fellowship = 4; + public const uint CraftInteraction = 5; + public const uint Augmentation = 6; + public const uint YesNo = 7; + } + + /// What happened to the last prompt (). + public static class ConfirmationOutcome + { + public const int None = 0; // no prompt this session + public const int Shown = 1; // not armed: the client showed its dialog + public const int Accepted = 2; // answered Yes for the plugin + public const int Declined = 3; // answered No: the server's percent was below the minimum + public const int SendFailed = 4; // armed, but the send failed: the client showed it + } + + /// + /// v81: answer the next server prompt of (a + /// ) that arrives within , + /// without the client opening its dialog: Yes when the server's "N percent chance" is at + /// least (or it is 0), else No. One-shot; timeoutMs <= 0 + /// disarms. 1 armed, 0 unavailable (engine before v81, sender or hook missing), -3 bad + /// arguments. + /// + public int ArmConfirmation(uint type, int minPercent, int timeoutMs) + { + if (!HasConfirmationAnswers) + return 0; + return ((delegate* unmanaged[Cdecl])_api.ArmConfirmationFn)(type, minPercent, timeoutMs); + } + + /// + /// v81: the last prompt the server sent. counts them (0 = none yet); + /// is -1 when the text has none; is a + /// . False on an engine before v81. + /// + public bool TryGetLastConfirmation(out int seq, out uint type, out int percent, out int outcome, out int ageMs) + { + seq = 0; type = 0; percent = -1; outcome = 0; ageMs = 0; + if (!HasConfirmationAnswers) + return false; + uint t = 0, ctx = 0; + int pct = -1, oc = 0, age = 0; + seq = ((delegate* unmanaged[Cdecl])_api.GetLastConfirmationFn)(&t, &ctx, &pct, &oc, &age); + type = t; percent = pct; outcome = oc; ageMs = age; + return true; + } + /// /// Gives an item to an NPC or another player by sending the F7B1 give /// GameAction (CM_Inventory::Event_GiveObjectRequest). This is the correct @@ -1054,6 +1112,37 @@ public readonly unsafe struct RynthCoreHost return true; } + /// + /// v86: which server this is, as JSON: every server the engine knows (built in, or declared + /// by a loaded server plugin) with its verdict, this character's override, the reason and the + /// plugin that owns its settings, plus "active" / "activePlugin" and the Diagnostics "pick". + /// Schema: RynthCore.Engine UI/Sections/ServerStateJson.cs. False when the engine predates + /// v86 or the call failed. Any thread; a few hundred bytes, so poll it (every second or two) + /// rather than caching it for a session: an override changes it live. + /// + public bool TryGetServerStateJson(out string json) + { + json = string.Empty; + if (!HasGetServerStateJson) + return false; + var fn = (delegate* unmanaged[Cdecl])_api.GetServerStateJsonFn; + int capacity = 2048; + for (int attempt = 0; attempt < 3; attempt++) + { + byte[] buffer = new byte[capacity]; + int length; + fixed (byte* p = buffer) length = fn(p, capacity); + if (length < 0) return false; + if (length < capacity) + { + json = System.Text.Encoding.UTF8.GetString(buffer, 0, length); + return true; + } + capacity = length + 256; + } + return false; + } + public bool TryGetObjectBoolProperty(uint objectId, uint stype, out bool value) { value = false; diff --git a/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets b/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets index bbb2dfd..f0a19f3 100644 --- a/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets +++ b/src/RynthCore.PluginSdk/build/RynthCore.PluginSdk.targets @@ -14,6 +14,9 @@ description RynthPluginDescription (default: Description) homepage RynthPluginHomepage (default: PackageProjectUrl) license RynthPluginLicense (default: PackageLicenseExpression) + server RynthPluginServerId (lower-case a-z 0-9 -), RynthPluginServerName, + RynthPluginServerHosts and RynthPluginServerWorldNames ('|'-separated): + a server plugin, loaded only for its own server (engine PluginManifestGate) 2. adds [assembly: RynthPluginManifest(minEngineApi)], which RynthPluginBase.MinimumApiVersion defaults to (the plugin's own runtime check, which also covers engines from before manifests), and generates RynthPluginInfo (Name, Version, MinEngineApi constants) in the @@ -33,7 +36,7 @@ - 84 + 86 <_RynthPluginManifestOn Condition="'$(RynthPluginMinEngineApi)' != '' and '$(RynthPluginManifest)' != 'false'">true @@ -79,6 +82,10 @@ public class RynthWritePluginManifest : Task public string Description { get; set; } public string Homepage { get; set; } public string License { get; set; } + public string ServerId { get; set; } + public string ServerName { get; set; } + public string ServerHosts { get; set; } + public string ServerWorldNames { get; set; } public ITaskItem[] Dependencies { get; set; } public string RootNamespace { get; set; } [Required] public string JsonPath { get; set; } @@ -126,6 +133,21 @@ public class RynthWritePluginManifest : Task AppendOpt(sb, "description", Description); AppendOpt(sb, "homepage", Homepage); AppendOpt(sb, "license", License); + + string serverId = (ServerId ?? "").Trim().ToLowerInvariant(); + string serverName = (ServerName ?? "").Trim(); + string[] hosts = Split(ServerHosts), worlds = Split(ServerWorldNames); + if (serverId.Length > 0) + { + foreach (char c in serverId) + if (!(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-')) + { Log.LogError("RynthPluginServerId '{0}' may only have a-z, 0-9 and '-'.", serverId); return false; } + if (hosts.Length + worlds.Length == 0) + { Log.LogError("RynthPluginServerId '{0}' needs RynthPluginServerHosts or RynthPluginServerWorldNames.", serverId); return false; } + if (serverName.Length == 0) serverName = serverId; + sb.Append(",\n \"server\": { \"id\": ").Append(Q(serverId)).Append(", \"name\": ").Append(Q(serverName)); + sb.Append(", \"hosts\": [").Append(JoinQ(hosts)).Append("], \"worldNames\": [").Append(JoinQ(worlds)).Append("] }"); + } sb.Append("\n}\n"); WriteIfChanged(JsonPath, sb.ToString()); @@ -139,6 +161,11 @@ public class RynthWritePluginManifest : Task cs.Append(" public const string Version = ").Append(Q((Version ?? "").Trim())).Append(";\n"); cs.Append(" /// The oldest engine API this plugin runs on (its manifest's minEngineApi).\n"); cs.Append(" public const uint MinEngineApi = ").Append(min).Append(";\n"); + cs.Append(" /// The manifest's server block (\"\" and empty lists for a plugin that isn't a server plugin).\n"); + cs.Append(" public const string ServerId = ").Append(Q(serverId)).Append(";\n"); + cs.Append(" public const string ServerName = ").Append(Q(serverId.Length > 0 ? serverName : "")).Append(";\n"); + cs.Append(" public static readonly string[] ServerHosts = { ").Append(serverId.Length > 0 ? JoinQ(hosts) : "").Append(" };\n"); + cs.Append(" public static readonly string[] ServerWorldNames = { ").Append(serverId.Length > 0 ? JoinQ(worlds) : "").Append(" };\n"); cs.Append("}\n"); WriteIfChanged(InfoSourcePath, cs.ToString()); return !Log.HasLoggedErrors; @@ -150,6 +177,25 @@ public class RynthWritePluginManifest : Task sb.Append(",\n ").Append(Q(key)).Append(": ").Append(Q(value.Trim())); } + // '|'-separated (MSBuild would split ';' lists into items), blanks dropped, at most 16. + private static string[] Split(string text) + { + var list = new List(); + foreach (string part in (text ?? "").Split('|')) + { + string p = part.Trim(); + if (p.Length > 0 && list.Count < 16) list.Add(p); + } + return list.ToArray(); + } + + private static string JoinQ(string[] values) + { + var sb = new StringBuilder(); + for (int i = 0; i < values.Length; i++) sb.Append(i == 0 ? "" : ", ").Append(Q(values[i])); + return sb.ToString(); + } + private static void WriteIfChanged(string path, string text) { if (File.Exists(path) && File.ReadAllText(path) == text) return; @@ -241,6 +287,8 @@ public class RynthEmbedPluginManifest : Task MaxEngineApi="$(RynthPluginMaxEngineApi)" SdkApiVersion="$(RynthCoreSdkApiVersion)" Author="$(RynthPluginAuthor)" Description="$(RynthPluginDescription)" Homepage="$(RynthPluginHomepage)" License="$(RynthPluginLicense)" + ServerId="$(RynthPluginServerId)" ServerName="$(RynthPluginServerName)" + ServerHosts="$(RynthPluginServerHosts)" ServerWorldNames="$(RynthPluginServerWorldNames)" Dependencies="@(RynthPluginDependency)" RootNamespace="$(RootNamespace)" JsonPath="$(_RynthPluginManifestJson)" InfoSourcePath="$(_RynthPluginInfoSource)" /> diff --git a/src/RynthCore.StatusAgent/AgentConfig.cs b/src/RynthCore.StatusAgent/AgentConfig.cs index 78372e6..a32b75f 100644 --- a/src/RynthCore.StatusAgent/AgentConfig.cs +++ b/src/RynthCore.StatusAgent/AgentConfig.cs @@ -61,7 +61,10 @@ internal sealed class AgentConfig /// Shared secret, required when is on: every route but /// /healthz needs Authorization: Bearer <token> or ?token=. Empty = - /// the server stays off, on any bind (it can stream the screens and click in them). + /// the server stays off, on any bind (it can stream the screens and click in them). A + /// other than 127.0.0.1/localhost needs at least + /// characters; an address that sends + /// bad tokens in a minute is locked out for 5 minutes. [JsonPropertyName("ServeToken")] public string ServeToken { get; set; } = ""; /// When true, also write the latest rollup to diff --git a/src/RynthCore.StatusAgent/LocalStatusServer.cs b/src/RynthCore.StatusAgent/LocalStatusServer.cs index 59b7442..006a6ef 100644 --- a/src/RynthCore.StatusAgent/LocalStatusServer.cs +++ b/src/RynthCore.StatusAgent/LocalStatusServer.cs @@ -40,6 +40,8 @@ internal sealed class LocalStatusServer : IDisposable // Connected /statusfeed push clients — each value is a per-socket wake signal. UpdateLatest pulses // them all; each socket's loop then sends the freshest _latest (coalescing rapid updates). private readonly ConcurrentDictionary _feedSignals = new(); + // Failed token checks per remote address (lockout after repeated guesses). + private readonly AuthThrottle _authThrottle = new(); private const int FeedKeepAliveMs = 20000; // re-send _latest at least this often (keepalive + missed-pulse cover) public bool Running { get; private set; } @@ -93,9 +95,11 @@ internal sealed class LocalStatusServer : IDisposable public bool TryStart(out string error) { // Never serve without a token, loopback included: every route but /healthz is behind it. - if (_token == null) + // A bind other PCs can reach also needs one long enough not to be guessed (ServeGuard). + string? tokenProblem = ServeGuard.TokenProblem(_prefix, _token); + if (tokenProblem != null) { - error = "no ServeToken set"; + error = tokenProblem; Running = false; return false; } @@ -141,7 +145,7 @@ internal sealed class LocalStatusServer : IDisposable // Diagnostic: log every /webrtc request + every CORS preflight, at the door (before any // auth/route processing), so we can see whether the app's offer POST even reaches us. if (path.StartsWith("/webrtc") || string.Equals(method, "OPTIONS", StringComparison.OrdinalIgnoreCase)) - AgentLog.Info($"[video] HTTP {method} {path} ua=\"{req.UserAgent}\""); + AgentLog.Info($"[video] HTTP {ServeGuard.LogSafe(method, 16)} {ServeGuard.LogSafe(path, 64)} ua=\"{ServeGuard.LogSafe(req.UserAgent)}\""); // CORS preflight for the POST /command path (a browser-hosted client may send it). if (string.Equals(method, "OPTIONS", StringComparison.OrdinalIgnoreCase)) @@ -199,7 +203,7 @@ internal sealed class LocalStatusServer : IDisposable int vpid = int.TryParse(req.QueryString["pid"], out int vv) ? vv : 0; if (vpid <= 0) { Write(res, 400, "application/json", "{\"error\":\"pid required\"}"u8.ToArray()); return; } if (!req.IsWebSocketRequest) { Write(res, 426, "application/json", "{\"error\":\"websocket required\"}"u8.ToArray()); return; } - AgentLog.Info($"[vsock] HTTP WS /video pid={vpid} ua=\"{req.UserAgent}\""); + AgentLog.Info($"[vsock] HTTP WS /video pid={vpid} ua=\"{ServeGuard.LogSafe(req.UserAgent)}\""); _ = HandleVideoSocketAsync(ctx, vpid); return; } @@ -209,7 +213,7 @@ internal sealed class LocalStatusServer : IDisposable { if (_token != null && !Authorized(req)) { Write(res, 401, "application/json", "{\"error\":\"unauthorized\"}"u8.ToArray()); return; } if (!req.IsWebSocketRequest) { Write(res, 426, "application/json", "{\"error\":\"websocket required\"}"u8.ToArray()); return; } - AgentLog.Info($"[feed] WS /statusfeed ua=\"{req.UserAgent}\""); + AgentLog.Info($"[feed] WS /statusfeed ua=\"{ServeGuard.LogSafe(req.UserAgent)}\""); _ = HandleStatusFeedAsync(ctx); return; } @@ -241,7 +245,13 @@ internal sealed class LocalStatusServer : IDisposable if (path == "/webrtc/stop") { _video.Stop(pid); Write(res, 200, "application/json", "{\"ok\":true}"u8.ToArray()); return; } if (path == "/webrtc/clientlog") // diagnostic: WKWebView reports its WebRTC errors/states here { - try { using var sr = new StreamReader(req.InputStream, req.ContentEncoding ?? Encoding.UTF8); AgentLog.Info($"[video] CLIENT pid={pid}: {sr.ReadToEnd()}"); } catch { } + try + { + if (!ServeGuard.TryReadBounded(req.InputStream, req.ContentLength64, ServeGuard.MaxClientLogBodyBytes, req.ContentEncoding, out string clientLog)) + { Write(res, 413, "application/json", "{\"error\":\"too large\"}"u8.ToArray()); return; } + AgentLog.Info($"[video] CLIENT pid={pid}: {ServeGuard.LogSafe(clientLog, 2000)}"); + } + catch { } Write(res, 200, "application/json", "{\"ok\":true}"u8.ToArray()); return; } @@ -526,9 +536,11 @@ internal sealed class LocalStatusServer : IDisposable { try { - string body; - using (var reader = new StreamReader(req.InputStream, req.ContentEncoding ?? Encoding.UTF8)) - body = reader.ReadToEnd(); + if (!ServeGuard.TryReadBounded(req.InputStream, req.ContentLength64, ServeGuard.MaxCommandBodyBytes, req.ContentEncoding, out string body)) + { + Write(res, 413, "application/json", "{\"error\":\"command too large\"}"u8.ToArray()); + return; + } int pid; string action; string value; using (var doc = JsonDocument.Parse(body)) @@ -614,9 +626,9 @@ internal sealed class LocalStatusServer : IDisposable // Keep-alives arrive ~5 a second per held client: debug only, so the log keeps the presses and releases. if (string.Equals(action, "moveKeepAlive", StringComparison.OrdinalIgnoreCase)) - AgentLog.Debug($"command queued: pid={pid} {action}={value}"); + AgentLog.Debug($"command queued: pid={pid} {action}={ServeGuard.LogSafe(value, 500)}"); else - AgentLog.Info($"command queued: pid={pid} {action}={value}"); + AgentLog.Info($"command queued: pid={pid} {action}={ServeGuard.LogSafe(value, 500)}"); Write(res, 202, "application/json", "{\"ok\":true}"u8.ToArray()); } catch (Exception ex) @@ -837,9 +849,11 @@ internal sealed class LocalStatusServer : IDisposable private void HandleWebRtcOffer(HttpListenerRequest req, HttpListenerResponse res, int pid) { - string body; - using (var sr = new StreamReader(req.InputStream, req.ContentEncoding ?? Encoding.UTF8)) - body = sr.ReadToEnd(); + if (!ServeGuard.TryReadBounded(req.InputStream, req.ContentLength64, ServeGuard.MaxOfferBodyBytes, req.ContentEncoding, out string body)) + { + Write(res, 413, "application/json", "{\"error\":\"offer too large\"}"u8.ToArray()); + return; + } string? offer = null; try { offer = JsonDocument.Parse(body).RootElement.GetProperty("sdp").GetString(); } catch { } if (string.IsNullOrEmpty(offer)) @@ -849,10 +863,10 @@ internal sealed class LocalStatusServer : IDisposable } // Diagnostic: confirm the offer arrived + from which client (Safari vs Chrome), and what H.264 // profile-level-id(s) it can RECEIVE. - AgentLog.Info($"[video] OFFER pid={pid} ua=\"{req.UserAgent}\""); + AgentLog.Info($"[video] OFFER pid={pid} ua=\"{ServeGuard.LogSafe(req.UserAgent)}\""); foreach (var ln in offer.Split('\n')) if (ln.StartsWith("m=video", StringComparison.Ordinal) || ln.Contains("profile-level-id", StringComparison.OrdinalIgnoreCase) || ln.Contains("candidate", StringComparison.OrdinalIgnoreCase)) - AgentLog.Info($"[video] offer> {ln.Trim()}"); + AgentLog.Info($"[video] offer> {ServeGuard.LogSafe(ln.Trim(), 300)}"); string? answer; try { answer = _video!.CreateAnswerAsync(pid, offer).GetAwaiter().GetResult(); } catch (Exception ex) { AgentLog.Warn($"[video] offer failed pid {pid}: {ex.Message}"); answer = null; } @@ -871,13 +885,24 @@ internal sealed class LocalStatusServer : IDisposable private bool Authorized(HttpListenerRequest req) { - string? header = req.Headers["Authorization"]; - if (header != null && header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase) && - TokenMatches(header.Substring("Bearer ".Length).Trim())) - return true; + // An address that kept guessing is refused outright for a while, right token or not. + IPAddress? from = req.RemoteEndPoint?.Address; + DateTime now = DateTime.UtcNow; + if (_authThrottle.IsBlocked(from, now)) return false; - string? q = req.QueryString["token"]; - return q != null && TokenMatches(q); + string? header = req.Headers["Authorization"]; + bool ok = header != null && header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase) && + TokenMatches(header.Substring("Bearer ".Length).Trim()); + if (!ok) + { + string? q = req.QueryString["token"]; + ok = q != null && TokenMatches(q); + } + + if (ok) _authThrottle.Succeed(from); + else if (_authThrottle.Fail(from, now)) + AgentLog.Warn($"auth: {from} locked out for {AuthThrottle.Lockout.TotalMinutes:0} min after {AuthThrottle.MaxFailures} bad tokens."); + return ok; } private bool TokenMatches(string candidate) diff --git a/src/RynthCore.StatusAgent/Program.cs b/src/RynthCore.StatusAgent/Program.cs index 4acfc86..418a009 100644 --- a/src/RynthCore.StatusAgent/Program.cs +++ b/src/RynthCore.StatusAgent/Program.cs @@ -64,6 +64,7 @@ var navAtlas = new NavAtlasService(cfg.NavAtlasPath); LocalStatusServer? server = null; WebRtcVideoService? video = null; // HD WebRTC video mode (opt-in); disposed in finally IconService? icons = null; // item-icon decoder (GET /icon); disposed in finally +string? serveTokenProblem = cfg.ServeHttp ? ServeGuard.TokenProblem(cfg.ServePrefix, cfg.ServeToken) : null; if (cfg.ServeHttp && string.IsNullOrWhiteSpace(cfg.ServeToken)) { // Same rule as DrakBot's remote: no token, no server, loopback included. The server can show @@ -72,8 +73,20 @@ if (cfg.ServeHttp && string.IsNullOrWhiteSpace(cfg.ServeToken)) AgentLog.Warn($"Set \"ServeToken\" in {configPath} and restart the agent. Use the same token as your"); AgentLog.Warn("DrakBot remote and one DrakRemote entry shows both."); } +else if (serveTokenProblem != null) +{ + // A bind other PCs reach (LAN, Tailscale) needs a token that can't be guessed. + AgentLog.Warn($"ServeHttp is on but {serveTokenProblem}, so the status server stays off."); + AgentLog.Warn($"Put a longer \"ServeToken\" in {configPath} (a random 24+ characters) and restart the agent."); +} else if (cfg.ServeHttp) { + if (!ServeGuard.IsLoopbackPrefix(cfg.ServePrefix)) + { + // HttpListener here is plain HTTP: the token and the screens cross the network unencrypted. + AgentLog.Warn($"ServePrefix {cfg.ServePrefix} is reachable from other PCs over plain HTTP: use it only"); + AgentLog.Warn("inside an encrypted network (Tailscale/WireGuard VPN), never forwarded to the internet."); + } string? commandDir = cfg.EnableRemoteControl ? Path.Combine(cfg.StatusDirectory, "commands") : null; VideoSocketService? videoSocket = null; if (cfg.EnableVideoStream) diff --git a/src/RynthCore.StatusAgent/RynthCore.StatusAgent.csproj b/src/RynthCore.StatusAgent/RynthCore.StatusAgent.csproj index 61355b8..0545856 100644 --- a/src/RynthCore.StatusAgent/RynthCore.StatusAgent.csproj +++ b/src/RynthCore.StatusAgent/RynthCore.StatusAgent.csproj @@ -19,7 +19,8 @@ RynthCore.StatusAgent RynthCore.StatusAgent true - 1.0.0 + + 1.0.1 diff --git a/src/RynthCore.StatusAgent/ServeGuard.cs b/src/RynthCore.StatusAgent/ServeGuard.cs new file mode 100644 index 0000000..4f3b876 --- /dev/null +++ b/src/RynthCore.StatusAgent/ServeGuard.cs @@ -0,0 +1,155 @@ +using System.Text; + +namespace RynthCore.StatusAgent; + +/// +/// The status server's guards for a bind other PCs can reach (LAN, Tailscale): a token long +/// enough to resist guessing, a lockout for an address that keeps guessing, bounded request +/// bodies, and client text made safe for the log. Pure code; compiled into tools/StatusAgentTests. +/// +internal static class ServeGuard +{ + /// Shortest ServeToken accepted when the prefix isn't loopback-only. + public const int MinRemoteTokenLength = 16; + + // Request bodies: a command is a few hundred bytes, a WebRTC offer a few KB. + public const int MaxCommandBodyBytes = 64 * 1024; + public const int MaxOfferBodyBytes = 256 * 1024; + public const int MaxClientLogBodyBytes = 16 * 1024; + + /// + /// True when (an HttpListener prefix, "http://host:port/") only + /// listens on this PC: 127.x.x.x, localhost or [::1]. "+", "*", a LAN address or a name = false. + /// + public static bool IsLoopbackPrefix(string? prefix) + { + if (string.IsNullOrWhiteSpace(prefix)) return false; + int scheme = prefix.IndexOf("://", StringComparison.Ordinal); + if (scheme < 0) return false; + string rest = prefix.Substring(scheme + 3); + string host; + if (rest.StartsWith('[')) + { + int close = rest.IndexOf(']'); + if (close < 0) return false; + host = rest.Substring(1, close - 1); + } + else + { + int end = rest.IndexOfAny(new[] { ':', '/' }); + host = end < 0 ? rest : rest.Substring(0, end); + } + if (host.Equals("localhost", StringComparison.OrdinalIgnoreCase) || host == "::1") return true; + return System.Net.IPAddress.TryParse(host, out var ip) + && ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork + && System.Net.IPAddress.IsLoopback(ip); + } + + /// Why the server must not start with this token on this prefix, or null when it may. + public static string? TokenProblem(string prefix, string? token) + { + if (string.IsNullOrWhiteSpace(token)) return "no ServeToken set"; + if (!IsLoopbackPrefix(prefix) && token.Trim().Length < MinRemoteTokenLength) + return $"ServeToken must be at least {MinRemoteTokenLength} characters when ServePrefix isn't 127.0.0.1/localhost"; + return null; + } + + /// + /// Reads a request body of at most . False (nothing read past the + /// limit) when the declared or actual length is over it. + /// + public static bool TryReadBounded(Stream input, long declaredLength, int maxBytes, Encoding? encoding, out string text) + { + text = ""; + if (declaredLength > maxBytes) return false; + var buffer = new byte[Math.Min(maxBytes + 1, 64 * 1024)]; + using var collected = new MemoryStream(); + int read; + while ((read = input.Read(buffer, 0, buffer.Length)) > 0) + { + if (collected.Length + read > maxBytes) return false; + collected.Write(buffer, 0, read); + } + text = (encoding ?? Encoding.UTF8).GetString(collected.GetBuffer(), 0, (int)collected.Length); + return true; + } + + /// Client-supplied text for one log line: control characters (CR/LF included) become spaces, capped at . + public static string LogSafe(string? text, int max = 200) + { + if (string.IsNullOrEmpty(text)) return ""; + var sb = new StringBuilder(Math.Min(text.Length, max) + 3); + foreach (char c in text) + { + if (sb.Length >= max) { sb.Append("..."); break; } + sb.Append(char.IsControl(c) ? ' ' : c); + } + return sb.ToString(); + } +} + +/// +/// Locks out an address after too many failed token checks: within +/// blocks it for (even with the right token, so a +/// guesser learns nothing). Loopback is never locked out (the owner's own tools). Thread-safe. +/// +internal sealed class AuthThrottle +{ + public const int MaxFailures = 10; + public static readonly TimeSpan Window = TimeSpan.FromMinutes(1); + public static readonly TimeSpan Lockout = TimeSpan.FromMinutes(5); + private const int MaxTracked = 4096; + + private sealed class Entry { public int Failures; public DateTime WindowStart; public DateTime BlockedUntil; } + + private readonly Dictionary _byAddress = new(StringComparer.Ordinal); + private readonly object _gate = new(); + + /// True while is locked out. + public bool IsBlocked(System.Net.IPAddress? address, DateTime nowUtc) + { + if (address == null || System.Net.IPAddress.IsLoopback(address)) return false; + lock (_gate) + return _byAddress.TryGetValue(address.ToString(), out Entry? e) && e.BlockedUntil > nowUtc; + } + + /// Counts a failed check; true when this one started a lockout (log it once). + public bool Fail(System.Net.IPAddress? address, DateTime nowUtc) + { + if (address == null || System.Net.IPAddress.IsLoopback(address)) return false; + lock (_gate) + { + string key = address.ToString(); + if (!_byAddress.TryGetValue(key, out Entry? e)) + { + if (_byAddress.Count >= MaxTracked) Prune(nowUtc); + e = new Entry { WindowStart = nowUtc }; + _byAddress[key] = e; + } + if (nowUtc - e.WindowStart > Window) { e.WindowStart = nowUtc; e.Failures = 0; } + if (++e.Failures < MaxFailures) return false; + e.Failures = 0; + e.WindowStart = nowUtc; + e.BlockedUntil = nowUtc + Lockout; + return true; + } + } + + /// A good token clears the address's count. + public void Succeed(System.Net.IPAddress? address) + { + if (address == null) return; + lock (_gate) _byAddress.Remove(address.ToString()); + } + + private void Prune(DateTime nowUtc) + { + foreach (var key in _byAddress.Where(kv => kv.Value.BlockedUntil <= nowUtc && nowUtc - kv.Value.WindowStart > Window) + .Select(kv => kv.Key).ToList()) + _byAddress.Remove(key); + // Still full (a flood of blocked addresses): drop the oldest windows rather than grow without bound. + if (_byAddress.Count >= MaxTracked) + foreach (var key in _byAddress.OrderBy(kv => kv.Value.WindowStart).Take(_byAddress.Count / 4).Select(kv => kv.Key).ToList()) + _byAddress.Remove(key); + } +} diff --git a/tools/EngineSettingsTests/EngineSettingsTests.csproj b/tools/EngineSettingsTests/EngineSettingsTests.csproj index 4201d3e..afc8f70 100644 --- a/tools/EngineSettingsTests/EngineSettingsTests.csproj +++ b/tools/EngineSettingsTests/EngineSettingsTests.csproj @@ -24,6 +24,9 @@ + + + diff --git a/tools/EngineSettingsTests/Program.cs b/tools/EngineSettingsTests/Program.cs index 8c506f3..4785290 100644 --- a/tools/EngineSettingsTests/Program.cs +++ b/tools/EngineSettingsTests/Program.cs @@ -52,6 +52,7 @@ namespace EngineSettingsTests Run(nameof(SaveLeavesMalformedFileAlone), SaveLeavesMalformedFileAlone); Run(nameof(MaxHotReloadsReadAndKept), MaxHotReloadsReadAndKept); Run(nameof(CloseOnServerDisconnectDefaultOnAndSaved), CloseOnServerDisconnectDefaultOnAndSaved); + Run(nameof(IltServerNamesEdit), IltServerNamesEdit); } finally { @@ -88,6 +89,8 @@ namespace EngineSettingsTests if (!RynthCore.Engine.Compatibility.AutoIdPolicy.TryParseMode(args[1], out var aim)) throw new ArgumentException(args[1]); EngineSettings.AutoIdMode = aim; break; + case "ilt-add": Console.WriteLine("Changed=" + EngineSettings.EditIltServerName(args[1], add: true)); break; + case "ilt-remove": Console.WriteLine("Changed=" + EngineSettings.EditIltServerName(args[1], add: false)); break; case "dump": Console.WriteLine("AutoIdMode=" + EngineSettings.AutoIdMode); Console.WriteLine("PluginPaths=" + string.Join("|", EngineSettings.PluginPaths)); @@ -97,6 +100,7 @@ namespace EngineSettingsTests Console.WriteLine("ServerMessageStream=" + EngineSettings.ServerMessageStream); Console.WriteLine("MaxHotReloads=" + EngineSettings.MaxHotReloads); Console.WriteLine("CloseOnServerDisconnect=" + EngineSettings.CloseOnServerDisconnect); + Console.WriteLine("IltServerNames=" + (EngineSettings.IltServerNames is { } n ? string.Join("|", n) : "(none)")); break; default: throw new ArgumentException(args[0]); } @@ -359,6 +363,32 @@ namespace EngineSettingsTests } } + // /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. + private static void IltServerNamesEdit() + { + string dir = NewDir("iltnames"); + string path = Path.Combine(dir, "engine.json"); + File.WriteAllText(path, LauncherFile); + JsonElement before = ReadJson(path); + + Eq(DumpValue(RunChild(path, "dump").Out, "IltServerNames"), "(none)", "no list in the file"); + Eq(DumpValue(RunChild(path, "ilt-add", "Frosthaven").Out, "Changed"), "True", "add"); + string defaults = string.Join("|", RynthCore.Engine.Compatibility.IltDetect.DefaultServerNames); + Eq(DumpValue(RunChild(path, "dump").Out, "IltServerNames"), defaults + "|Frosthaven", "the defaults kept, the new one added"); + Eq(Raw(ReadJson(path).GetProperty("LauncherWindow")), Raw(before.GetProperty("LauncherWindow")), "the launcher's keys kept"); + NoTempFilesLeft(dir); + + Eq(DumpValue(RunChild(path, "ilt-add", "FROSTHAVEN").Out, "Changed"), "False", "adding again (any case) changes nothing"); + Eq(DumpValue(RunChild(path, "ilt-remove", "nope").Out, "Changed"), "False", "removing an unknown pattern changes nothing"); + Eq(DumpValue(RunChild(path, "ilt-add", " ").Out, "Changed"), "False", "an empty pattern is refused"); + Eq(DumpValue(RunChild(path, "ilt-add", new string('x', EngineSettings.MaxIltServerNameLength + 1)).Out, "Changed"), "False", + "an overlong pattern is refused"); + Eq(DumpValue(RunChild(path, "ilt-remove", "frosthaven").Out, "Changed"), "True", "remove (any case)"); + Eq(DumpValue(RunChild(path, "dump").Out, "IltServerNames"), defaults, "back to the defaults"); + } + /// The value of a "Name=value" line of the child's dump output ("" if none). private static string DumpValue(string output, string name) { diff --git a/tools/LauncherSettingsTests/LauncherSettingsTests.csproj b/tools/LauncherSettingsTests/LauncherSettingsTests.csproj index c5fd01b..f479758 100644 --- a/tools/LauncherSettingsTests/LauncherSettingsTests.csproj +++ b/tools/LauncherSettingsTests/LauncherSettingsTests.csproj @@ -27,6 +27,7 @@ + diff --git a/tools/LauncherSettingsTests/Program.cs b/tools/LauncherSettingsTests/Program.cs index 22c2735..b966787 100644 --- a/tools/LauncherSettingsTests/Program.cs +++ b/tools/LauncherSettingsTests/Program.cs @@ -278,6 +278,37 @@ internal static class Program AppSettingsStore.Save(loaded); 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"); + }); } finally { diff --git a/tools/NetMessageTests/NetMessageTests.csproj b/tools/NetMessageTests/NetMessageTests.csproj index 2f77613..5f898b5 100644 --- a/tools/NetMessageTests/NetMessageTests.csproj +++ b/tools/NetMessageTests/NetMessageTests.csproj @@ -36,6 +36,7 @@ + diff --git a/tools/NetMessageTests/VaultWireTests.cs b/tools/NetMessageTests/VaultWireTests.cs index 6628bbf..40ee561 100644 --- a/tools/NetMessageTests/VaultWireTests.cs +++ b/tools/NetMessageTests/VaultWireTests.cs @@ -33,6 +33,18 @@ internal static unsafe partial class Program Check(!AelrynthVaultWire.TryParse("~ael1 {\"t\":\"mule\",\"ready\":tru", out _), "damaged JSON is refused"); Check(AelrynthVaultWire.IsUnknownCommand("Unknown command: mule-data"), "ACE's reply for a missing command"); Check(!AelrynthVaultWire.IsUnknownCommand("Unknown command: mastery-data"), "another command's reply is not ours"); + + Case("vault wire: a player's copy of a server line is not ours"); + Check(!AelrynthVaultWire.IsMuleLine("Bob says, \"" + page + "\""), "spoken data line"); + Check(!AelrynthVaultWire.IsMuleLine("Bob " + page), "emoted data line (no quote)"); + Check(!AelrynthVaultWire.TryParse("[Allegiance] Bob says, \"" + page + "\"", out _), "a channel's copy does not parse"); + Check(AelrynthVaultWire.IsMuleLine(" " + page), "leading whitespace is fine"); + Check(AelrynthVaultWire.TryParse(" " + page, out _), "and parses"); + Check(!AelrynthVaultWire.IsUnknownCommand("Bob tells you, \"Unknown command: mule-data\""), "a told refusal"); + Check(!AelrynthVaultWire.IsUnknownCommand("Unknown command: mule-data-extra"), "a longer command name"); + Check(AelrynthVaultWire.IsUnknownCommand("Unknown command: /mule-data"), "a slash before the name is allowed"); + Check(ChatOrigin.IsPlayerAuthored(ChatOrigin.Emote) && ChatOrigin.IsPlayerAuthored(ChatOrigin.Tell), "emotes and tells are players'"); + Check(!ChatOrigin.IsPlayerAuthored(0) && !ChatOrigin.IsPlayerAuthored(0x0F), "Broadcast and Help (ACE's replies) are not"); Eq(AelrynthVaultWire.PageCommand(1), "@mule-data", "first page is the bare command"); Eq(AelrynthVaultWire.PageCommand(3), "@mule-data 3", "later pages say which"); diff --git a/tools/PluginManifestTests/Program.cs b/tools/PluginManifestTests/Program.cs index c2b537b..39a8621 100644 --- a/tools/PluginManifestTests/Program.cs +++ b/tools/PluginManifestTests/Program.cs @@ -50,6 +50,12 @@ internal static class Program Run(nameof(ReadsResourceFromPe32AndPe32Plus), ReadsResourceFromPe32AndPe32Plus); Run(nameof(NoResourceAndNotAPe), NoResourceAndNotAPe); Run(nameof(GatePlanFromFiles), GatePlanFromFiles); + Run(nameof(ServerBlockParsesAndRoundTrips), ServerBlockParsesAndRoundTrips); + Run(nameof(ServerBlockRejectsBadIds), ServerBlockRejectsBadIds); + Run(nameof(ServerHostMatching), ServerHostMatching); + Run(nameof(ServerGateKeepsOnlyTheHostsPlugin), ServerGateKeepsOnlyTheHostsPlugin); + Run(nameof(ServerGateFailsOpen), ServerGateFailsOpen); + Run(nameof(ServerGatePlanFromFiles), ServerGatePlanFromFiles); Run(nameof(SdkApiVersionCannotDrift), SdkApiVersionCannotDrift); Run(nameof(TrainingStructsMirror), TrainingStructsMirror); Run(nameof(ContainerOrderSlots), ContainerOrderSlots); @@ -441,6 +447,117 @@ internal static class Program Check(none.Log.Any(l => l.Contains("no plugin has a manifest")), "said once"); } + // ── Server plugins (the manifest's "server" block and the load gate) ──── + + private static RynthPluginManifest S(string name, string id, string[] hosts, params string[] worlds) + { + var m = M(name); + m.Server = new RynthPluginServer { Id = id, Name = name, Hosts = hosts.ToList(), WorldNames = worlds.ToList() }; + return m; + } + + private static void ServerBlockParsesAndRoundTrips() + { + var m = RynthPluginManifest.Parse(""" + { "name": "RynthColdeve", "minEngineApi": 66, + "server": { "id": "Coldeve", "name": "Coldeve", "hosts": ["play.coldeve.ac", "", 5], "worldNames": ["Coldeve"] } } + """); + Check(m.Server != null, "server block read"); + Eq(m.Server!.Id, "coldeve", "id lower-cased"); + Eq(string.Join(",", m.Server.Hosts), "play.coldeve.ac", "blank and non-string hosts dropped"); + Eq(string.Join(",", m.Server.WorldNames), "Coldeve", "world names"); + var back = RynthPluginManifest.Parse(m.ToJson()); + Eq(back.Server?.Id, "coldeve", "round trip id"); + Eq(back.Server?.Hosts.Count, 1, "round trip hosts"); + Check(RynthPluginManifest.Parse("""{ "name": "RynthAi" }""").Server == null, "no block, not a server plugin"); + Check(!M("RynthAi").ToJson().Contains("\"server\""), "no server block written for other plugins"); + } + + private static void ServerBlockRejectsBadIds() + { + string[] bad = + { + """{ "name": "X", "server": "coldeve" }""", + """{ "name": "X", "server": { "name": "No id" } }""", + """{ "name": "X", "server": { "id": "has space" } }""", + """{ "name": "X", "server": { "id": "ok", "hosts": "not-an-array" } }""", + }; + foreach (string json in bad) + Check(RynthPluginManifest.TryParse(json, out string err) == null && err.Length > 0, $"refused: {json}"); + } + + private static void ServerHostMatching() + { + var ilt = new RynthPluginServer { Id = "ilt", Hosts = { "infiniteleaftide.online" } }; + Check(ilt.MatchesHost("game.infiniteleaftide.online", out string hit) && hit == "infiniteleaftide.online", "a host under the name"); + Check(ilt.MatchesHost("INFINITELEAFTIDE.ONLINE.", out _), "case and trailing dot ignored"); + Check(!ilt.MatchesHost("notinfiniteleaftide.online", out _), "not a suffix without the dot"); + var ip = new RynthPluginServer { Id = "aelrynth", Hosts = { "144.217.84.148" } }; + Check(ip.MatchesHost("144.217.84.148", out _), "an IP matches itself"); + Check(!ip.MatchesHost("1.144.217.84.148", out _), "an IP never matches as a suffix"); + var wild = new RynthPluginServer { Id = "x", Hosts = { "*.ddns.net" } }; + Check(wild.MatchesHost("frostcull.ddns.net", out _), "wildcard"); + Check(!wild.MatchesHost("", out _), "no host, no match"); + } + + private static void ServerGateKeepsOnlyTheHostsPlugin() + { + var list = new List + { + C("RynthAi", M("RynthAi")), + C("RynthChat"), + C("RynthColdeve", S("RynthColdeve", "coldeve", new[] { "play.coldeve.ac" }, "Coldeve")), + C("RynthLeafDawn", S("RynthLeafDawn", "leafdawn", new[] { "leafdawn.hopto.org" }, "LeafDawn")), + C("RynthLeafdawning", S("RynthLeafdawning", "leafdawning", new[] { "leafdawning.duckdns.org" }, "Leafdawning")), + }; + var log = new List(); + HashSet skip = PluginManifestGate.SelectServerPlugins(list, "leafdawn.hopto.org", false, log); + Eq(skip.Count, 2, "the two other server plugins are left out"); + Check(skip.Contains(list[2].Key) && skip.Contains(list[4].Key), "Coldeve and Leafdawning left out"); + Check(!skip.Contains(list[0].Key) && !skip.Contains(list[1].Key), "other plugins always load"); + Check(log.Any(l => l.Contains("RynthColdeve") && l.Contains("not loaded")), "logged why"); + Eq(PluginManifestGate.SelectServerPlugins(list, "leafdawn.hopto.org", true, log).Count, 0, "LoadAllServerPlugins keeps every one"); + } + + private static void ServerGateFailsOpen() + { + var list = new List + { + C("RynthColdeve", S("RynthColdeve", "coldeve", new[] { "play.coldeve.ac" })), + C("RynthFrostcull", S("RynthFrostcull", "frostcull", new[] { "frostcull.ddns.net" })), + }; + var log = new List(); + Eq(PluginManifestGate.SelectServerPlugins(list, "", false, log).Count, 0, "no connect host: all load"); + Eq(PluginManifestGate.SelectServerPlugins(list, "10.0.0.5", false, log).Count, 0, "a host nobody lists: all load"); + Check(log.Any(l => l.Contains("none lists host 10.0.0.5")), "said why"); + } + + private static void ServerGatePlanFromFiles() + { + string dir = Path.Combine(_root, "servers"); + Directory.CreateDirectory(dir); + string P(string name) => Path.Combine(dir, $"RynthCore.Plugin.{name}.dll"); + File.Copy(ThisDll, P("RynthAi")); + Embed(P("RynthAi"), M("RynthAi").ToJson()); + File.Copy(ThisDll, P("RynthILT")); + Embed(P("RynthILT"), S("RynthILT", "ilt", new[] { "infiniteleaftide.online" }, "*Leaftide*").ToJson()); + File.Copy(ThisDll, P("RynthAelrynth")); + Embed(P("RynthAelrynth"), S("RynthAelrynth", "aelrynth", new[] { "144.217.84.148" }, "Aelrynth*").ToJson()); + + var paths = new[] { P("RynthAi"), P("RynthILT"), P("RynthAelrynth") }; + PluginManifestGate.LoadPlan onIlt = PluginManifestGate.Plan(paths, Api, null, "game.infiniteleaftide.online"); + Eq(string.Join(",", onIlt.Load.Select(l => RynthPluginManifest.NameFromFile(l.Path))), "RynthAi,RynthILT", "on ILT"); + Eq(onIlt.SkippedForServer.Count, 1, "Aelrynth's plugin skipped"); + // The skipped one keeps its manifest: Options > Diagnostics lists its server, and forcing it loads it. + Eq(onIlt.SkippedServerPlugins.Count, 1, "skipped server plugin kept with its manifest"); + Eq(onIlt.SkippedServerPlugins[0].Manifest.Server?.Id ?? "", "aelrynth", "its server id"); + Eq(onIlt.SkippedServerPlugins[0].Path, P("RynthAelrynth"), "its path"); + Eq(onIlt.Refused.Count, 0, "skipping is not a refusal (no chat notice)"); + Check(onIlt.Log.Any(l => l.Contains("server ilt")), "the manifest line names the server"); + PluginManifestGate.LoadPlan onAelrynth = PluginManifestGate.Plan(paths, Api, null, "144.217.84.148"); + Eq(string.Join(",", onAelrynth.Load.Select(l => RynthPluginManifest.NameFromFile(l.Path))), "RynthAi,RynthAelrynth", "on Aelrynth"); + } + // ── The SDK's version ──────────────────────────────────────────────────── private static void SdkApiVersionCannotDrift() @@ -474,29 +591,36 @@ internal static class Program Eq((int)Marshal.OffsetOf(f.Name), (int)Marshal.OffsetOf(f.Name), "TrainingEntryNative." + f.Name + " offset"); Eq(RynthCore.PluginSdk.TrainingInfoFlags.Busy, RynthCore.Engine.Plugins.TrainingInfoFlags.Busy, "info flag bits"); Eq(RynthCore.PluginSdk.TrainingEntryFlags.Trainable, RynthCore.Engine.Plugins.TrainingEntryFlags.Trainable, "entry flag bits"); - // The three v79 slots follow v78's, then v80's two and v81's GetMergeStackResultFn (v82-v84 follow). - var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).SkipLast(4).TakeLast(6).ToArray(); + // The three v79 slots follow v78's, then v80's two and v81's GetMergeStackResultFn (v82's one, v83's two, + // v84's one, v85's two and v86's one come after: 7 slots). + var names = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).SkipLast(7).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(4).TakeLast(6).ToArray(); + var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SkipLast(7).TakeLast(6).ToArray(); Check(sdkNames.SequenceEqual(names), "SDK v79, v80 and v81 slots in the same order"); } // v80: GetContainerOrder and PutItemInContainer come right before v81's slot, engine and SDK alike; - // v81: GetMergeStackResult, then v82: SalvageDirect, v83's two and v84's GetObjectProperties last. The whole table has the same field names in the same - // order on both sides, and the same size. + // v81: GetMergeStackResult, v82: SalvageDirect, v83: the ghost-creature pair, v84: GetObjectProperties, + // v85: the confirmation pair, v86: GetServerStateJson last. + // The whole table has the same field names in the same order on both sides, and the same size. private static void ContainerOrderSlots() { - 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(); + var allNames = typeof(RynthCore.Engine.Plugins.RynthCoreAPI).GetFields().Select(f => f.Name).ToArray(); + // v86: GetServerStateJson ends the table; the checks below count back from the v85 slots before it. + Check(allNames.Last() == "GetServerStateJsonFn", "v86 slot last: " + allNames.Last()); + var names = allNames.SkipLast(1).ToArray(); + var sdkNames = typeof(RynthCore.PluginSdk.RynthCoreApiNative).GetFields().Select(f => f.Name).SkipLast(1).ToArray(); // v81's GetMergeStackResultFn follows v80's two slots. - Check(names.SkipLast(5).TakeLast(2).SequenceEqual(new[] { "GetContainerOrderFn", "PutItemInContainerFn" }), "v80 slots before v81's to v84's: " + string.Join(",", names.SkipLast(5).TakeLast(2))); - Check(sdkNames.SkipLast(5).TakeLast(2).SequenceEqual(names.SkipLast(5).TakeLast(2)), "SDK v80 slots in the same order"); - Check(names.SkipLast(3).Last() == "SalvageDirectFn", "v82 slot before v83's"); - // v83: GetObjectServerAge and RemoveClientObject (ghost creatures), then v84's slot. - Check(names.SkipLast(1).TakeLast(2).SequenceEqual(new[] { "GetObjectServerAgeFn", "RemoveClientObjectFn" }), "v83 slots before v84's: " + string.Join(",", names.SkipLast(1).TakeLast(2))); - // v84: GetObjectProperties ends the table (every property of an object, /ub propertydump). - Check(names.Last() == "GetObjectPropertiesFn", "v84 slot last: " + names.Last()); + Check(names.SkipLast(7).TakeLast(2).SequenceEqual(new[] { "GetContainerOrderFn", "PutItemInContainerFn" }), "v80 slots before v81's to v85's: " + string.Join(",", names.SkipLast(7).TakeLast(2))); + Check(sdkNames.SkipLast(7).TakeLast(2).SequenceEqual(names.SkipLast(7).TakeLast(2)), "SDK v80 slots in the same order"); + Check(names.SkipLast(5).Last() == "SalvageDirectFn", "v82 slot before v83's"); + // v83: GetObjectServerAge and RemoveClientObject (ghost creatures). + Check(names.SkipLast(3).TakeLast(2).SequenceEqual(new[] { "GetObjectServerAgeFn", "RemoveClientObjectFn" }), "v83 slots before v84's: " + string.Join(",", names.SkipLast(3).TakeLast(2))); + // v84: GetObjectProperties (every property of an object, /ub propertydump). + Check(names.SkipLast(2).Last() == "GetObjectPropertiesFn", "v84 slot before v85's: " + names.SkipLast(2).Last()); + // v85: ArmConfirmation and GetLastConfirmation (answer the craft-chance prompt), before v86's slot. + Check(names.TakeLast(2).SequenceEqual(new[] { "ArmConfirmationFn", "GetLastConfirmationFn" }), "v85 slots before v86's: " + string.Join(",", names.TakeLast(2))); 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"), @@ -511,6 +635,14 @@ internal static class Program (int)Marshal.OffsetOf("GetObjectPropertiesFn"), "GetObjectPropertiesFn offset"); Eq((int)Marshal.OffsetOf("GetObjectPropertiesFn"), (int)Marshal.OffsetOf("RemoveClientObjectFn") + IntPtr.Size, "GetObjectPropertiesFn right after RemoveClientObjectFn"); + Eq((int)Marshal.OffsetOf("ArmConfirmationFn"), + (int)Marshal.OffsetOf("ArmConfirmationFn"), "ArmConfirmationFn offset"); + Eq((int)Marshal.OffsetOf("ArmConfirmationFn"), + (int)Marshal.OffsetOf("GetObjectPropertiesFn") + IntPtr.Size, "ArmConfirmationFn right after GetObjectPropertiesFn"); + Eq((int)Marshal.OffsetOf("GetLastConfirmationFn"), + (int)Marshal.OffsetOf("GetLastConfirmationFn"), "GetLastConfirmationFn offset"); + Eq((int)Marshal.OffsetOf("GetServerStateJsonFn"), + (int)Marshal.OffsetOf("GetServerStateJsonFn"), "GetServerStateJsonFn offset"); } private sealed class ProbePlugin : RynthCore.PluginCore.RynthPluginBase { } diff --git a/tools/SectionsTests/Program.cs b/tools/SectionsTests/Program.cs new file mode 100644 index 0000000..1e64c24 --- /dev/null +++ b/tools/SectionsTests/Program.cs @@ -0,0 +1,515 @@ +using RynthCore.Engine.Compatibility; +using RynthCore.Engine.UI.Sections; + +namespace SectionsTests; + +/// +/// The Mini Remote's sections, offline: per-character server overrides (server_force.txt), +/// plugin manifests (RynthPluginGetSectionsJson) and the section catalog built from them. +/// +internal static class Program +{ + private static int _checks, _failed; + private static string _case = ""; + + private static int Main() + { + ForceText(); + ForceFile(); + ManifestBasics(); + ManifestRejects(); + ManifestLimits(); + CatalogCore(); + CatalogServers(); + CatalogPluginSections(); + DeclaredServers(); + SelectionPlan(); + NotLoadedServerList(); + SelectionCurrentPick(); + SelectionActiveAndOwner(); + StateJson(); + RatesRises(); + RatesBank(); + RatesChat(); + + Console.WriteLine(); + Console.WriteLine($"{_checks - _failed}/{_checks} checks passed."); + if (_checks == 0) { Console.WriteLine("ABORT: no checks ran."); return 1; } + Console.WriteLine(_failed == 0 ? "ALL SECTIONS TESTS PASSED." : $"{_failed} FAILED."); + return _failed == 0 ? 0 : 1; + } + + // ── Overrides ────────────────────────────────────────────────────── + + private static void ForceText() + { + Case("force text"); + Check(ServerForceText.TryParse("on", out ServerForce m) && m == ServerForce.On, "on"); + Check(ServerForceText.TryParse(" OFF ", out m) && m == ServerForce.Off, "OFF, padded"); + Check(ServerForceText.TryParse("auto", out m) && m == ServerForce.Auto, "auto"); + Check(!ServerForceText.TryParse("maybe", out _) && !ServerForceText.TryParse(null, out _), "junk and null"); + Check(ServerForceText.Name(ServerForce.On) == "on" && ServerForceText.Name(ServerForce.Auto) == "auto", "names"); + Check(ServerForceText.Apply(ServerForce.On, false), "On wins over not detected"); + Check(!ServerForceText.Apply(ServerForce.Off, true), "Off wins over detected"); + Check(ServerForceText.Apply(ServerForce.Auto, true) && !ServerForceText.Apply(ServerForce.Auto, false), "Auto follows detection"); + } + + private static void ForceFile() + { + Case("force file"); + var f = new ServerForceFile(); + Check(f.Set("Kelpie@ILT", "ilt", ServerForce.On), "set on"); + Check(!f.Set("Kelpie@ILT", "ilt", ServerForce.On), "same value again is no change"); + Check(f.Get("kelpie@ilt", "ILT") == ServerForce.On, "keys are case-insensitive"); + Check(f.Get("Other", "ilt") == ServerForce.Auto, "another character is Auto"); + Check(f.Set("Kelpie@ILT", "aelrynth", ServerForce.Off), "a second server"); + Check(f.For("Kelpie@ILT").Count == 2, "For lists both"); + + var round = ServerForceFile.Parse(f.Write().Split('\n')); + Check(round.Get("Kelpie@ILT", "ilt") == ServerForce.On && round.Get("Kelpie@ILT", "aelrynth") == ServerForce.Off, "round trip"); + + Check(f.Set("Kelpie@ILT", "ilt", ServerForce.Auto) && f.Get("Kelpie@ILT", "ilt") == ServerForce.Auto, "Auto removes"); + Check(!f.Set("Kelpie@ILT", "ilt", ServerForce.Auto), "removing again is no change"); + Check(!f.Set("bad\tkey", "ilt", ServerForce.On) && !f.Set("k", "a\nb", ServerForce.On), "tabs and line breaks refused"); + Check(!f.Set(new string('x', ServerForceFile.MaxFieldLength + 1), "ilt", ServerForce.On), "overlong key refused"); + Check(!f.Set("", "ilt", ServerForce.On) && !f.Set("k", " ", ServerForce.On), "empty fields refused"); + + var damaged = ServerForceFile.Parse(new[] { "# comment", "", "a\tilt", "a\tilt\tmaybe", "a\tilt\tauto", "b\tilt\ton\textra" }); + Check(damaged.For("a").Count == 0, "short, unknown and auto lines are skipped"); + Check(damaged.Get("b", "ilt") == ServerForce.On, "extra fields are ignored"); + Check(ServerForceFile.Parse(null).For("a").Count == 0, "no file"); + } + + // ── Manifests ────────────────────────────────────────────────────── + + private const string GoodManifest = """ + { + "version": 1, + "servers": [ { "id": "ilt", "name": "Infinite Leaftide", "worldNames": ["*Leaftide*"], "hosts": ["infiniteleaftide.online"] }, + { "id": "Frost-Haven", "name": "Frosthaven", "worldNames": ["Frosthaven"], "hosts": [] } ], + "sections": [ { "id": "quests", "label": "Quests", "order": 650 } ], + "contributions": [ + { "section": "pets", "server": "", "label": "Pets", "surface": "section:pets", "primary": true, "width": 560, "height": 580 }, + { "section": "skills", "server": "ilt", "label": "Progression", "command": "/rc progression", "tooltip": "line one\nline two" }, + { "section": "quests", "label": "Quests", "surface": "section:quests", "primary": true }, + { "section": "char", "server": "ilt", "label": "Off now", "command": "/ra x", "enabled": false, "note": "Not reported." } + ], + "future": { "ignored": true } + } + """; + + private static void ManifestBasics() + { + Case("manifest basics"); + SectionManifest m = SectionManifestParser.Parse("RynthAi", GoodManifest, out string err); + Check(err.Length == 0, "no error: " + err); + Check(m.Plugin == "RynthAi", "plugin name kept"); + Check(m.Servers.Length == 2 && m.Servers[1].Id == "frost-haven", "server ids lower-cased"); + Check(m.Servers[0].WorldNames.SequenceEqual(new[] { "*Leaftide*" }) && m.Servers[0].Hosts.Length == 1, "server lists"); + Check(m.Sections.Length == 1 && m.Sections[0].Order == 650, "a plugin section with its order"); + Check(m.Contributions.Length == 4, "four contributions"); + SectionContribution pets = m.Contributions[0]; + Check(pets.IsSurface && pets.IsUniversal && pets.Primary && pets.Width == 560 && pets.Height == 580, "surface fields"); + SectionContribution prog = m.Contributions[1]; + Check(!prog.IsSurface && prog.Command == "/rc progression" && prog.Server == "ilt" && prog.Enabled, "command fields"); + Check(prog.Tooltip.Contains('\n'), "tooltips keep line breaks"); + Check(m.Contributions[2].Order == 1000, "order defaults to 1000"); + Check(!m.Contributions[3].Enabled && m.Contributions[3].Note == "Not reported.", "disabled with a note"); + } + + private static void ManifestRejects() + { + Case("manifest rejects"); + Check(SectionManifestParser.Parse("p", null, out string e).Contributions.Length == 0 && e == "empty", "null"); + Check(SectionManifestParser.Parse("p", "[1,2]", out e).Contributions.Length == 0 && e.Length > 0, "not an object"); + Check(SectionManifestParser.Parse("p", "{ bad", out e).Contributions.Length == 0 && e.StartsWith("bad JSON"), "bad JSON"); + Check(SectionManifestParser.Parse("p", """{"version":0}""", out e).Contributions.Length == 0 && e.Length > 0, "version 0"); + + string deep = new string('[', 40) + new string(']', 40); + Check(SectionManifestParser.Parse("p", "{\"x\":" + deep + "}", out e).Contributions.Length == 0 && e.Length > 0, "too deep"); + + SectionManifest m = SectionManifestParser.Parse("p", """ + { "contributions": [ + { "section": "Bad Id!", "label": "x", "command": "/a" }, + { "section": "char", "label": "", "command": "/a" }, + { "section": "char", "label": "no action" }, + { "section": "char", "label": "not a command", "command": "say hi" }, + { "section": "char", "label": "two lines", "command": "/a\n/b" }, + { "section": "char", "label": "popout", "surface": "x:popout" }, + { "section": "char", "label": "odd surface", "surface": "a b" }, + { "section": "char", "label": "bad server", "server": "no way", "command": "/a" }, + { "section": "char", "label": "Line\nbreak", "command": "/ok", "width": -5, "height": 99999 } + ] } + """, out e); + Check(e.Length == 0, "entries are skipped, not the manifest"); + Check(m.Contributions.Length == 1, "only the good entry survives"); + SectionContribution c = m.Contributions.Single(); + Check(c.Label == "Line break", "labels lose line breaks"); + Check(c.Width == 0 && c.Height == SectionManifestParser.MaxSurfaceSize, "sizes clamped"); + + Check(SectionManifestParser.Id("ab_c-1") == "ab_c-1" && SectionManifestParser.Id("A B") == "", "ids"); + Check(SectionManifestParser.Id(new string('a', SectionManifestParser.MaxIdLength + 1)) == "", "long ids"); + Check(SectionManifestParser.Command("/x") == "/x" && SectionManifestParser.Command("/") == "", "commands"); + Check(SectionManifestParser.Surface("section:ilt-options") == "section:ilt-options", "a section surface"); + } + + private static void ManifestLimits() + { + Case("manifest limits"); + var items = string.Join(",", Enumerable.Range(0, 300).Select(i => $$"""{"section":"char","label":"L{{i}}","command":"/c {{i}}"}""")); + SectionManifest m = SectionManifestParser.Parse("p", "{\"contributions\":[" + items + "]}", out _); + Check(m.Contributions.Length == SectionManifestParser.MaxContributions, "contributions capped"); + + var servers = string.Join(",", Enumerable.Range(0, 40).Select(i => $$"""{"id":"s{{i}}"}""")); + m = SectionManifestParser.Parse("p", "{\"servers\":[" + servers + "]}", out _); + Check(m.Servers.Length == SectionManifestParser.MaxServers, "servers capped"); + + string big = "{\"x\":\"" + new string('a', SectionManifestParser.MaxJsonLength) + "\"}"; + Check(SectionManifestParser.Parse("p", big, out string e).Contributions.Length == 0 && e.StartsWith("too large"), "size capped"); + + string longLabel = new string('L', 200); + m = SectionManifestParser.Parse("p", $$"""{"contributions":[{"section":"char","label":"{{longLabel}}","command":"/a"}]}""", out _); + Check(m.Contributions[0].Label.Length == SectionManifestParser.MaxLabelLength, "labels capped"); + } + + // ── Catalog ──────────────────────────────────────────────────────── + + private static readonly ServerState IltOn = new("ilt", "Infinite Leaftide", true, true, ServerForce.Auto, true, "world"); + private static readonly ServerState IltOff = IltOn with { Active = false, Detected = false }; + private static readonly ServerState AelOff = new("aelrynth", "Aelrynth", false, false, ServerForce.Auto, true, ""); + + private static bool Panels(string title) => title is "Radar" or "Skills" or "Nav" or "Inventory" or "Items" or "Chat"; + + private static void CatalogCore() + { + Case("catalog core"); + List views = SectionCatalog.Build(Array.Empty(), Panels, new[] { IltOff, AelOff }); + string[] ids = views.Select(v => v.Id).ToArray(); + Check(ids.SequenceEqual(new[] { "char", "map", "skills", "combat", "nav", "inventory", "crafting", "spells", "chat", "friends", "fellowship", "pets" }), + "the twelve core sections, in order: " + string.Join(",", ids)); + Check(views.All(v => v.Core), "all core"); + Check(views[0].Panes.Single().Kind == SectionPaneKind.Overview, "Char starts with the overview"); + Check(views[0].Label == SectionCatalog.SessionStatsLabel && views[0].Label == "Session Stats", "the char section is labelled Session Stats"); + + // A plugin's universal primary surface in char (RynthAi's session stats) replaces the overview. + var session = SectionManifestParser.Parse("RynthAi", """ + { "contributions": [ { "section": "char", "label": "Session stats", "surface": "section:session", "primary": true } ] } + """, out _); + SectionView chr = SectionCatalog.Build(new[] { session }, Panels, new[] { IltOff }).Single(v => v.Id == "char"); + Check(chr.Panes.Single().Kind == SectionPaneKind.Surface && chr.Panes[0].Contribution!.Surface == "section:session", + "a universal primary surface drops the overview"); + // A server-scoped primary surface doesn't: the overview stays beside it. + var scoped = SectionManifestParser.Parse("p", """ + { "contributions": [ { "section": "char", "server": "ilt", "label": "ILT", "surface": "section:ilt", "primary": true } ] } + """, out _); + chr = SectionCatalog.Build(new[] { scoped }, Panels, new[] { IltOn }).Single(v => v.Id == "char"); + Check(chr.Panes.Any(p => p.Kind == SectionPaneKind.Overview), "a server-scoped surface keeps the overview"); + Check(views[1].Panes.Select(p => p.Panel).SequenceEqual(new[] { "Radar" }), "Map has only the panels that exist"); + Check(views[5].Panes.Select(p => p.Panel).SequenceEqual(new[] { "Inventory", "Items" }), "Inventory keeps panel order"); + Check(!views[3].HasContent && !views[11].HasContent, "Combat (no panels here) and Pets are empty"); + Check(SectionCatalog.FindCore("PETS")?.Id == "pets" && SectionCatalog.FindCore("remote") == null, "FindCore"); + Check(SectionCatalog.Build(Array.Empty(), _ => throw new InvalidOperationException(), new[] { IltOff }) + .All(v => v.Panes.All(p => p.Kind != SectionPaneKind.CorePanel)), "a throwing panel check means no panels"); + } + + private static void CatalogServers() + { + Case("catalog servers"); + SectionManifest m = SectionManifestParser.Parse("RynthAi", GoodManifest, out _); + + List off = SectionCatalog.Build(new[] { m }, Panels, new[] { IltOff, AelOff }); + SectionView pets = off.Single(v => v.Id == "pets"); + Check(pets.Panes.Single().Kind == SectionPaneKind.Surface && pets.Panes[0].Contribution!.Surface == "section:pets", "a primary surface is a pane"); + SectionView skills = off.Single(v => v.Id == "skills"); + Check(skills.Groups.Length == 0, "ILT items hidden while ILT is off"); + + List on = SectionCatalog.Build(new[] { m }, Panels, new[] { IltOn, AelOff }); + skills = on.Single(v => v.Id == "skills"); + Check(skills.Groups.Length == 1 && skills.Groups[0].Title == "Server: Infinite Leaftide" && skills.Groups[0].Server == IltOn, "ILT group while active"); + Check(skills.Groups[0].Items.Single().Command == "/rc progression", "its command"); + SectionView chr = on.Single(v => v.Id == "char"); + Check(chr.Groups.Single().Items.Single().Label == "Off now", "disabled items still listed (with their note)"); + + var universal = SectionManifestParser.Parse("Other", """ + { "contributions": [ { "section": "skills", "label": "Z", "command": "/z", "order": 5 }, + { "section": "skills", "label": "A", "command": "/a", "order": 5 } ] } + """, out _); + skills = SectionCatalog.Build(new[] { m, universal }, Panels, new[] { IltOn }).Single(v => v.Id == "skills"); + Check(skills.Groups.Select(g => g.Title).SequenceEqual(new[] { "Server: Infinite Leaftide", "Plugins" }), "server groups first, then Plugins"); + Check(skills.Groups[1].Items.Select(i => i.Label).SequenceEqual(new[] { "A", "Z" }), "equal orders sort by label"); + } + + private static void CatalogPluginSections() + { + Case("catalog plugin sections"); + SectionManifest m = SectionManifestParser.Parse("RynthAi", GoodManifest, out _); + List views = SectionCatalog.Build(new[] { m }, Panels, new[] { IltOff }); + int quests = views.FindIndex(v => v.Id == "quests"); + Check(quests >= 0 && !views[quests].Core, "the plugin's Quests section shows"); + Check(views[quests - 1].Id == "crafting" && views[quests + 1].Id == "spells", "order 650 puts it between Crafting (600) and Spells (700)"); + var empty = SectionManifestParser.Parse("p", """{ "sections": [ { "id": "empty", "label": "Empty" } ] }""", out _); + Check(SectionCatalog.Build(new[] { empty }, Panels, new[] { IltOff }).All(v => v.Id != "empty"), "an empty plugin section is hidden"); + var hijack = SectionManifestParser.Parse("p", """ + { "sections": [ { "id": "pets", "label": "Mine" }, { "id": "remote", "label": "Mine" } ], + "contributions": [ { "section": "remote", "label": "x", "command": "/x" } ] } + """, out _); + views = SectionCatalog.Build(new[] { hijack }, Panels, new[] { IltOff }); + Check(views.Count(v => v.Id == "pets") == 1 && views.Single(v => v.Id == "pets").Label == "Pets", "core ids can't be redeclared"); + Check(views.All(v => v.Id != "remote"), "the remote id can't be declared"); + var dup = SectionManifestParser.Parse("q", """ + { "sections": [ { "id": "quests", "label": "Other quests", "order": 1 } ], + "contributions": [ { "section": "quests", "label": "x", "command": "/x" } ] } + """, out _); + views = SectionCatalog.Build(new[] { m, dup }, Panels, new[] { IltOff }); + SectionView q = views.Single(v => v.Id == "quests"); + Check(q.Label == "Quests" && q.Order == 650, "the first declaration wins"); + Check(q.Panes.Length == 1 && q.Groups.Single().Items.Single().Plugin == "q", "both plugins' contributions land in it"); + } + + private static void DeclaredServers() + { + Case("declared servers"); + var decl = new SectionServerDecl("frosthaven", "Frosthaven", new[] { "Frosthaven*" }, new[] { "frosthaven.example" }); + Check(SectionCatalog.DetectDeclared(decl, "play.frosthaven.example", null, out string why) && why.Contains("host"), "by host"); + Check(SectionCatalog.DetectDeclared(decl, null, "Frosthaven PvE", out why) && why.Contains("world"), "by world name"); + Check(!SectionCatalog.DetectDeclared(decl, "infiniteleaftide.online", "InfiniteLeaftide", out _), "not another server"); + var none = new SectionServerDecl("x", "X", Array.Empty(), Array.Empty()); + Check(!SectionCatalog.DetectDeclared(none, "a", "b", out why) && why.StartsWith("no host or world-name list"), "no lists"); + } + + // -- Server selection (Diagnostics picker, "/rc server pick", plugin API v86) -- + + /// A server row as SectionRegistry builds it (Active = override applied to detection). + private static ServerState Srv(string id, bool detected, ServerForce force, bool builtIn = false) + => new(id, id.ToUpperInvariant(), ServerForceText.Apply(force, detected), detected, force, builtIn, detected ? "host matches" : ""); + + private static void SelectionPlan() + { + Case("selection plan"); + var servers = new[] { Srv("ilt", true, ServerForce.Auto, true), Srv("aelrynth", false, ServerForce.Off, true), Srv("frost", false, ServerForce.Auto) }; + + var pick = ServerSelection.Plan(servers, "FROST"); + Check(pick != null && pick.Count == 3, "a known id plans every server"); + Check(pick!.Single(p => p.Id == "frost").Force == ServerForce.On, "the pick is forced On (case-insensitive)"); + Check(pick.Where(p => p.Id != "frost").All(p => p.Force == ServerForce.Off), "every other server is forced Off"); + + var auto = ServerSelection.Plan(servers, " Auto "); + Check(auto != null && auto.All(p => p.Force == ServerForce.Auto), "auto resets every override"); + Check(ServerSelection.Plan(servers, "")!.All(p => p.Force == ServerForce.Auto), "empty means auto"); + Check(ServerSelection.Plan(servers, null)!.All(p => p.Force == ServerForce.Auto), "null means auto"); + Check(ServerSelection.Plan(servers, "nowhere") == null, "an unknown id is refused"); + Check(ServerSelection.Plan(Array.Empty(), "auto")!.Count == 0, "no servers, empty plan"); + } + + private static void NotLoadedServerList() + { + Case("not-loaded server plugins"); + var forces = new Dictionary(StringComparer.OrdinalIgnoreCase) { ["coldeve"] = ServerForce.On }; + ServerForce Force(string id) => forces.TryGetValue(id, out ServerForce f) ? f : ServerForce.Auto; + var notLoaded = new[] + { + new NotLoadedServer("frost", "Frosthaven", "RynthFrostACE"), + new NotLoadedServer("coldeve", "Coldeve", "RynthColdeve"), + new NotLoadedServer("ilt", "Infinite Leaftide", "RynthILT"), // a built-in id: the built-in row wins + new NotLoadedServer("", "No id", "RynthBroken"), + }; + var list = new List { Srv("ilt", true, ServerForce.Auto, true) }; + NotLoadedServers.Append(list, notLoaded, Force); + Check(list.Count == 3, "each new id added once, the built-in and the blank id skipped"); + ServerState frost = list.Single(s => s.Id == "frost"); + Check(!frost.Active && !frost.Detected && !frost.BuiltIn && frost.Name == "Frosthaven", "not loaded: listed, not detected, not active"); + Check(frost.Reason.Contains("RynthFrostACE") && frost.Reason.Contains("pick it"), "the reason names the plugin and how to load it"); + ServerState coldeve = list.Single(s => s.Id == "coldeve"); + Check(coldeve.Active && coldeve.Force == ServerForce.On && coldeve.Reason.Contains("loading RynthColdeve"), "forced On: active, loading its plugin"); + Check(list.Single(s => s.Id == "ilt").BuiltIn, "the built-in ilt row is kept"); + Check(ServerSelection.Plan(list, "frost") != null, "a not-loaded server can be picked"); + + var load = NotLoadedServers.ForcedOn(notLoaded, Force); + Check(load.Count == 1 && load[0] == "coldeve", "only the server forced On asks for its plugin"); + forces["coldeve"] = ServerForce.Off; + Check(NotLoadedServers.ForcedOn(notLoaded, Force).Count == 0, "Off loads nothing"); + } + + private static void SelectionCurrentPick() + { + Case("selection current pick"); + Check(ServerSelection.CurrentPick(new[] { Srv("ilt", true, ServerForce.Auto), Srv("ael", false, ServerForce.Auto) }) == ServerSelection.Auto, "no overrides is auto"); + Check(ServerSelection.CurrentPick(new[] { Srv("ilt", true, ServerForce.Off), Srv("ael", false, ServerForce.On) }) == "ael", "one On, rest Off is that pick"); + Check(ServerSelection.CurrentPick(new[] { Srv("ilt", true, ServerForce.On), Srv("ael", false, ServerForce.On) }) == null, "two On is a mix"); + Check(ServerSelection.CurrentPick(new[] { Srv("ilt", true, ServerForce.On), Srv("ael", false, ServerForce.Auto) }) == null, "one On, another Auto is a mix"); + Check(ServerSelection.CurrentPick(new[] { Srv("ilt", true, ServerForce.Off), Srv("ael", false, ServerForce.Auto) }) == null, "only Offs is a mix"); + Check(ServerSelection.CurrentPick(Array.Empty()) == ServerSelection.Auto, "no servers is auto"); + + // A plan applied gives back the same pick. + var servers = new[] { Srv("ilt", true, ServerForce.Auto), Srv("ael", false, ServerForce.Auto) }; + var applied = ServerSelection.Plan(servers, "ael")!.Select(p => Srv(p.Id, servers.Single(s => s.Id == p.Id).Detected, p.Force)).ToArray(); + Check(ServerSelection.CurrentPick(applied) == "ael", "plan round trip"); + } + + private static void SelectionActiveAndOwner() + { + Case("selection active and owner"); + Check(ServerSelection.ActiveServer(new[] { Srv("ilt", true, ServerForce.Auto), Srv("frost", true, ServerForce.Auto) })!.Id == "ilt", "first detected wins"); + Check(ServerSelection.ActiveServer(new[] { Srv("ilt", true, ServerForce.Auto), Srv("frost", false, ServerForce.On) })!.Id == "frost", "forced On beats detection"); + Check(ServerSelection.ActiveServer(new[] { Srv("ilt", true, ServerForce.Off) }) == null, "Off hides a detected server"); + Check(ServerSelection.ActiveServer(Array.Empty()) == null, "none"); + + var pack = SectionManifestParser.Parse("RynthServerPack", """ + { "servers": [ { "id": "frost", "name": "Frosthaven", "hosts": [ "frost.example" ] } ] } + """, out _); + var ilt = SectionManifestParser.Parse("RynthILT", """ + { "contributions": [ { "section": "skills", "server": "ilt", "label": "A", "command": "/a" }, + { "section": "char", "server": "ilt", "label": "B", "command": "/b" } ] } + """, out _); + var ai = SectionManifestParser.Parse("RynthAi", """ + { "contributions": [ { "section": "skills", "server": "ilt", "label": "C", "command": "/c" }, + { "section": "skills", "server": "frost", "label": "D", "command": "/d" } ] } + """, out _); + var engine = SectionManifestParser.Parse("RynthCore", """ + { "servers": [ { "id": "ilt", "name": "Infinite Leaftide" } ] } + """, out _); + var all = new[] { engine, ai, ilt, pack }; + + Check(ServerSelection.OwnerPlugin(all, "frost", "RynthCore") == "RynthServerPack", "the declaring plugin owns a server"); + Check(ServerSelection.OwnerPlugin(all, "ILT", "RynthCore") == "RynthILT", "else the most contributions (engine skipped)"); + Check(ServerSelection.OwnerPlugin(all, "nowhere", "RynthCore") == "", "nobody"); + var tie = SectionManifestParser.Parse("Alpha", """ + { "contributions": [ { "section": "skills", "server": "x", "label": "A", "command": "/a" } ] } + """, out _); + var tie2 = SectionManifestParser.Parse("Beta", """ + { "contributions": [ { "section": "skills", "server": "x", "label": "A", "command": "/a" } ] } + """, out _); + Check(ServerSelection.OwnerPlugin(new[] { tie2, tie }, "x", "RynthCore") == "Alpha", "ties go to the name that sorts first"); + } + + private static unsafe void StateJson() + { + Case("state json"); + var ilt = SectionManifestParser.Parse("RynthILT", """ + { "contributions": [ { "section": "skills", "server": "ilt", "label": "A", "command": "/a" } ] } + """, out _); + var servers = new[] { Srv("ilt", true, ServerForce.Auto, true), Srv("aelrynth", false, ServerForce.Auto, true) }; + string json = ServerStateJson.Build(servers, new[] { ilt }, 7, "infiniteleaftide.online", "Infinite \"Leaf\"", "RynthCore"); + + using var doc = System.Text.Json.JsonDocument.Parse(json); + var root = doc.RootElement; + Check(root.GetProperty("schema").GetInt32() == ServerStateJson.Schema && root.GetProperty("revision").GetInt32() == 7, "schema and revision"); + Check(root.GetProperty("host").GetString() == "infiniteleaftide.online", "host"); + Check(root.GetProperty("world").GetString() == "Infinite \"Leaf\"", "world (quotes escaped)"); + Check(root.GetProperty("pick").GetString() == "auto", "pick auto"); + Check(root.GetProperty("active").GetString() == "ilt" && root.GetProperty("activeName").GetString() == "ILT", "active server"); + Check(root.GetProperty("activePlugin").GetString() == "RynthILT", "active server's owner plugin"); + var rows = root.GetProperty("servers"); + Check(rows.GetArrayLength() == 2, "every server listed"); + var first = rows[0]; + Check(first.GetProperty("id").GetString() == "ilt" && first.GetProperty("active").GetBoolean() && first.GetProperty("detected").GetBoolean(), "row state"); + Check(first.GetProperty("force").GetString() == "auto" && first.GetProperty("builtIn").GetBoolean(), "row override and built-in"); + Check(rows[1].GetProperty("plugin").GetString() == "" && rows[1].GetProperty("reason").GetString() == "", "row with no owner"); + + var mixed = new[] { Srv("ilt", true, ServerForce.On), Srv("ael", false, ServerForce.On) }; + using (var m = System.Text.Json.JsonDocument.Parse(ServerStateJson.Build(mixed, Array.Empty(), 1, null, null, "RynthCore"))) + Check(m.RootElement.GetProperty("pick").GetString() == "mixed" && m.RootElement.GetProperty("host").GetString() == "", "mixed pick, null host"); + using (var n = System.Text.Json.JsonDocument.Parse(ServerStateJson.Build(new[] { Srv("ilt", false, ServerForce.Auto) }, Array.Empty(), 1, "h", "w", "RynthCore"))) + Check(n.RootElement.GetProperty("active").GetString() == "" && n.RootElement.GetProperty("activePlugin").GetString() == "", "no active server"); + + // Write: the plugin API's buffer convention (length returned; nothing written when too small). + int length = System.Text.Encoding.UTF8.GetByteCount(json); + byte[] small = new byte[length]; + fixed (byte* p = small) + Check(ServerStateJson.Write(json, p, small.Length) == length && small.All(b => b == 0), "too small: length only, nothing written"); + Check(ServerStateJson.Write(json, null, 0) == length, "null buffer: length only"); + byte[] big = new byte[length + 1]; + fixed (byte* p = big) + Check(ServerStateJson.Write(json, p, big.Length) == length, "fits: length"); + Check(System.Text.Encoding.UTF8.GetString(big, 0, length) == json && big[length] == 0, "fits: text and NUL"); + } + + // ── Session rates (status feed / Session Stats) ──────────────────── + + private static readonly DateTime T0 = new(2026, 10, 13, 12, 0, 0, DateTimeKind.Utc); + + /// XP and character luminance: only rises count, the first read is the baseline. + private static void RatesRises() + { + Case("rates rises"); + var r = new SessionRates(); + Check(r.View(T0).Xp == 0 && r.View(T0).Seconds == 0, "zeros before the first sample"); + r.Sample(0, new SessionRatesSample(100, 5, null, null, null), T0); + Check(r.Character == 0, "character 0 is ignored"); + + r.Sample(7, new SessionRatesSample(1_000, 50, null, null, null), T0); + Check(r.View(T0).Xp == 0 && r.View(T0).Lum == 0, "first read is the baseline"); + r.Sample(7, new SessionRatesSample(4_000, 80, null, null, null), T0.AddMinutes(30)); + r.Sample(7, new SessionRatesSample(4_000, 10, null, null, null), T0.AddMinutes(45)); // spent 70 lum + r.Sample(7, new SessionRatesSample(5_000, 30, null, null, null), T0.AddHours(1)); + SessionRatesView v = r.View(T0.AddHours(1)); + Check(v.Xp == 4_000, "xp is the sum of rises: " + v.Xp); + Check(v.Lum == 50, "a spend moves the baseline, it doesn't take earnings back: " + v.Lum); + Check(Math.Abs(v.XpPerHour - 4_000) < 0.001 && Math.Abs(v.LumPerHour - 50) < 0.001, "per hour over one hour"); + Check(r.View(T0).Seconds == 1, "a session is at least one second long"); + + r.Sample(8, new SessionRatesSample(9_000, 1, null, null, null), T0.AddHours(2)); + v = r.View(T0.AddHours(2)); + Check(r.Character == 8 && v.Xp == 0 && v.Lum == 0 && v.StartUtc == T0.AddHours(2), "a new character starts a new session"); + } + + /// ACECustom's bank (9005) and Aelrynth's banked (9102) / drawn (9103) totals. + private static void RatesBank() + { + Case("rates bank"); + var r = new SessionRates(); + r.Sample(1, new SessionRatesSample(null, 100, 1_000, null, null), T0); + r.Sample(1, new SessionRatesSample(null, 100, 1_500, null, null), T0.AddMinutes(1)); + Check(r.View(T0.AddMinutes(1)).Lum == 500, "a bank rise is income"); + r.Sample(1, new SessionRatesSample(null, 400, 1_200, null, null), T0.AddMinutes(2)); + Check(r.View(T0.AddMinutes(2)).Lum == 500, "a withdrawal (bank down, character up) isn't income once the bank is tracked"); + + var a = new SessionRates(); + a.Sample(2, new SessionRatesSample(null, 10, null, 0, 0), T0); + a.Sample(2, new SessionRatesSample(null, 10, null, 300, 0), T0.AddMinutes(1)); + Check(a.View(T0.AddMinutes(1)).Lum == 300, "auto-banked luminance was earned"); + a.Sample(2, new SessionRatesSample(null, 210, null, 300, 200), T0.AddMinutes(2)); + Check(a.View(T0.AddMinutes(2)).Lum == 300, "drawn luminance landing on the character isn't earned"); + a.Sample(2, new SessionRatesSample(null, 260, null, 300, 200), T0.AddMinutes(3)); + Check(a.View(T0.AddMinutes(3)).Lum == 350, "a real character rise after a draw still counts"); + } + + /// Deposits and incoming transfers seen in chat aren't income; the marker expires. + private static void RatesChat() + { + Case("rates chat"); + Check(SessionRates.TryMovedIntoBank("Deposited 1,234 luminance into your bank.", out long n) && n == 1_234, "a deposit line"); + Check(SessionRates.TryMovedIntoBank(" Received 50 luminance from Kelpie.", out n) && n == 50, "a transfer line, padded"); + Check(!SessionRates.TryMovedIntoBank("Kelpie tells you, \"Deposited 5 luminance\"", out _), "a quoted line isn't a deposit"); + Check(!SessionRates.TryMovedIntoBank("Deposited luminance", out _) && !SessionRates.TryMovedIntoBank(null, out _), "no amount, null"); + Check(!SessionRates.TryMovedIntoBank("Deposited 99999999999999999999 luminance", out _), "overflow is rejected"); + + var r = new SessionRates(); + r.Sample(1, new SessionRatesSample(null, 1_000, 0, null, null), T0); + r.OnChat("Deposited 600 luminance", T0.AddSeconds(5)); + r.Sample(1, new SessionRatesSample(null, 400, 600, null, null), T0.AddSeconds(6)); + Check(r.View(T0.AddSeconds(6)).Lum == 0, "a deposit is moved money"); + r.Sample(1, new SessionRatesSample(null, 400, 700, null, null), T0.AddSeconds(7)); + Check(r.View(T0.AddSeconds(7)).Lum == 100, "the next bank rise after the deposit is income"); + + r.OnChat("Received 50 luminance from Someone", T0.AddSeconds(10)); + r.Sample(1, new SessionRatesSample(null, 400, 800, null, null), T0.AddSeconds(100)); + Check(r.View(T0.AddSeconds(100)).Lum == 200, "the marker expires after 60 seconds"); + } + + // ── Harness ──────────────────────────────────────────────────────── + + private static void Case(string name) + { + _case = name; + Console.WriteLine($"-- {name}"); + } + + private static void Check(bool ok, string what) + { + _checks++; + if (ok) return; + _failed++; + Console.WriteLine($"FAIL [{_case}] {what}"); + } +} diff --git a/tools/SectionsTests/SectionsTests.csproj b/tools/SectionsTests/SectionsTests.csproj new file mode 100644 index 0000000..e8bac41 --- /dev/null +++ b/tools/SectionsTests/SectionsTests.csproj @@ -0,0 +1,37 @@ + + + + + Exe + net10.0 + enable + enable + true + SectionsTests + + true + + + + + + + + + + + + + + + + + + diff --git a/tools/StatusAgentTests/Program.cs b/tools/StatusAgentTests/Program.cs index 54d5c4b..7e501b0 100644 --- a/tools/StatusAgentTests/Program.cs +++ b/tools/StatusAgentTests/Program.cs @@ -33,6 +33,7 @@ internal static class Program StatusFileReads(); MoveProtocol(); LogRollover(); + ServeGuards(); if (Arg(args, "--atlas") is { } atlas) RealAtlas(atlas); if (portal != null) RealSpellTable(portal); if (cell != null) RealWorldMap(cell, outFile); @@ -42,6 +43,53 @@ internal static class Program return _failed == 0 ? 0 : 1; } + // ── serve guards (remote access) ──────────────────────────────────────── + + private static void ServeGuards() + { + Section("status server: loopback, token length, lockout, bounded bodies, log-safe text"); + Check(ServeGuard.IsLoopbackPrefix("http://127.0.0.1:8740/"), "127.0.0.1 is loopback"); + Check(ServeGuard.IsLoopbackPrefix("http://localhost:8740/"), "localhost is loopback"); + Check(ServeGuard.IsLoopbackPrefix("http://[::1]:8740/"), "[::1] is loopback"); + Check(!ServeGuard.IsLoopbackPrefix("http://+:8740/"), "+ is every address"); + Check(!ServeGuard.IsLoopbackPrefix("http://*:8740/"), "* is every address"); + Check(!ServeGuard.IsLoopbackPrefix("http://100.64.1.2:8740/"), "a Tailscale address is not"); + Check(!ServeGuard.IsLoopbackPrefix("http://127.0.0.1.evil.example:8740/"), "a name starting 127.0.0.1 is not"); + + Check(ServeGuard.TokenProblem("http://127.0.0.1:8740/", "") != null, "no token: never serves"); + Check(ServeGuard.TokenProblem("http://127.0.0.1:8740/", "short") == null, "loopback: any token"); + Check(ServeGuard.TokenProblem("http://+:8740/", "short") != null, "remote bind: a short token is refused"); + Check(ServeGuard.TokenProblem("http://+:8740/", new string('k', 16)) == null, "remote bind: 16 characters is fine"); + + var t = new AuthThrottle(); + var lan = System.Net.IPAddress.Parse("192.168.1.50"); + var t0 = new DateTime(2026, 10, 13, 12, 0, 0, DateTimeKind.Utc); + bool started = false; + for (int i = 0; i < AuthThrottle.MaxFailures - 1; i++) started |= t.Fail(lan, t0.AddSeconds(i)); + Check(!started && !t.IsBlocked(lan, t0.AddSeconds(10)), "under the limit: not blocked"); + Check(t.Fail(lan, t0.AddSeconds(10)), "the limit starts a lockout (reported once)"); + Check(t.IsBlocked(lan, t0.AddMinutes(4)), "still blocked inside the lockout"); + Check(!t.IsBlocked(lan, t0.AddMinutes(6)), "free again after it"); + var slow = System.Net.IPAddress.Parse("192.168.1.51"); + for (int i = 0; i < AuthThrottle.MaxFailures * 2; i++) t.Fail(slow, t0.AddSeconds(i * 61)); + Check(!t.IsBlocked(slow, t0.AddSeconds(AuthThrottle.MaxFailures * 2 * 61)), "failures spread past the window don't add up"); + var other = System.Net.IPAddress.Parse("192.168.1.52"); + for (int i = 0; i < AuthThrottle.MaxFailures - 1; i++) t.Fail(other, t0); + t.Succeed(other); + Check(!t.Fail(other, t0), "a good token clears the count"); + for (int i = 0; i < AuthThrottle.MaxFailures * 2; i++) t.Fail(System.Net.IPAddress.Loopback, t0); + Check(!t.IsBlocked(System.Net.IPAddress.Loopback, t0), "loopback is never locked out"); + + Check(ServeGuard.TryReadBounded(new MemoryStream(Encoding.UTF8.GetBytes("{\"pid\":1}")), 9, 64, null, out string small) && small == "{\"pid\":1}", "a small body reads"); + Check(!ServeGuard.TryReadBounded(new MemoryStream(new byte[100]), 100, 64, null, out _), "a declared length over the limit is refused"); + Check(!ServeGuard.TryReadBounded(new MemoryStream(new byte[100]), -1, 64, null, out _), "chunked (no length) over the limit is refused"); + Check(ServeGuard.TryReadBounded(new MemoryStream(new byte[64]), -1, 64, null, out _), "exactly the limit reads"); + + Check(ServeGuard.LogSafe("a\r\nFAKE LOG LINE") == "a FAKE LOG LINE", "CR/LF can't start a log line"); + Check(ServeGuard.LogSafe(new string('x', 500), 10) == "xxxxxxxxxx...", "capped"); + Check(ServeGuard.LogSafe(null) == "", "null is empty"); + } + // ── log rollover ──────────────────────────────────────────────────────── private static void LogRollover() diff --git a/tools/StatusAgentTests/StatusAgentTests.csproj b/tools/StatusAgentTests/StatusAgentTests.csproj index 6ce4287..23c8933 100644 --- a/tools/StatusAgentTests/StatusAgentTests.csproj +++ b/tools/StatusAgentTests/StatusAgentTests.csproj @@ -32,6 +32,7 @@ +