feat: port SK test branch (2026.10.18.24) onto sk

Squash of test/hotbuild-2026-10-16 as merged onto aelrynth main 2026.10.17.1, matching the
2026.10.18.24 test installer. The test branch wins where both changed the same lines; sk-only
changes kept; duplicate features cut to the test branch's copy. RynthAi HandWrittenVersion stays
0.5.0-legacy-ui on sk.

Highlights: RynthOracle 0.6.0 (Legendary, Markers, Dynamic Stamps and Temple guardians merged into
the Quests list, RynthNav Go to), RynthILT 0.2.20 (ub-IT auto-chunk rules, rating level,
RynthILT.Data v3), RynthAi ub-IT /ub and VT/MT meta compatibility and the loot attribute checklist,
RynthNav destination alternatives. Changelog/2026-10-18-sk-port-test-branch-2026.10.18.24.md.
This commit is contained in:
BlankenshipG 2026-10-18 16:22:40 -04:00
commit 7797901d69
287 changed files with 22602 additions and 1090 deletions

View file

@ -0,0 +1,15 @@
# ub-Rythai 3.0.2 — .NET 10 vs net48
## Summary
Documents and enforces that **ub-Rythai** builds as **`net10.0-windows`** (RynthCore NativeAOT plugin). **net48** remains the domain of **Utility Belt / UB-ILT** in `UB/` and `ub-IT/` (Decal host), not this project.
## Technical
- `.csproj`: explicit comment block; no `net48` multi-target.
- Restored full plugin sources under `ub-Rythai/RynthCore.Plugin.UbRythai/` (settings store, chat automation, exports).
- `UbRythaiSettingsStore.cs`: added `using System;` for `Environment`.
## Previous release
- **3.0.1** — version bump prior to TFM documentation pass.

View file

@ -0,0 +1,40 @@
# ub-Rythai 3.1.0 — P1-P4 baseline
## Summary
Implements a working **P1-P4 baseline** inside the dedicated `ub-Rythai` repo on **net10.0-windows** (RynthCore NativeAOT), keeping UB-ILT migration code out of Decal/net48 plugin lines.
## P1 (foundation automation)
- Login command queue and periodic command batch scheduler (`InvokeChatParser`-based).
- Login macro parity toggles: open main pack, optional chat-resize command.
- Log-out-on-death automation with configurable cooldown.
- Chat commands: `/ub help`, `/ub build`, `/ub loginq run`, `/ub periodic status`.
## P2 (high-traffic parity baseline)
- Selective chat filtering toggles:
- busy lines
- spell fizzle lines
- vendor spam lines
- monster death lines
- Client FPS policy settings wired to `Host.SetFpsLimit`.
- P2 runtime counters surfaced via `/ub p2 status`.
- Window mover flags persisted as placeholders for deeper host integration.
## P3 (ILT gameplay gates)
- Persisted feature gates added for spellcraft queues, temple/guardian tools,
fellowship games, and quest/economy tooling.
- UI controls added so each surface can be turned on incrementally.
## P4 (deferred host-dependent gates)
- Persisted toggles added for VHS hotkey bridge, Decal HUD compatibility layer,
and legacy autopack import compatibility.
- These remain opt-in placeholders pending deeper host/API work.
## Technical
- Version bumped: `3.1.0` (`InformationalVersion: 3.1.0-p1-p4-baseline`).
- Build verified via `dotnet publish -c Release` on `RynthCore.Plugin.UbRythai.csproj`.

View file

@ -0,0 +1,28 @@
# ub-Rythai 3.1.1 — logging to local files with rollover
## Summary
Adds built-in granular file logging to `ub-Rythai` with local rollover under the install `Logs` folder, plus configurable runtime log level from the plugin UI.
## Changes
- Added `UbRythaiFileLogger`:
- writes to `AppContext.BaseDirectory/Logs/ub-Rythai.log`
- rolls files at 5 MB
- keeps the newest 10 rolled files
- Added `UbRythaiLogLevel` enum (`Trace`, `Debug`, `Info`, `Warn`, `Error`).
- Added persisted setting `UbRythaiSettings.LogLevel` with default `Info`.
- Added **Logging** section in the base plugin ImGui window:
- level dropdown for minimum file log level
- shows active logs folder path
- Routed automation/plugin operational logs through centralized `LogAt(...)`:
- still sends to host log
- now also writes to rolling file output based on configured level
- Added `/ub log status` to report active log level and local log folder path.
## Build / verification
- Target remains `net10.0-windows` (`RynthCore` plugin model, not net48 Decal).
- Verified with:
- `dotnet publish -c Release`
- no linter errors in `ub-Rythai/RynthCore.Plugin.UbRythai`

View file

@ -0,0 +1,29 @@
# Changelog 3.1.2 - AutoTradeAccept parity
Date: 2026-04-22
## Added
- Added P1 `AutoTradeAccept` parity controls to `ub-Rythai` settings:
- `AutoTradeAcceptEnabled`
- `AutoTradeAcceptWhitelist` (regex list, comma/semicolon separated)
- `AutoTradeAcceptCommand` (chat command fallback to trigger acceptance)
- `AutoTradeAcceptDebounceSeconds` (re-fire guardrail)
- Added P1 ImGui controls under **P1 Foundation** for auto trade acceptance.
- Added `/ub autotradeaccept` command surface:
- `status`
- `on` / `off`
- `debounce <sec>`
- `cmd <chat command>`
- `whitelist <regex list>`
## Behavior
- When enabled, incoming trade-related chat lines are parsed for common partner-name phrases.
- If the extracted partner name matches whitelist policy (or whitelist is empty), `ub-Rythai` invokes the configured trade-accept chat command.
- A debounce window blocks rapid repeat accepts to reduce accidental loops.
## Notes
- RynthCore currently does not expose a dedicated native trade-accept callback in the plugin host surface used here, so this parity slice uses a chat-signal + command-dispatch strategy.
- This is an incremental parity step intended to be safe-by-default and shard-command configurable.

View file

@ -0,0 +1,29 @@
# Changelog 3.1.3 - AutoPercentConfirmation parity
Date: 2026-04-22
## Added
- Added P1 `AutoPercentConfirmation` parity controls:
- `AutoPercentConfirmationEnabled`
- `AutoPercentConfirmationThreshold` (1-100)
- `AutoPercentConfirmationCommand` (default `/yes`)
- `AutoPercentConfirmationDebounceSeconds`
- Added P1 ImGui controls for percent confirmation in the main `ub-Rythai` window.
- Added `/ub autopercent` command surface:
- `status`
- `on` / `off`
- `threshold <1-100>`
- `debounce <sec>`
- `cmd <chat command>`
## Behavior
- Watches incoming chat for:
- `You determine that you have a <n> percent chance to succeed.`
- When enabled, if `<n>` meets/exceeds the configured threshold, executes the configured confirm command.
- Debounce prevents rapid re-firing during repeated prompt sequences.
## Fixes
- `AutoTradeAccept` and `AutoPercentConfirmation` checks now run independently of the P2 chat filter toggle, so disabling message filtering no longer disables those P1 automations.

View file

@ -0,0 +1,36 @@
# Changelog 3.1.4 - Busy-state guardrails
Date: 2026-04-22
## Added
- Added centralized chat command dispatch guardrails for P1 safety parity:
- `BusyGuardrailsEnabled`
- `BusyGuardrailsMinCommandGapMs`
- `BusyGuardrailsBusyStateThreshold`
- Added `/ub guard` command surface:
- `status`
- `on` / `off`
- `gap <ms>`
- `threshold <n>`
- `reset`
- Added P1 UI controls for guardrails and blocked-command counters.
## Behavior
- All plugin command dispatch now routes through one gate:
- Login command queue
- Periodic command queue
- Login macros
- Death logout
- AutoTradeAccept
- AutoPercentConfirmation
- Guard gate blocks dispatch when:
- command interval is below configured min gap
- host busy state is above configured threshold
- Block counters track busy and gap suppressions for diagnostics.
## Notes
- Guardrails default to enabled with conservative initial values.
- This step reduces overlapping command dispatch and prepares for later per-line diagnostics.

View file

@ -0,0 +1,23 @@
# Changelog 3.1.5 - Login queue diagnostics
Date: 2026-04-22
## Added
- Added per-line login queue diagnostics in `ub-Rythai` automation.
- Each login queue dispatch attempt now records:
- UTC timestamp
- source line number from the login command text area
- command preview
- success/failure state
- detail (`dispatched`, `dispatch blocked or failed`, or exception message)
- Added diagnostics status and history panel in the main UI under P1 Foundation.
- Added login diagnostics commands:
- `/ub loginq diag`
- `/ub loginq clear`
## Behavior
- Diagnostic history keeps the most recent 100 login queue attempts.
- History persists for the current runtime session and can be manually cleared.
- Existing `/ub loginq run` replay behavior remains unchanged.

View file

@ -0,0 +1,30 @@
# Changelog 3.1.6 - P2 chat filter expansion
Date: 2026-04-22
## Added
- Expanded P2 chat filter parity set with additional UB-style categories:
- attack evades
- defense evades
- attack resists
- defense resists
- spell cast mine
- spell cast others
- spell expires
- periodic healing
- failed assess
- kill task complete
- Added per-category counters for all P2 filter categories currently implemented.
- Added counter reset controls:
- `/ub p2 reset`
- `Reset P2 counters` button in the UI
## Updated
- `/ub p2 status` now reports the expanded category counters in addition to existing counters.
- P2 panel now includes toggle checkboxes for all newly added categories plus inline counter summaries.
## Notes
- This is an incremental parity step toward the full UB Mag-style chat filter matrix.

View file

@ -0,0 +1,24 @@
# Changelog 3.1.7 - XPMeter + MiniRemote portal gems + Temple guardian phrasebook
Date: 2026-04-22
## Added
- **XP Meter (UB-ILT parity, RynthCore adaptation)**:
- ImGui overlay window
- Tracks deltas from `PropertyInt64.TotalExperience` (earned XP) and `PropertyInt64.AvailableLuminance` (LUM gains)
- `/ub xpmeter on|off|reset|status`
- **Mini Remote portal gem quick use (UB-ILT parity)**:
- ImGui button panel for the canonical UB portal gem names
- Inventory BFS scan + `UseObject` when found
- `/ub portal list` and `/ub portal use <gem name>`
- **Temple / Guardian logic (UB-ILT phrasebook parity)**:
- Ported `TempleGuardianPhrasebook` mapping logic into `ub-Rythai`
- `/ub guardian translate <text>`
- Optional auto-chat translation when `EnableTempleGuardianTools` is on and `TempleGuardianAutoChat` is enabled
- Optional **best-effort** auto hand-in pump toggle (`TempleGuardianAutoHandIn`) — see notes
## Notes / limitations
- UB-ILT `XPMeter` used a native client hook on int64 quality updates. RynthCore plugins instead poll `TryGetObjectQuadProperty` on the player, so updates are smooth but not hook-identical.
- UB-ILT guardian auto hand-in depends on UB-only tooling (`AutoVendor`, `UB_GiveItem`, vendor cache). On RynthCore, the auto hand-in path is **best-effort chat-command scaffolding only** and may be a no-op on shards without equivalent UB macros.

View file

@ -0,0 +1,12 @@
# ub-Rythai 3.1.8 — RynthBundle installer inclusion
**Assembly / package version:** 3.1.8 (`RynthCore.Plugin.UbRythai.csproj`)
## Summary
- Version bump aligned with **RynthBundle 0.4.2**: the RynthCore **`installer\Build-Installer.ps1`** pipeline now publishes this project when the **`ub-Rythai`** repo sits next to **`RynthCore`** and **`RynthSuite`**, and stages **`RynthCore.Plugin.UbRythai.dll`** into the installer’s `Runtime\Plugins\` layout.
## RynthCore references
- `RynthCore/Changelog/2026-04-23-release-0.4.2.md` — full bundle release notes.
- `RynthCore/BUILD.md` — `-UbRythaiPluginProject`, `-SkipUbRythai`.

View file

@ -0,0 +1,29 @@
# ub-Rythai 3.1.9 — ILT mode gate + banking port
Date: 2026-04-23
## What changed
- Added UB-ILT style ILT gating in `ub-Rythai`:
- `LeaftideFeaturesMode`: `Auto | On | Off`
- `LeaftideAutoWorldNames`: world-name list used by `Auto`
- `LeaftideManualAllowBanking`: manual override that allows banking when mode is `On`
- Added new commands:
- `/ub leaftide on|off|auto`
- `/ub leaftide` (status with effective ILT + banking state and world match result)
- `/ub bank status|refresh|transfer <p|l|k|mk|e|we> <amount> <target>`
- Ported core UB-ILT banking behavior into `ub-Rythai`:
- `/bank` refresh dispatch with throttling
- `[BANK]` line parsing for balances (pyreals, luminance, keys, coins)
- transfer command builder for all bank currencies
- optional periodic auto-transfer based on parsed balances and percent
- Extended ImGui UI with ILT + banking controls:
- ILT mode selector and auto world-name configuration
- banking enablement/status/readout
- manual transfer controls
- auto-transfer settings
## Why
- Lets the same `ub-Rythai` build work across multiple shards without hardcoding ILT behavior everywhere.
- Brings UB-ILT banking utility into the RynthCore/Suite plugin path with explicit safety gates and manual override.

View file

@ -0,0 +1,44 @@
# ub-Rythai
Workspace and **RynthCore** plugin for **Utility Belt / UB-ILT–inspired** automation on the **3.x** line. This repo is **.NET 10** only; it is **not** a .NET Framework 4.8 Decal assembly.
## .NET 10 vs .NET Framework 4.8
| Deliverable | Target framework | Host | Output |
|-------------|------------------|------|--------|
| **ub-Rythai** (`RynthCore.Plugin.UbRythai`) | **`net10.0-windows`**, win-x86, **NativeAOT** | RynthCore injected client | `RynthCore.Plugin.UbRythai.dll` → Engine `Plugins\` |
| **Utility Belt / UB-ILT** | **`net48`** (and net8 / net10 for other UB lines) | Decal | `UtilityBelt.dll` / `UBLoader` — see `UB/` and `ub-IT/` |
Do not add `net48` to this plugin project: it references **RynthCore.PluginCore** (modern .NET) and ships as an unmanaged **RynthPlugin** entry-point DLL, not a Decal add-on.
## How this relates to other repos
| Location | Role |
|----------|------|
| `UB/` | Upstream Utility Belt (Decal): net48 **1.x**, net8 **1.x**, net10 **2.x** (`UtilityBelt.csproj`). |
| `ub-IT/` | ILT fork: nested `utilitybelt.gitlab.io-ILT_Customizations/.../UtilityBelt` — Decal stack, UB-ILT docs. |
| **`ub-Rythai/`** (this repo) | **3.x** RynthCore plugin sources: `RynthCore.Plugin.UbRythai/`. |
| `RynthSuite/` | RynthAi and other RynthCore plugins (sibling repo). |
## Build (plugin)
Requires **.NET 10 SDK**, **x86**. `RynthCore` must be a **sibling** directory next to `ub-Rythai` (same parent folder).
```powershell
cd "D:\asherons call-int code\ub-Rythai\RynthCore.Plugin.UbRythai"
dotnet publish -c Release
```
Publish copies the DLL into `RynthCore\src\RynthCore.Engine\...\Plugins\` when those output paths exist.
## Adaptation reality
UB-ILT uses **Decal.Adapter**, Virindi views, WinForms, MoonSharp, VTank interop, etc. That does not run inside the **NativeAOT** RynthCore host. Features are re-implemented here against `RynthCoreHost` / **ImGui** as needed.
## Changelog
See `Changelog/` in this repo.
## Roadmap
See `ROADMAP-PORT-REMAINING.md` for remaining UB-ILT parity work by P1-P4 tier.

View file

@ -0,0 +1,74 @@
# ub-Rythai Remaining Port Roadmap
This roadmap tracks what is still left to port from UB-ILT/UtilityBelt semantics into `ub-Rythai` on the RynthCore host.
## Current baseline (already in ub-Rythai)
- P1 baseline: login command queue, periodic command batch, login macro hooks, death logout hook.
- P2 baseline: selective chat filtering toggles, FPS policy, basic counters and status command.
- P3/P4 feature gates: persisted toggles and UI placeholders for staged rollout.
- Built-in rolling file logging and log-level controls.
## P1 - Remaining (foundation and safety)
- **AutoTradeAccept parity**: add robust, whitelist-driven trade acceptance flow.
- **AutoPercentConfirmation parity**: dialog recognition/confirmation pipeline with safe thresholds.
- **Busy-state guardrails**: centralize action throttling to prevent overlapping command dispatch.
- **Login command diagnostics**: per-line success/failure history in UI, not only log output.
## P2 - Remaining (high-traffic parity)
- **ChatFilter parity expansion**:
- port the full UB Mag-style line set (26+3 categories), not current subset.
- add per-category counters and reset controls in UI.
- **Window mover**:
- implement save/list/restore/delete profile positions per world/account/character.
- add `/ub window ...` command surface.
- **Tracker parity**:
- corpse tracker persistence and summary panel.
- player/profit tracker equivalents with export/import compatibility where feasible.
## P3 - Remaining (ILT gameplay systems)
- **Spellcraft queue execution**:
- queue model + validation rules + cadence controls.
- integration with inventory/object cache and action dispatch.
- **Temple/guardian tools**:
- quest-state-driven actions and helper UI.
- **Fellowship games**:
- blackjack/poker/trivia command handling and state.
- **Quest/economy modules**:
- XP, bank/economy utilities, and character progression helpers mapped to available RynthCore APIs.
## P4 - Remaining (deferred/host-dependent)
- **VHS hotkey bridge**:
- requires host/API strategy for key binding interoperability.
- **Decal HUD compatibility layer**:
- evaluate if practical under RynthCore+ImGui; scope likely limited.
- **Legacy AutoPack profile import**:
- parser + mapping from legacy formats into ub-Rythai native profile format.
## Architecture work still needed
- Move duplicated UB-port traces out of `RynthAi` into `ub-Rythai` (single ownership).
- Create shared port libraries (classification, trackers, command bridge) to avoid monolithic plugin file growth.
- Add profile/folder abstraction so nav/loot/meta/profile paths are configurable per character without hardcoded roots.
## Test/quality backlog
- Add automated smoke test checklist for each command family:
- login queue, periodic queue, log config, filter toggles.
- Add regression test matrix for:
- login/logout flows
- character switch
- missing-path handling
- malformed profile files
- Add performance guardrails for per-tick work and logging volume.
## Suggested next milestone
**Milestone 3.2.0**
- Complete P2 chat-filter parity set.
- Implement window mover command/UI.
- Remove UB-port remnants from `RynthAi` and finalize repo boundary.

View file

@ -0,0 +1,16 @@
using System.Reflection;
namespace RynthCore.Plugin.UbRythai;
/// <summary>Build/version strings aligned with the .csproj (net10.0-windows; not net48).</summary>
internal static class PluginBuildInfo
{
internal static string AssemblyName => typeof(UbRythaiPlugin).Assembly.GetName().Name ?? "RynthCore.Plugin.UbRythai";
internal static string AssemblyInformationalVersion =>
typeof(UbRythaiPlugin).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion
?? typeof(UbRythaiPlugin).Assembly.GetName().Version?.ToString()
?? "3.1.0-p1-p4-baseline";
internal static string DisplayVersion => $"v{AssemblyInformationalVersion} net10";
}

View file

@ -0,0 +1,99 @@
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.UbRythai;
/// <summary>Unmanaged exports consumed by RynthCore.Engine.Plugins.PluginLoader.</summary>
public static unsafe class PluginExports
{
private static readonly RynthPluginRuntime<UbRythaiPlugin> Runtime = new();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginInit", CallConvs = new[] { typeof(CallConvCdecl) })]
private static int Init(RynthCoreApiNative* api) => Runtime.Init(api);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginShutdown", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Shutdown() => Runtime.Shutdown();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUIInitialized", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnUIInitialized() => Runtime.OnUIInitialized();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLoginComplete", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnLoginComplete() => Runtime.OnLoginComplete();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnBarAction", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnBarAction() => Runtime.OnBarAction();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnSelectedTargetChange", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnSelectedTargetChange(uint currentTargetId, uint previousTargetId) =>
Runtime.OnSelectedTargetChange(currentTargetId, previousTargetId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginName", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetName() => UbRythaiPlugin.NamePointer;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginVersion", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr GetVersion() => UbRythaiPlugin.VersionPointer;
[UnmanagedCallersOnly(EntryPoint = "RynthPluginTick", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Tick() => Runtime.OnTick();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginRender", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Render() => Runtime.OnRender();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatBarEnter", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnChatBarEnter(IntPtr textUtf16, IntPtr eatFlag) => Runtime.OnChatBarEnter(textUtf16, eatFlag);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnChatWindowText", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnChatWindowText(IntPtr textUtf16, int chatType, IntPtr eatFlag) =>
Runtime.OnChatWindowText(textUtf16, chatType, eatFlag);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnCreateObject", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnCreateObject(uint objectId) => Runtime.OnCreateObject(objectId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnDeleteObject", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnDeleteObject(uint objectId) => Runtime.OnDeleteObject(objectId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUpdateObject", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnUpdateObject(uint objectId) => Runtime.OnUpdateObject(objectId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUpdateObjectInventory", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnUpdateObjectInventory(uint objectId) => Runtime.OnUpdateObjectInventory(objectId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnViewObjectContents", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnViewObjectContents(uint objectId) => Runtime.OnViewObjectContents(objectId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnStopViewingObjectContents", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnStopViewingObjectContents(uint objectId) => Runtime.OnStopViewingObjectContents(objectId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnVendorOpen", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnVendorOpen(uint vendorId) => Runtime.OnVendorOpen(vendorId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnVendorClose", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnVendorClose(uint vendorId) => Runtime.OnVendorClose(vendorId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnBusyCountIncremented", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnBusyCountIncremented() => Runtime.OnBusyCountIncremented();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnBusyCountDecremented", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnBusyCountDecremented() => Runtime.OnBusyCountDecremented();
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnSmartBoxEvent", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnSmartBoxEvent(uint opcode, uint blobSize, uint status) => Runtime.OnSmartBoxEvent(opcode, blobSize, status);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnCombatModeChange", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnCombatModeChange(int currentCombatMode, int previousCombatMode) =>
Runtime.OnCombatModeChange(currentCombatMode, previousCombatMode);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnUpdateHealth", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth) =>
Runtime.OnUpdateHealth(targetId, healthRatio, currentHealth, maxHealth);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnEnchantmentAdded", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnEnchantmentAdded(uint spellId, double durationSeconds) =>
Runtime.OnEnchantmentAdded(spellId, durationSeconds);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnEnchantmentRemoved", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnEnchantmentRemoved(uint enchantmentId) => Runtime.OnEnchantmentRemoved(enchantmentId);
}

View file

@ -0,0 +1,103 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<!--
TFMs: THIS PROJECT IS net10.0-windows ONLY (RynthCore NativeAOT plugin, win-x86).
Do NOT add net48 here — classic Utility Belt / UB-ILT (Decal) builds net48 in UB/ and ub-IT/
(UtilityBelt.csproj multi-TFM). ub-Rythai is a separate deliverable: .NET 10 vs .NET Framework 4.8.
-->
<!-- Previous release: 3.1.13. -->
<Version>3.1.15</Version>
<AssemblyVersion>3.1.15.0</AssemblyVersion>
<FileVersion>3.1.15.0</FileVersion>
<InformationalVersion>3.1.15</InformationalVersion>
<TargetFramework>net10.0-windows</TargetFramework>
<PlatformTarget>x86</PlatformTarget>
<RuntimeIdentifier>win-x86</RuntimeIdentifier>
<OutputType>Library</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Nullable>enable</Nullable>
<PublishAot>true</PublishAot>
<NativeLib>Shared</NativeLib>
<InvariantGlobalization>true</InvariantGlobalization>
<IlcOptimizationPreference>Size</IlcOptimizationPreference>
<StripSymbols>false</StripSymbols>
<RootNamespace>RynthCore.Plugin.UbRythai</RootNamespace>
<AssemblyName>RynthCore.Plugin.UbRythai</AssemblyName>
<Platforms>x86</Platforms>
<!-- Sibling RynthCore checkout: <workspace>\RynthCore beside <workspace>\RynthSuite (this project lives in RynthSuite\Plugins\ub-Rythai\<project>\). -->
<RynthCoreRoot Condition="'$(RynthCoreRoot)' == ''">$(MSBuildThisFileDirectory)..\..\..\..\RynthCore\</RynthCoreRoot>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="ImGui.NET" Version="1.91.6.1" />
</ItemGroup>
<ItemGroup>
<TrimmerRootAssembly Include="ImGui.NET" />
</ItemGroup>
<ItemGroup>
<!-- ImGui text calls for non-literal text ('%' escaped): see the file's header. -->
<Compile Include="..\..\Shared\SafeImGui.cs" Link="Shared\SafeImGui.cs" />
<!-- RynthCore's server list (API v86) and the active server's settings: ILT Auto follows the engine. -->
<Compile Include="..\..\Shared\EngineServerState.cs" Link="Shared\EngineServerState.cs" />
<Compile Include="..\..\Shared\ServerStateClient.cs" Link="Shared\ServerStateClient.cs" />
<Compile Include="..\..\Shared\RynthServerProfileApi.cs" Link="Shared\RynthServerProfileApi.cs" />
<Compile Include="..\..\Shared\RynthIltServerApi.cs" Link="Shared\RynthIltServerApi.cs" />
<!-- XP meter (3.1.13): RynthAi's session through "RynthAi.Hub" when loaded, else the shared
SessionStats formula RynthAi and RynthTracker use (one way to count XP and luminance). -->
<Compile Include="..\..\Shared\RynthAiHubApi.cs" Link="Shared\RynthAiHubApi.cs" />
<Compile Include="..\..\Shared\RynthAiSessionClient.cs" Link="Shared\RynthAiSessionClient.cs" />
<Compile Include="..\..\Shared\SessionStats.cs" Link="Shared\SessionStats.cs" />
<Compile Include="..\..\Shared\KillCounter.cs" Link="Shared\KillCounter.cs" />
<Compile Include="..\..\Shared\CombatText.cs" Link="Shared\CombatText.cs" />
<Compile Include="..\..\Shared\TrackerSessionStore.cs" Link="Shared\TrackerSessionStore.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="$(RynthCoreRoot)src\RynthCore.PluginCore\RynthCore.PluginCore.csproj" />
<ProjectReference Include="$(RynthCoreRoot)src\RynthCore.PluginSdk\RynthCore.PluginSdk.csproj" />
</ItemGroup>
<Target Name="CopyPublishedPluginToEngineOutputs" AfterTargets="Publish" Condition="'$(PublishDir)' != ''">
<ItemGroup>
<_EnginePluginDir Include="$(RynthCoreRoot)src\RynthCore.Engine\bin\$(Configuration)\net10.0-windows\win-x86\Plugins\" />
<_EnginePluginDir Include="$(RynthCoreRoot)src\RynthCore.Engine\bin\$(PlatformTarget)\$(Configuration)\net10.0-windows\win-x86\Plugins\" />
<_EnginePluginPublishDir Include="$(RynthCoreRoot)src\RynthCore.Engine\bin\$(Configuration)\net10.0-windows\win-x86\publish\Plugins\" />
<_EnginePluginPublishDir Include="$(RynthCoreRoot)src\RynthCore.Engine\bin\$(PlatformTarget)\$(Configuration)\net10.0-windows\win-x86\publish\Plugins\" />
</ItemGroup>
<MakeDir Directories="@(_EnginePluginDir)" />
<MakeDir Directories="@(_EnginePluginPublishDir)" />
<Copy
SourceFiles="$(PublishDir)$(AssemblyName).dll"
DestinationFolder="%(_EnginePluginDir.Identity)"
SkipUnchangedFiles="true"
Condition="Exists('$(PublishDir)$(AssemblyName).dll')" />
<Copy
SourceFiles="$(PublishDir)$(AssemblyName).pdb"
DestinationFolder="%(_EnginePluginDir.Identity)"
SkipUnchangedFiles="true"
Condition="Exists('$(PublishDir)$(AssemblyName).pdb')" />
<Copy
SourceFiles="$(PublishDir)$(AssemblyName).dll"
DestinationFolder="%(_EnginePluginPublishDir.Identity)"
SkipUnchangedFiles="true"
Condition="Exists('$(PublishDir)$(AssemblyName).dll')" />
<Copy
SourceFiles="$(PublishDir)$(AssemblyName).pdb"
DestinationFolder="%(_EnginePluginPublishDir.Identity)"
SkipUnchangedFiles="true"
Condition="Exists('$(PublishDir)$(AssemblyName).pdb')" />
</Target>
<Target Name="RemoveBundledImGuiNativeFromBuild" AfterTargets="Build">
<Delete Files="$(OutputPath)cimgui.dll" Condition="Exists('$(OutputPath)cimgui.dll')" />
</Target>
<Target Name="RemoveBundledImGuiNativeFromPublish" AfterTargets="Publish" Condition="'$(PublishDir)' != ''">
<Delete Files="$(PublishDir)cimgui.dll" Condition="Exists('$(PublishDir)cimgui.dll')" />
</Target>
</Project>

View file

@ -0,0 +1,333 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.UbRythai;
/// <summary>
/// Chat command queues for ub-Rythai (.NET 10 RynthCore plugin): login batch and periodic batch,
/// sent via <see cref="RynthCoreHost.InvokeChatParser"/> (not the net48 Decal host).
/// </summary>
internal sealed class UbRythaiChatCommandAutomation
{
private const int MaxLoginDiagnostics = 100;
private readonly RynthCoreHost _host;
private readonly Func<UbRythaiSettings> _getSettings;
private readonly Action<UbRythaiLogLevel, string> _log;
private readonly Func<string, string, bool> _dispatchChatCommand;
private bool _loginBatchActive;
private int _loginCursor;
private DateTime _nextLoginInvokeUtc = DateTime.MinValue;
private bool _periodicBatchActive;
private int _periodicCursor;
private DateTime _nextPeriodicInvokeUtc = DateTime.MinValue;
private DateTime _lastPeriodicCycleCompleteUtc = DateTime.MinValue;
private bool _gapWaitLogin;
private bool _gapWaitPeriodic;
private readonly List<LoginQueueDiagnostic> _loginDiagnostics = [];
public UbRythaiChatCommandAutomation(
RynthCoreHost host,
Func<UbRythaiSettings> getSettings,
Action<UbRythaiLogLevel, string> log,
Func<string, string, bool> dispatchChatCommand)
{
_host = host;
_getSettings = getSettings;
_log = log;
_dispatchChatCommand = dispatchChatCommand;
}
public void OnLoginComplete()
{
UbRythaiSettings s = _getSettings();
_loginBatchActive = s.LoginCommandsEnabled && HasNonEmptyLines(s.LoginCommandsText);
_loginCursor = 0;
_gapWaitLogin = false;
if (_loginBatchActive)
{
int initialMs = ClampMs(s.LoginCommandsInitialDelayMs, 0, 120_000);
_nextLoginInvokeUtc = DateTime.UtcNow.AddMilliseconds(initialMs);
_log(UbRythaiLogLevel.Info, $"ub-rythai: login queue scheduled ({CountLines(s.LoginCommandsText)} line(s), initial delay {initialMs} ms).");
}
else
{
_nextLoginInvokeUtc = DateTime.MinValue;
}
_lastPeriodicCycleCompleteUtc = DateTime.UtcNow;
_periodicBatchActive = false;
_periodicCursor = 0;
_gapWaitPeriodic = false;
}
public void RequestLoginQueueReplay()
{
UbRythaiSettings s = _getSettings();
if (!s.LoginCommandsEnabled)
{
_log(UbRythaiLogLevel.Warn, "ub-rythai: login queue disabled (open ub-Rythai window from bar action).");
return;
}
if (!HasNonEmptyLines(s.LoginCommandsText))
{
_log(UbRythaiLogLevel.Warn, "ub-rythai: login queue text is empty.");
return;
}
_loginBatchActive = true;
_loginCursor = 0;
_gapWaitLogin = false;
_nextLoginInvokeUtc = DateTime.UtcNow.AddMilliseconds(ClampMs(s.LoginCommandsInitialDelayMs, 0, 120_000));
_log(UbRythaiLogLevel.Info, "ub-rythai: login queue replay requested.");
}
public void OnTick()
{
if (!_host.HasInvokeChatParser)
return;
UbRythaiSettings s = _getSettings();
DateTime now = DateTime.UtcNow;
if (_loginBatchActive && s.LoginCommandsEnabled)
TickLoginQueue(s, now);
else if (_periodicBatchActive || ShouldStartPeriodicCycle(s, now))
TickPeriodicQueue(s, now);
}
public string GetPeriodicStatusLine()
{
UbRythaiSettings s = _getSettings();
if (!s.PeriodicCommandsEnabled)
return "periodic: disabled.";
int n = CountLines(s.PeriodicCommandsText);
if (n == 0)
return "periodic: enabled, no lines.";
return string.Format(CultureInfo.InvariantCulture,
"periodic: enabled, {0} line(s), interval {1}s, batchActive={2}, cursor={3}, lastCycleUtc={4:O}",
n, s.PeriodicIntervalSeconds, _periodicBatchActive, _periodicCursor, _lastPeriodicCycleCompleteUtc);
}
public string GetLoginQueueDiagnosticsStatusLine()
{
int success = 0;
int failed = 0;
for (int i = 0; i < _loginDiagnostics.Count; i++)
{
if (_loginDiagnostics[i].Success) success++;
else failed++;
}
return string.Format(
CultureInfo.InvariantCulture,
"loginq diag: attempts={0}, ok={1}, fail={2}, batchActive={3}, cursor={4}",
_loginDiagnostics.Count, success, failed, _loginBatchActive, _loginCursor);
}
public IReadOnlyList<LoginQueueDiagnostic> GetLoginQueueDiagnosticsSnapshot() => _loginDiagnostics;
public void ClearLoginQueueDiagnostics()
{
_loginDiagnostics.Clear();
}
private void TickLoginQueue(UbRythaiSettings s, DateTime now)
{
if (!s.LoginCommandsEnabled)
{
_loginBatchActive = false;
return;
}
List<ParsedCommandLine> lines = ParseCommandLines(s.LoginCommandsText);
if (_loginCursor >= lines.Count)
{
_loginBatchActive = false;
_log(UbRythaiLogLevel.Info, "ub-rythai: login queue finished.");
return;
}
int gap = ClampMs(s.LoginCommandsGapMs, 50, 60_000);
if (_gapWaitLogin)
{
if (now < _nextLoginInvokeUtc)
return;
_gapWaitLogin = false;
}
if (now < _nextLoginInvokeUtc)
return;
ParsedCommandLine line = lines[_loginCursor];
_loginCursor++;
if (!TryInvokeLine(line.Command, "login queue", true, line.SourceLine))
return;
_gapWaitLogin = true;
_nextLoginInvokeUtc = now.AddMilliseconds(gap);
}
private bool ShouldStartPeriodicCycle(UbRythaiSettings s, DateTime now)
{
if (!s.PeriodicCommandsEnabled || !HasNonEmptyLines(s.PeriodicCommandsText))
return false;
if (_periodicBatchActive)
return false;
int intervalSec = Math.Clamp(s.PeriodicIntervalSeconds, 5, 86_400);
double elapsed = (now - _lastPeriodicCycleCompleteUtc).TotalSeconds;
return elapsed >= intervalSec;
}
private void TickPeriodicQueue(UbRythaiSettings s, DateTime now)
{
if (!s.PeriodicCommandsEnabled)
{
_periodicBatchActive = false;
return;
}
List<ParsedCommandLine> lines = ParseCommandLines(s.PeriodicCommandsText);
if (lines.Count == 0)
{
_periodicBatchActive = false;
return;
}
if (!_periodicBatchActive)
{
_periodicBatchActive = true;
_periodicCursor = 0;
_gapWaitPeriodic = false;
_nextPeriodicInvokeUtc = now;
}
if (_periodicCursor >= lines.Count)
{
_periodicBatchActive = false;
_lastPeriodicCycleCompleteUtc = now;
_log(UbRythaiLogLevel.Info, "ub-rythai: periodic batch finished.");
return;
}
int gap = ClampMs(s.PeriodicCommandsGapMs, 50, 60_000);
if (_gapWaitPeriodic)
{
if (now < _nextPeriodicInvokeUtc)
return;
_gapWaitPeriodic = false;
}
if (now < _nextPeriodicInvokeUtc)
return;
ParsedCommandLine line = lines[_periodicCursor];
_periodicCursor++;
if (!TryInvokeLine(line.Command, "periodic queue", false, line.SourceLine))
return;
_gapWaitPeriodic = true;
_nextPeriodicInvokeUtc = now.AddMilliseconds(gap);
}
private bool TryInvokeLine(string line, string source, bool trackLoginDiagnostics, int sourceLine)
{
try
{
bool ok = _dispatchChatCommand(line, source);
if (trackLoginDiagnostics)
{
AddLoginDiagnostic(new LoginQueueDiagnostic(
DateTime.UtcNow,
sourceLine,
Truncate(line, 100),
ok,
ok ? "dispatched" : "dispatch blocked or failed"));
}
if (!ok)
_log(UbRythaiLogLevel.Warn, $"ub-rythai: dispatch blocked/failed for {source}: {Truncate(line, 120)}");
return ok;
}
catch (Exception ex)
{
if (trackLoginDiagnostics)
{
AddLoginDiagnostic(new LoginQueueDiagnostic(
DateTime.UtcNow,
sourceLine,
Truncate(line, 100),
false,
$"exception: {ex.Message}"));
}
_log(UbRythaiLogLevel.Error, $"ub-rythai: InvokeChatParser exception: {ex.Message}");
return false;
}
}
private static List<ParsedCommandLine> ParseCommandLines(string blob)
{
var list = new List<ParsedCommandLine>();
if (string.IsNullOrWhiteSpace(blob))
return list;
int sourceLine = 1;
foreach (ReadOnlySpan<char> raw in blob.AsSpan().EnumerateLines())
{
string line = raw.Trim().ToString();
if (line.Length == 0)
{
sourceLine++;
continue;
}
if (line.StartsWith('#') || line.StartsWith("//", StringComparison.Ordinal))
{
sourceLine++;
continue;
}
list.Add(new ParsedCommandLine(sourceLine, line));
sourceLine++;
}
return list;
}
private static bool HasNonEmptyLines(string blob) => ParseCommandLines(blob).Count > 0;
private static int CountLines(string blob) => ParseCommandLines(blob).Count;
private void AddLoginDiagnostic(LoginQueueDiagnostic diagnostic)
{
_loginDiagnostics.Add(diagnostic);
if (_loginDiagnostics.Count > MaxLoginDiagnostics)
_loginDiagnostics.RemoveAt(0);
}
private static int ClampMs(int value, int min, int max)
{
if (value < min) return min;
if (value > max) return max;
return value;
}
private static string Truncate(string s, int maxLen)
{
if (s.Length <= maxLen)
return s;
return s.Substring(0, maxLen) + "...";
}
internal readonly record struct LoginQueueDiagnostic(
DateTime TimestampUtc,
int SourceLine,
string CommandPreview,
bool Success,
string Detail);
private readonly record struct ParsedCommandLine(int SourceLine, string Command);
}

View file

@ -0,0 +1,74 @@
using System;
using System.IO;
using System.Text;
namespace RynthCore.Plugin.UbRythai;
/// <summary>
/// Built-in rolling file logger for ub-Rythai.
/// Writes to the local install folder under "Logs" and rolls by size.
/// </summary>
internal sealed class UbRythaiFileLogger
{
private const long MaxBytesPerFile = 5 * 1024 * 1024; // 5 MB
private const int MaxRolledFiles = 10;
private readonly object _sync = new();
private readonly string _logsDir;
private readonly string _activeFilePath;
public UbRythaiFileLogger(string installBaseDir)
{
// Keep logs colocated with the local runtime install for easy support collection.
_logsDir = Path.Combine(installBaseDir, "Logs");
_activeFilePath = Path.Combine(_logsDir, "ub-Rythai.log");
}
/// <summary>
/// Writes one log line if <paramref name="level"/> is enabled by <paramref name="minimumLevel"/>.
/// </summary>
public void Write(UbRythaiLogLevel level, UbRythaiLogLevel minimumLevel, string message)
{
if (level < minimumLevel)
return;
lock (_sync)
{
Directory.CreateDirectory(_logsDir);
RollIfNeeded();
string line = $"{DateTime.UtcNow:O} [{level}] {message}{Environment.NewLine}";
File.AppendAllText(_activeFilePath, line, Encoding.UTF8);
}
}
private void RollIfNeeded()
{
if (!File.Exists(_activeFilePath))
return;
var fi = new FileInfo(_activeFilePath);
if (fi.Length < MaxBytesPerFile)
return;
string rolledName = $"ub-Rythai-{DateTime.UtcNow:yyyyMMdd-HHmmss}.log";
string rolledPath = Path.Combine(_logsDir, rolledName);
File.Move(_activeFilePath, rolledPath, overwrite: true);
string[] rolled = Directory.GetFiles(_logsDir, "ub-Rythai-*.log");
Array.Sort(rolled, StringComparer.OrdinalIgnoreCase);
int extra = rolled.Length - MaxRolledFiles;
for (int i = 0; i < extra; i++)
{
try
{
File.Delete(rolled[i]);
}
catch
{
// Best-effort retention cleanup; logging should continue even if deletion fails.
}
}
}
}

View file

@ -0,0 +1,8 @@
using System.Text.Json.Serialization;
namespace RynthCore.Plugin.UbRythai;
/// <summary>Source-generated JSON serializer context for NativeAOT-safe settings persistence.</summary>
[JsonSerializable(typeof(UbRythaiSettings))]
[JsonSourceGenerationOptions(WriteIndented = true)]
internal partial class UbRythaiJsonContext : JsonSerializerContext;

View file

@ -0,0 +1,14 @@
namespace RynthCore.Plugin.UbRythai;
/// <summary>
/// Log levels for ub-Rythai file logging.
/// Lower numeric value means more verbose output.
/// </summary>
internal enum UbRythaiLogLevel
{
Trace = 0,
Debug = 1,
Info = 2,
Warn = 3,
Error = 4
}

View file

@ -0,0 +1,167 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace RynthCore.Plugin.UbRythai;
/// <summary>
/// ub-IT's PeriodicCommandsTool list ("/ub periodic add|remove|toggle|list|clear"): each entry is
/// a chat command with its own interval in minutes. Stored in
/// <see cref="UbRythaiSettings.PeriodicEntriesText"/>, one "minutes|on|command" line per entry, so
/// it saves with the character's other ub-Rythai settings. This is separate from the
/// settings-window periodic batch (all lines on one interval), which keeps working as before.
/// </summary>
internal sealed class UbRythaiPeriodicEntries
{
internal readonly record struct Entry(int IntervalMinutes, bool Enabled, string Command);
private readonly Func<UbRythaiSettings> _getSettings;
private readonly Func<string, string, bool> _dispatch;
private readonly Action<string> _say;
private readonly Action _save;
// When each entry (by its text) last ran. Entries start their clock at login (or when added),
// as ub-IT's timer does, rather than all firing on the first tick.
private readonly Dictionary<string, DateTime> _lastRunUtc = new(StringComparer.Ordinal);
public UbRythaiPeriodicEntries(Func<UbRythaiSettings> getSettings, Func<string, string, bool> dispatch,
Action<string> say, Action save)
{
_getSettings = getSettings;
_dispatch = dispatch;
_say = say;
_save = save;
}
/// <summary>Restarts every entry's clock (login).</summary>
public void Reset() => _lastRunUtc.Clear();
/// <summary>Runs every enabled entry whose interval has passed. Plugin tick.</summary>
public void OnTick(DateTime nowUtc)
{
List<Entry> list = Parse(_getSettings().PeriodicEntriesText);
for (int i = 0; i < list.Count; i++)
{
Entry e = list[i];
string key = Key(i, e);
if (!_lastRunUtc.TryGetValue(key, out DateTime last))
{
_lastRunUtc[key] = nowUtc;
continue;
}
if (!e.Enabled || (nowUtc - last).TotalMinutes < e.IntervalMinutes)
continue;
_lastRunUtc[key] = nowUtc;
_dispatch(e.Command, "periodic entry");
}
}
/// <summary>"/ub periodic &lt;verb&gt; [args]" for the list verbs. Returns false for any other verb.</summary>
public bool HandleCommand(string verb, string args)
{
switch (verb.ToLowerInvariant())
{
case "add": Add(args); return true;
case "remove": Remove(args); return true;
case "toggle": Toggle(args); return true;
case "list": ListAll(); return true;
case "clear": Write(new List<Entry>()); _say("periodic clear: all periodic commands removed"); return true;
default: return false;
}
}
private void Add(string args)
{
string[] p = (args ?? "").Trim().Split(' ', 2, StringSplitOptions.RemoveEmptyEntries);
if (p.Length < 2 || !int.TryParse(p[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out int minutes) || minutes < 1)
{
_say("Usage: /ub periodic add <minutes> <command> (minutes is a positive whole number)");
return;
}
List<Entry> list = Parse(_getSettings().PeriodicEntriesText);
list.Add(new Entry(minutes, true, p[1].Trim()));
Write(list);
_say($"periodic add: added [{minutes}m] {p[1].Trim()} (entry #{list.Count})");
}
private void Remove(string args)
{
List<Entry> list = Parse(_getSettings().PeriodicEntriesText);
if (!TryIndex(args, list.Count, "remove", out int idx)) return;
Entry removed = list[idx];
list.RemoveAt(idx);
Write(list);
_say($"periodic remove: removed entry #{idx + 1}: [{removed.IntervalMinutes}m] {removed.Command}");
}
private void Toggle(string args)
{
List<Entry> list = Parse(_getSettings().PeriodicEntriesText);
if (!TryIndex(args, list.Count, "toggle", out int idx)) return;
Entry e = list[idx] with { Enabled = !list[idx].Enabled };
list[idx] = e;
Write(list);
_say($"periodic toggle: entry #{idx + 1} is now {(e.Enabled ? "enabled" : "disabled")}");
}
private void ListAll()
{
List<Entry> list = Parse(_getSettings().PeriodicEntriesText);
if (list.Count == 0) { _say("periodic list: no commands configured"); return; }
_say($"periodic list ({list.Count} entries):");
for (int i = 0; i < list.Count; i++)
_say($" [{i + 1}] every {list[i].IntervalMinutes}m {(list[i].Enabled ? "[ON]" : "[OFF]")} {list[i].Command}");
}
/// <summary>A 1-based index from the command, as ub-IT takes it; 0-based out.</summary>
private bool TryIndex(string args, int count, string verb, out int idx)
{
idx = -1;
if (!int.TryParse((args ?? "").Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int n) || n < 1)
{
_say($"Usage: /ub periodic {verb} <N> (1-based index)");
return false;
}
if (n > count)
{
_say($"periodic {verb}: index {n} out of range (1-{count})");
return false;
}
idx = n - 1;
return true;
}
private void Write(List<Entry> list)
{
_getSettings().PeriodicEntriesText = Format(list);
_lastRunUtc.Clear();
_save();
}
private static string Key(int index, Entry e) => index.ToString(CultureInfo.InvariantCulture) + "|" + e.Command;
/// <summary>Parses "minutes|on|command" lines; malformed lines are skipped.</summary>
internal static List<Entry> Parse(string? text)
{
var list = new List<Entry>();
if (string.IsNullOrWhiteSpace(text)) return list;
foreach (string raw in text.Split('\n'))
{
string[] p = raw.Trim().Split('|', 3);
if (p.Length < 3 || p[2].Trim().Length == 0) continue;
if (!int.TryParse(p[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out int minutes) || minutes < 1) continue;
list.Add(new Entry(minutes, p[1].Trim().Equals("on", StringComparison.OrdinalIgnoreCase), p[2].Trim()));
}
return list;
}
internal static string Format(List<Entry> list)
{
var sb = new StringBuilder();
foreach (Entry e in list)
sb.Append(e.IntervalMinutes.ToString(CultureInfo.InvariantCulture)).Append('|')
.Append(e.Enabled ? "on" : "off").Append('|').Append(e.Command).Append('\n');
return sb.ToString();
}
}

View file

@ -0,0 +1,458 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
using ImGuiNET;
using System.Numerics;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.UbRythai;
public sealed partial class UbRythaiPlugin
{
private enum BankTransferItem
{
Pyreals,
Luminance,
LegendaryKeys,
MythicalKeys,
EnlightenedCoins,
WeaklyEnlightenedCoins,
}
private struct UbBankData
{
public long Pyreals;
public long Luminance;
public int LegendaryKeys;
public int MythicalKeys;
public int EnlightenedCoins;
public int WeaklyEnlightenedCoins;
public DateTime LastUpdatedUtc;
}
private static readonly string[] _leaftideModeLabels = { "Auto", "On", "Off" };
private static readonly string[] _bankTransferItemLabels =
{
"Pyreals", "Luminance", "Legendary Keys", "Mythical Keys", "Enlightened Coins", "Weakly Enlightened Coins"
};
private UbBankData _bankData;
private DateTime _lastBankRefreshUtc = DateTime.MinValue;
private DateTime _nextBankRefreshUtc = DateTime.MinValue;
private DateTime _nextAutoTransferUtc = DateTime.MinValue;
private bool _bankRefreshPending;
private string _bankTransferAmountText = "";
private string _bankTransferTargetText = "";
private int _bankTransferItemIndex;
private static string NormalizeLeaftideMode(string? mode)
{
if (string.IsNullOrWhiteSpace(mode))
return "Auto";
return mode.Trim().ToLowerInvariant() switch
{
"on" => "On",
"off" => "Off",
_ => "Auto",
};
}
/// <summary>RynthCore's server list (API v86): Auto follows its verdict, overrides and Diagnostics pick included.</summary>
private readonly ServerStateClient _serverState = new();
/// <summary>Polls RynthCore's server list (every 2 s, cheap when not due). Pump thread.</summary>
private void PollServerState(bool force = false) => _serverState.Poll(Host, Environment.TickCount64, force);
private bool CurrentWorldMatchesLeaftideAutoList()
{
string worldName = Host.HasGetWorldName && Host.TryGetWorldName(out string w) ? w.Trim() : "";
string[] tokens = (_settings.LeaftideAutoWorldNames ?? "")
.Split([',', ';', '\r', '\n'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
if (tokens.Length == 0)
return false;
// Engines with GetServerStateJson decide (the same verdict as RynthCore's menus); older ones: the world name.
PollServerState();
return EngineServerState.MatchesNameList(_serverState.State, worldName, tokens);
}
private bool IsLeaftideFeaturesEnabled()
{
return NormalizeLeaftideMode(_settings.LeaftideFeaturesMode) switch
{
"On" => true,
"Off" => false,
_ => CurrentWorldMatchesLeaftideAutoList(),
};
}
private bool IsLeaftideBankingEnabled()
{
string mode = NormalizeLeaftideMode(_settings.LeaftideFeaturesMode);
if (mode == "Off")
return false;
if (mode == "On")
return _settings.LeaftideManualAllowBanking;
return CurrentWorldMatchesLeaftideAutoList();
}
private void HandleLeaftideCommand(string[] parts)
{
string action = parts.Length >= 3 ? (parts[2] ?? "").Trim().ToLowerInvariant() : "";
if (action is "on" or "off" or "auto")
{
_settings.LeaftideFeaturesMode = action switch
{
"on" => "On",
"off" => "Off",
_ => "Auto",
};
Host.WriteToChat($"[ub-Rythai] ILT mode set to {_settings.LeaftideFeaturesMode}.", 1);
return;
}
string worldName = "(unknown)";
if (Host.HasGetWorldName && Host.TryGetWorldName(out string world) && !string.IsNullOrWhiteSpace(world))
worldName = world.Trim();
bool autoMatch = CurrentWorldMatchesLeaftideAutoList();
bool iltEnabled = IsLeaftideFeaturesEnabled();
bool bankEnabled = IsLeaftideBankingEnabled();
Host.WriteToChat(
$"[ub-Rythai] ILT mode={NormalizeLeaftideMode(_settings.LeaftideFeaturesMode)} | features={(iltEnabled ? "ON" : "OFF")} | banking={(bankEnabled ? "ON" : "OFF")} | world='{worldName}' | autoMatch={(autoMatch ? "yes" : "no")} | names='{_settings.LeaftideAutoWorldNames}'",
1);
EngineServerState? es = _serverState.State;
Host.WriteToChat(es == null
? "[ub-Rythai] RynthCore server: not reported (engine older than API v86) - Auto uses the world name."
: $"[ub-Rythai] RynthCore server: {(es.HasActive ? es.ActiveName + " (" + es.Active + ")" : "none active")} | pick={es.Pick} | settings from {(es.ActivePlugin.Length > 0 ? es.ActivePlugin : "-")}",
1);
Host.WriteToChat("[ub-Rythai] Usage: /ub leaftide on|off|auto", 1);
}
private void HandleBankCommand(string[] parts, string rawText)
{
if (!_settings.BankToolsEnabled)
{
Host.WriteToChat("[ub-Rythai] banking tools are disabled in settings.", 1);
return;
}
if (!IsLeaftideBankingEnabled())
{
Host.WriteToChat("[ub-Rythai] banking is gated off (use /ub leaftide, auto world list, or manual banking flag).", 1);
return;
}
string action = parts.Length >= 3 ? (parts[2] ?? "").Trim().ToLowerInvariant() : "status";
if (action == "status")
{
Host.WriteToChat(
$"[ub-Rythai] bank: updated={( _bankData.LastUpdatedUtc == DateTime.MinValue ? "never" : _bankData.LastUpdatedUtc.ToLocalTime().ToString("HH:mm:ss"))}, p={_bankData.Pyreals:N0}, lum={_bankData.Luminance:N0}, lk={_bankData.LegendaryKeys:N0}, mk={_bankData.MythicalKeys:N0}, ec={_bankData.EnlightenedCoins:N0}, wec={_bankData.WeaklyEnlightenedCoins:N0}",
1);
return;
}
if (action == "refresh")
{
RequestBankRefresh("manual");
return;
}
if (action == "transfer")
{
if (parts.Length < 6)
{
Host.WriteToChat("[ub-Rythai] Usage: /ub bank transfer <p|l|k|mk|e|we> <amount> <target>", 1);
return;
}
if (!TryParseBankTransferItem(parts[3], out BankTransferItem item))
{
Host.WriteToChat("[ub-Rythai] transfer type must be p|l|k|mk|e|we.", 1);
return;
}
long amount = ParseBankAmount(parts[4]);
if (amount <= 0)
{
Host.WriteToChat("[ub-Rythai] transfer amount must be > 0 (supports k/m/b/t suffix).", 1);
return;
}
int targetStart = rawText.IndexOf(parts[5], StringComparison.Ordinal);
string target = targetStart >= 0 ? rawText[targetStart..].Trim().Trim('"') : parts[5].Trim().Trim('"');
string? transferCommand = BuildBankTransferCommand(item, amount, target);
if (string.IsNullOrWhiteSpace(transferCommand))
{
Host.WriteToChat("[ub-Rythai] invalid transfer target.", 1);
return;
}
if (TryDispatchChatCommand(transferCommand, "bank transfer"))
{
Host.WriteToChat($"[ub-Rythai] sent {GetBankTransferItemDisplayName(item)} transfer: {amount:N0} to {target}.", 1);
}
else
{
Host.WriteToChat("[ub-Rythai] transfer command dispatch failed.", 1);
}
return;
}
Host.WriteToChat("[ub-Rythai] Usage: /ub bank status|refresh|transfer <p|l|k|mk|e|we> <amount> <target>", 1);
}
private void RequestBankRefresh(string reason)
{
if (!Host.HasInvokeChatParser)
return;
_bankRefreshPending = true;
_nextBankRefreshUtc = DateTime.UtcNow.AddMilliseconds(250);
LogAt(UbRythaiLogLevel.Debug, $"queued /bank refresh ({reason}).");
}
private void TickBanking()
{
if (!_settings.BankToolsEnabled || !IsLeaftideBankingEnabled() || !Host.HasInvokeChatParser)
return;
if (_bankRefreshPending && DateTime.UtcNow >= _nextBankRefreshUtc)
{
if ((DateTime.UtcNow - _lastBankRefreshUtc).TotalSeconds >= 2 &&
TryDispatchChatCommand("/bank", "bank refresh"))
{
_lastBankRefreshUtc = DateTime.UtcNow;
_bankRefreshPending = false;
}
}
if (_settings.BankAutoTransferEnabled)
TickAutoTransfer();
}
private void TickAutoTransfer()
{
if (DateTime.UtcNow < _nextAutoTransferUtc)
return;
int intervalMinutes = Math.Clamp(_settings.BankAutoTransferIntervalMinutes, 1, 240);
_nextAutoTransferUtc = DateTime.UtcNow.AddMinutes(intervalMinutes);
string target = (_settings.BankAutoTransferTarget ?? "").Trim().Trim('"');
if (string.IsNullOrWhiteSpace(target))
return;
int pct = Math.Clamp(_settings.BankAutoTransferPercent, 1, 100);
int sent = 0;
sent += TryAutoTransferItem(_settings.BankAutoTransferPyreals, BankTransferItem.Pyreals, _bankData.Pyreals, pct, target);
sent += TryAutoTransferItem(_settings.BankAutoTransferLuminance, BankTransferItem.Luminance, _bankData.Luminance, pct, target);
sent += TryAutoTransferItem(_settings.BankAutoTransferLegendaryKeys, BankTransferItem.LegendaryKeys, _bankData.LegendaryKeys, pct, target);
sent += TryAutoTransferItem(_settings.BankAutoTransferMythicalKeys, BankTransferItem.MythicalKeys, _bankData.MythicalKeys, pct, target);
sent += TryAutoTransferItem(_settings.BankAutoTransferEnlightenedCoins, BankTransferItem.EnlightenedCoins, _bankData.EnlightenedCoins, pct, target);
sent += TryAutoTransferItem(_settings.BankAutoTransferWeaklyEnlightenedCoins, BankTransferItem.WeaklyEnlightenedCoins, _bankData.WeaklyEnlightenedCoins, pct, target);
if (sent > 0)
RequestBankRefresh("auto-transfer follow-up");
}
private int TryAutoTransferItem(bool enabled, BankTransferItem item, long currentBalance, int pct, string target)
{
if (!enabled || currentBalance <= 0)
return 0;
long amount = (long)Math.Floor(currentBalance * (pct / 100.0));
if (amount <= 0)
return 0;
string? cmd = BuildBankTransferCommand(item, amount, target);
if (string.IsNullOrWhiteSpace(cmd))
return 0;
return TryDispatchChatCommand(cmd, "bank auto-transfer") ? 1 : 0;
}
private void TryParseBankChatLine(string line)
{
if (!_settings.BankToolsEnabled || !IsLeaftideBankingEnabled())
return;
if (string.IsNullOrWhiteSpace(line) || !line.Contains("[BANK]", StringComparison.OrdinalIgnoreCase))
return;
bool changed = false;
changed |= TryParseBankCurrencyLine(line, "Pyreals:", v => _bankData.Pyreals = v);
changed |= TryParseBankCurrencyLine(line, "Luminance:", v => _bankData.Luminance = v);
changed |= TryParseBankCurrencyLine(line, "Legendary Keys:", v => _bankData.LegendaryKeys = (int)Math.Clamp(v, 0, int.MaxValue));
changed |= TryParseBankCurrencyLine(line, "Mythical Keys:", v => _bankData.MythicalKeys = (int)Math.Clamp(v, 0, int.MaxValue));
changed |= TryParseBankCurrencyLine(line, "Enlightened Coins:", v => _bankData.EnlightenedCoins = (int)Math.Clamp(v, 0, int.MaxValue));
changed |= TryParseBankCurrencyLine(line, "Weakly Enlightened Coins:", v => _bankData.WeaklyEnlightenedCoins = (int)Math.Clamp(v, 0, int.MaxValue));
if (changed)
_bankData.LastUpdatedUtc = DateTime.UtcNow;
}
private static bool TryParseBankCurrencyLine(string line, string marker, Action<long> set)
{
int idx = line.IndexOf(marker, StringComparison.OrdinalIgnoreCase);
if (idx < 0)
return false;
string valuePart = line[(idx + marker.Length)..].Trim();
Match m = Regex.Match(valuePart, @"^(?<num>[\d,]+)");
if (!m.Success)
return false;
if (!long.TryParse(m.Groups["num"].Value.Replace(",", ""), NumberStyles.None, CultureInfo.InvariantCulture, out long parsed))
return false;
set(parsed);
return true;
}
private static bool TryParseBankTransferItem(string token, out BankTransferItem item)
{
item = BankTransferItem.Pyreals;
string normalized = (token ?? "").Trim().ToLowerInvariant();
return normalized switch
{
"p" or "pyreals" => Assign(BankTransferItem.Pyreals, out item),
"l" or "lum" or "luminance" => Assign(BankTransferItem.Luminance, out item),
"k" or "lk" or "legendary" => Assign(BankTransferItem.LegendaryKeys, out item),
"mk" or "mythical" => Assign(BankTransferItem.MythicalKeys, out item),
"e" or "ec" or "enlightened" => Assign(BankTransferItem.EnlightenedCoins, out item),
"we" or "wec" or "weakly" => Assign(BankTransferItem.WeaklyEnlightenedCoins, out item),
_ => false,
};
}
private static bool Assign(BankTransferItem v, out BankTransferItem item)
{
item = v;
return true;
}
private static long ParseBankAmount(string input)
{
if (string.IsNullOrWhiteSpace(input))
return 0;
Match match = Regex.Match(input.Trim().ToLowerInvariant(), @"^(?<num>[\d,.]+)(?<sfx>[kmbt]?)$");
if (!match.Success)
return 0;
if (!double.TryParse(match.Groups["num"].Value.Replace(",", ""), NumberStyles.Float, CultureInfo.InvariantCulture, out double value))
return 0;
value *= match.Groups["sfx"].Value switch
{
"k" => 1_000d,
"m" => 1_000_000d,
"b" => 1_000_000_000d,
"t" => 1_000_000_000_000d,
_ => 1d,
};
return value <= 0 ? 0 : (long)Math.Floor(value);
}
private static string? BuildBankTransferCommand(BankTransferItem item, long amount, string targetName)
{
if (amount <= 0)
return null;
string target = (targetName ?? "").Trim().Trim('"');
if (string.IsNullOrWhiteSpace(target))
return null;
string type = item switch
{
BankTransferItem.Pyreals => "p",
BankTransferItem.Luminance => "l",
BankTransferItem.LegendaryKeys => "k",
BankTransferItem.MythicalKeys => "mk",
BankTransferItem.EnlightenedCoins => "e",
BankTransferItem.WeaklyEnlightenedCoins => "we",
_ => "p",
};
return $"/bank t {type} {amount} {target}";
}
private static string GetBankTransferItemDisplayName(BankTransferItem item)
{
return item switch
{
BankTransferItem.Pyreals => "Pyreals",
BankTransferItem.Luminance => "Luminance",
BankTransferItem.LegendaryKeys => "Legendary Keys",
BankTransferItem.MythicalKeys => "Mythical Keys",
BankTransferItem.EnlightenedCoins => "Enlightened Coins",
BankTransferItem.WeaklyEnlightenedCoins => "Weakly Enlightened Coins",
_ => "Unknown",
};
}
private void RenderIltAndBankUi()
{
ImGui.Spacing();
ImGui.TextColored(new Vector4(0.85f, 0.9f, 1.0f, 1.0f), "P3 ILT Gameplay + Bank");
int modeIndex = NormalizeLeaftideMode(_settings.LeaftideFeaturesMode) switch
{
"On" => 1,
"Off" => 2,
_ => 0,
};
if (ImGui.Combo("ILT mode##iltmode", ref modeIndex, _leaftideModeLabels, _leaftideModeLabels.Length))
_settings.LeaftideFeaturesMode = _leaftideModeLabels[Math.Clamp(modeIndex, 0, _leaftideModeLabels.Length - 1)];
ImGui.InputText("Auto world names##iltautonames", ref _settings.LeaftideAutoWorldNames, 512);
ImGui.Checkbox("Manual On allows banking##iltbankallow", ref _settings.LeaftideManualAllowBanking);
bool autoMatch = CurrentWorldMatchesLeaftideAutoList();
bool iltEnabled = IsLeaftideFeaturesEnabled();
bool bankEnabled = IsLeaftideBankingEnabled();
string world = "(unknown)";
if (Host.HasGetWorldName && Host.TryGetWorldName(out string worldName) && !string.IsNullOrWhiteSpace(worldName))
world = worldName.Trim();
SafeImGui.TextDisabled($"World={world}; autoMatch={(autoMatch ? "yes" : "no")}; features={(iltEnabled ? "ON" : "OFF")}; banking={(bankEnabled ? "ON" : "OFF")}");
ImGui.Checkbox("Enable spellcraft queue (phase-in)##p3sp", ref _settings.EnableSpellcraftQueue);
ImGui.Checkbox("Enable temple/guardian tools (phase-in)##p3tg", ref _settings.EnableTempleGuardianTools);
ImGui.Checkbox("Enable fellowship games (phase-in)##p3fg", ref _settings.EnableFellowshipGames);
ImGui.Checkbox("Enable quest/economy tools (phase-in)##p3qe", ref _settings.EnableQuestEconomyTools);
ImGui.Spacing();
ImGui.TextColored(new Vector4(0.85f, 0.9f, 1.0f, 1.0f), "UB-ILT Ports (Mini Remote / XPMeter / Guardian / Bank)");
ImGui.Checkbox("XP meter overlay##ubxp", ref _settings.XpMeterOverlayEnabled);
ImGui.Checkbox("XP meter show totals##ubxpt", ref _settings.XpMeterShowTotals);
ImGui.Checkbox("XP meter show time##ubxptime", ref _settings.XpMeterShowTime);
ImGui.Checkbox("Mini remote portal gem buttons##ubmr", ref _settings.MiniRemotePortalGemsEnabled);
ImGui.Checkbox("Temple guardian auto-chat##ubtgchat", ref _settings.TempleGuardianAutoChat);
ImGui.Checkbox("Temple guardian auto hand-in (best-effort)##ubtghand", ref _settings.TempleGuardianAutoHandIn);
ImGui.Checkbox("Bank tools enabled##ubbanken", ref _settings.BankToolsEnabled);
ImGui.Checkbox("Bank auto-refresh on login##ubbanklogin", ref _settings.BankAutoRefreshOnLogin);
SafeImGui.TextDisabled($"Bank: p={_bankData.Pyreals:N0}, lum={_bankData.Luminance:N0}, lk={_bankData.LegendaryKeys:N0}, mk={_bankData.MythicalKeys:N0}, ec={_bankData.EnlightenedCoins:N0}, wec={_bankData.WeaklyEnlightenedCoins:N0}");
SafeImGui.TextDisabled($"Bank updated: {(_bankData.LastUpdatedUtc == DateTime.MinValue ? "never" : _bankData.LastUpdatedUtc.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss"))}");
if (ImGui.Button("Refresh bank now##ubbankrefresh"))
RequestBankRefresh("ui");
ImGui.InputText("Transfer amount##ubbankamt", ref _bankTransferAmountText, 64);
ImGui.InputText("Transfer target##ubbanktarget", ref _bankTransferTargetText, 128);
ImGui.Combo("Transfer item##ubbankitem", ref _bankTransferItemIndex, _bankTransferItemLabels, _bankTransferItemLabels.Length);
if (ImGui.Button("Send bank transfer##ubbanksend"))
{
long amount = ParseBankAmount(_bankTransferAmountText);
BankTransferItem item = (BankTransferItem)Math.Clamp(_bankTransferItemIndex, 0, _bankTransferItemLabels.Length - 1);
string? cmd = BuildBankTransferCommand(item, amount, _bankTransferTargetText);
if (!string.IsNullOrWhiteSpace(cmd) && TryDispatchChatCommand(cmd, "bank ui transfer"))
{
Host.WriteToChat($"[ub-Rythai] sent {GetBankTransferItemDisplayName(item)} transfer: {amount:N0} to {_bankTransferTargetText.Trim()}.", 1);
}
else
{
Host.WriteToChat("[ub-Rythai] invalid bank transfer input.", 1);
}
}
ImGui.Checkbox("Auto transfer enabled##ubbankautoen", ref _settings.BankAutoTransferEnabled);
ImGui.InputText("Auto transfer target##ubbankautotarget", ref _settings.BankAutoTransferTarget, 128);
ImGui.InputInt("Auto transfer percent##ubbankautopct", ref _settings.BankAutoTransferPercent);
ImGui.InputInt("Auto transfer interval min##ubbankautoint", ref _settings.BankAutoTransferIntervalMinutes);
ImGui.Checkbox("Auto transfer pyreals##ubbankautop", ref _settings.BankAutoTransferPyreals);
ImGui.Checkbox("Auto transfer luminance##ubbankautol", ref _settings.BankAutoTransferLuminance);
ImGui.Checkbox("Auto transfer legendary keys##ubbankautolk", ref _settings.BankAutoTransferLegendaryKeys);
ImGui.Checkbox("Auto transfer mythical keys##ubbankautomk", ref _settings.BankAutoTransferMythicalKeys);
ImGui.Checkbox("Auto transfer enlightened coins##ubbankautoe", ref _settings.BankAutoTransferEnlightenedCoins);
ImGui.Checkbox("Auto transfer weakly enlightened coins##ubbankautowe", ref _settings.BankAutoTransferWeaklyEnlightenedCoins);
ImGui.TextDisabled("Commands: /ub leaftide … | /ub bank status|refresh|transfer … | /ub guardian …");
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,69 @@
using System;
using System.Collections.Generic;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.UbRythai;
/// <summary>
/// UB-ILT MiniRemote portal gem list + inventory lookup (name match) for RynthCore hosts.
/// </summary>
internal static class UbRythaiPortalGems
{
/// <summary>Same canonical names as UB-ILT MiniRemote / Enlightenment recall gem list.</summary>
public static readonly string[] CanonicalGemNames =
{
"Enlightened Facility Hub Portal Gem",
"Facility Hub Portal Gem",
"Infinite Town Network Portal Gem",
"Lifestone Recall Portal Gem",
"Frozen Valley Everlasting Portal Gem",
};
/// <summary>Attempts to find an inventory object id whose name matches <paramref name="gemName"/>.</summary>
public static bool TryFindInventoryObjectIdByName(RynthCoreHost host, uint playerId, string gemName, out uint objectId)
{
objectId = 0;
if (playerId == 0 || string.IsNullOrWhiteSpace(gemName))
return false;
if (!host.HasGetContainerContents || !host.HasGetNumContainedItems || !host.HasGetObjectName)
return false;
var visited = new HashSet<uint>();
var queue = new Queue<(uint containerId, int depth)>();
queue.Enqueue((playerId, 0));
uint[] buf = new uint[512];
while (queue.Count > 0)
{
(uint containerId, int depth) = queue.Dequeue();
if (containerId == 0 || !visited.Add(containerId))
continue;
if (depth > 6)
continue;
int n = host.GetContainerContents(containerId, buf);
for (int i = 0; i < n; i++)
{
uint id = buf[i];
if (id == 0)
continue;
if (host.TryGetObjectName(id, out string? name) && !string.IsNullOrWhiteSpace(name))
{
if (name.Equals(gemName, StringComparison.OrdinalIgnoreCase))
{
objectId = id;
return true;
}
}
int contained = host.GetNumContainedItems(id);
int subContainers = host.GetNumContainedContainers(id);
if (contained > 0 || subContainers > 0)
queue.Enqueue((id, depth + 1));
}
}
return false;
}
}

View file

@ -0,0 +1,127 @@
namespace RynthCore.Plugin.UbRythai;
/// <summary>
/// Persisted settings for the ub-Rythai plugin only (not RynthAi, not Decal UB-ILT).
/// Parity targets: Utility Belt login chat queues and periodic command batches.
/// </summary>
public sealed class UbRythaiSettings
{
/// <summary>
/// Minimum log level written to the local file logger. 0=Trace, 1=Debug, 2=Info, 3=Warn, 4=Error.
/// </summary>
public int LogLevel = (int)UbRythaiLogLevel.Info;
/// <summary>Login-time chat lines (UtilityBelt CharacterLoginCommands-style).</summary>
public bool LoginCommandsEnabled;
public int LoginCommandsInitialDelayMs = 2000;
public int LoginCommandsGapMs = 400;
public string LoginCommandsText = "";
/// <summary>Repeating chat batches (PeriodicCommandsTool-style).</summary>
public bool PeriodicCommandsEnabled;
public int PeriodicIntervalSeconds = 300;
public int PeriodicCommandsGapMs = 400;
public string PeriodicCommandsText = "";
/// <summary>ub-IT's "/ub periodic add" list: "minutes|on|command" per line (UbRythaiPeriodicEntries).</summary>
public string PeriodicEntriesText = "";
// P1: macro parity items that map cleanly onto chat-command dispatch.
public bool OpenMainPackOnLogin;
public bool RunChatResizeOnLogin;
public string ChatResizeCommand = "/ub chat max";
public bool LogOutOnDeathEnabled;
public int LogOutOnDeathCooldownSeconds = 30;
public bool AutoTradeAcceptEnabled;
public string AutoTradeAcceptWhitelist = "";
public string AutoTradeAcceptCommand = "/trade accept";
public int AutoTradeAcceptDebounceSeconds = 2;
public bool AutoPercentConfirmationEnabled;
public int AutoPercentConfirmationThreshold = 100;
public string AutoPercentConfirmationCommand = "/yes";
public int AutoPercentConfirmationDebounceSeconds = 2;
public bool BusyGuardrailsEnabled = true;
public int BusyGuardrailsMinCommandGapMs = 250;
public int BusyGuardrailsBusyStateThreshold = 0;
// P2: selective chat filtering and client FPS policy.
public bool ChatFilterEnabled;
public bool FilterBusyLines;
public bool FilterSpellFizzleLines;
public bool FilterVendorSpamLines;
public bool FilterMonsterDeathLines;
public bool FilterAttackEvadesLines;
public bool FilterDefenseEvadesLines;
public bool FilterAttackResistsLines;
public bool FilterDefenseResistsLines;
public bool FilterSpellCastMineLines;
public bool FilterSpellCastOthersLines;
public bool FilterSpellExpiresLines;
public bool FilterPeriodicHealingLines;
public bool FilterFailedAssessLines;
public bool FilterKillTaskCompleteLines;
public bool ClientFpsPolicyEnabled = true;
public int TargetFpsFocused = 60;
public int TargetFpsBackground = 30;
public bool WindowMoverEnabled;
public bool WindowMoverAutoRestore;
// P3: ILT gameplay systems (feature gates for incremental implementation).
public bool EnableSpellcraftQueue;
public bool EnableTempleGuardianTools;
public bool EnableFellowshipGames;
public bool EnableQuestEconomyTools;
/// <summary>
/// ILT feature gate mode: Auto | On | Off.
/// Auto enables ILT-only features when world name matches <see cref="LeaftideAutoWorldNames"/>.
/// On forces ILT-only features on any shard; Off disables ILT-only features.
/// </summary>
public string LeaftideFeaturesMode = "Auto";
/// <summary>
/// Comma/semicolon/newline-separated world names used by Auto mode (case-insensitive exact match).
/// </summary>
public string LeaftideAutoWorldNames = "InfiniteLeaftide,Conquest";
/// <summary>
/// Extra safety gate for banking when mode is manually forced On. Auto mode allows banking automatically on matched worlds.
/// </summary>
public bool LeaftideManualAllowBanking;
/// <summary>UB-ILT XPMeter parity: ImGui overlay tracking XP/LUM rates via player PropertyInt64 reads.</summary>
public bool XpMeterOverlayEnabled;
public bool XpMeterShowTotals = true;
public bool XpMeterShowTime = true;
/// <summary>UB-ILT MiniRemote parity: quick portal gem buttons (inventory scan + UseObject).</summary>
public bool MiniRemotePortalGemsEnabled;
/// <summary>UB-ILT TempleGuardianHelper parity: auto-translate incoming guardian tells using the phrasebook.</summary>
public bool TempleGuardianAutoChat;
/// <summary>UB-ILT TempleGuardianHelper parity: optional vendor/fillcomps/buyall pump (best-effort; requires UB-style chat commands).</summary>
public bool TempleGuardianAutoHandIn;
/// <summary>Enable /bank refresh + transfer helpers in ub-Rythai when ILT banking gate allows it.</summary>
public bool BankToolsEnabled = true;
/// <summary>Issue /bank once shortly after login if banking tools are active.</summary>
public bool BankAutoRefreshOnLogin = true;
/// <summary>Enable periodic auto-transfer from parsed bank balances.</summary>
public bool BankAutoTransferEnabled;
public string BankAutoTransferTarget = "";
public int BankAutoTransferPercent = 10;
public int BankAutoTransferIntervalMinutes = 15;
public bool BankAutoTransferPyreals;
public bool BankAutoTransferLuminance;
public bool BankAutoTransferLegendaryKeys;
public bool BankAutoTransferMythicalKeys;
public bool BankAutoTransferEnlightenedCoins;
public bool BankAutoTransferWeaklyEnlightenedCoins;
// P4: deferred or host-dependent surfaces.
public bool EnableVhsHotkeyBridge;
public bool EnableDecalHudCompat;
public bool EnableLegacyAutoPackImport;
}

View file

@ -0,0 +1,71 @@
using System;
using System.IO;
using System.Text;
using System.Text.Json;
namespace RynthCore.Plugin.UbRythai;
/// <summary>Loads and saves <see cref="UbRythaiSettings"/> per character under Documents\RynthSuite\ub-Rythai\.</summary>
internal static class UbRythaiSettingsStore
{
private static readonly string RootDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
"RynthSuite",
"ub-Rythai");
/// <summary>Returns the on-disk path for the settings file, or null if <paramref name="charName"/> is empty.</summary>
public static string? GetSettingsFilePath(string? charName)
{
if (string.IsNullOrWhiteSpace(charName))
return null;
string safe = SanitizeFileName(charName.Trim());
string dir = Path.Combine(RootDir, safe);
return Path.Combine(dir, "UbRythai-settings.json");
}
public static UbRythaiSettings LoadOrDefault(string? charName)
{
string? path = GetSettingsFilePath(charName);
if (path == null || !File.Exists(path))
return new UbRythaiSettings();
try
{
string json = File.ReadAllText(path, Encoding.UTF8);
UbRythaiSettings? loaded = JsonSerializer.Deserialize(json, UbRythaiJsonContext.Default.UbRythaiSettings);
return loaded ?? new UbRythaiSettings();
}
catch
{
return new UbRythaiSettings();
}
}
public static void Save(string? charName, UbRythaiSettings settings)
{
string? path = GetSettingsFilePath(charName);
if (path == null)
return;
try
{
string dir = Path.GetDirectoryName(path)!;
Directory.CreateDirectory(dir);
string json = JsonSerializer.Serialize(settings, UbRythaiJsonContext.Default.UbRythaiSettings);
File.WriteAllText(path, json, Encoding.UTF8);
}
catch
{
// best-effort persistence
}
}
private static string SanitizeFileName(string name)
{
var sb = new StringBuilder(name.Length);
foreach (char c in name)
sb.Append(char.IsLetterOrDigit(c) || c == '\'' || c == '-' ? c : '_');
return sb.ToString();
}
}

View file

@ -0,0 +1,94 @@
using System;
namespace RynthCore.Plugin.UbRythai;
/// <summary>
/// UB-ILT TempleGuardianHelper parity (best-effort): vendor → /fillcomps → buyall style chat pump.
/// RynthCore does not expose UB's AutoVendor / UB_GiveItem surfaces, so this is intentionally conservative.
/// </summary>
internal sealed class UbRythaiTempleGuardianAutomation
{
private int _step;
private int _waitTicks;
private string _itemName = "";
public bool IsActive => _step != 0;
public void Start(string itemName, string npcName, Func<string, bool> dispatchChatCommand, Action<string> logInfo)
{
Stop();
if (string.IsNullOrWhiteSpace(itemName) || string.IsNullOrWhiteSpace(npcName))
return;
_itemName = itemName.Trim();
bool skipVendor = npcName.IndexOf("Guardian of Attribute Enlightenment", StringComparison.OrdinalIgnoreCase) >= 0;
_step = skipVendor ? 10 : 1;
_waitTicks = 0;
logInfo(skipVendor
? "[Guardian] Attribute guardian detected: skipping vendor flow (hand-in automation not available on this host)."
: "[Guardian] Auto hand-in: starting vendor/fillcomps pump (best-effort).");
if (!skipVendor)
{
// UB-ILT uses AutoVendor chat verbs; many shards expose similar vendor tooling via UB macros.
dispatchChatCommand("/ub vendor clearbuy");
dispatchChatCommand("/ub vendor open");
}
}
public void Tick(Func<string, bool> dispatchChatCommand, Action<string> logInfo)
{
if (_step == 0)
return;
switch (_step)
{
case 1:
_step = 2;
_waitTicks = 0;
break;
case 2:
_waitTicks++;
if (_waitTicks > 120)
{
logInfo("[Guardian] Auto hand-in: vendor open timeout — stopping.");
Stop();
return;
}
// Heuristic: once vendor tooling reports ready, UB users typically proceed with fillcomps.
// Without vendor id introspection, we advance on a fixed delay (similar to UB frame waits).
if (_waitTicks == 30)
{
dispatchChatCommand("/fillcomps");
logInfo("[Guardian] /fillcomps");
}
if (_waitTicks == 60)
{
dispatchChatCommand("/ub vendor buyall");
logInfo("[Guardian] vendor buyall (best-effort)");
}
if (_waitTicks >= 90)
{
_step = 10;
_waitTicks = 0;
}
break;
case 10:
logInfo($"[Guardian] Resolved item: {_itemName}. Manual hand-in: stand next to the guardian and use the item on them (host automation not wired).");
Stop();
break;
}
}
public void Stop()
{
_step = 0;
_waitTicks = 0;
_itemName = "";
}
}

View file

@ -0,0 +1,231 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace RynthCore.Plugin.UbRythai;
/// <summary>
/// Port of UB-ILT <c>UtilityBelt.Tools.Leaftide.TempleGuardianPhrasebook</c> for RynthCore chat parsing.
/// Maps Temple spell-words and Attribute riddles to required commodity names (Leaftide / ILT parity).
/// </summary>
internal static class UbRythaiTempleGuardianPhrasebook
{
/// <summary>Incoming tell prefix for the Temple guardian (client chat log shape).</summary>
public const string IncomingTempleTellPrefix = "Guardian of the Temple of Enlightenment tells you";
/// <summary>Incoming tell prefix for the Attribute guardian (client chat log shape).</summary>
public const string IncomingAttributeTellPrefix = "Guardian of Attribute Enlightenment tells you";
private static readonly Dictionary<string, string> TempleSpells = new(StringComparer.OrdinalIgnoreCase)
{
{ "Boquar", "Mugwort" },
{ "Feazh", "Damiana" },
{ "Kenrak", "Amaranth" },
{ "Puish", "Saffron" },
{ "Shurov", "Comfrey" },
{ "Volae", "Eyebright" },
{ "Cruath", "Ginseng" },
{ "Helkas", "Wormwood" },
{ "Malar", "Hyssop" },
{ "Quavosh", "Dragonsblood" },
{ "Tugak", "Vervain" },
{ "Yanoi", "Bistort" },
{ "Equin", "Mandrake" },
{ "Jevak", "Myrrh" },
{ "Ozhur", "Frankincense" },
{ "Roiga", "Yarrow" },
{ "Uthoi", "Henbane" },
{ "Zojak", "Hawthorn" },
};
private static readonly (string needle, string item)[] AttributeClues = BuildAttributeClues();
private static (string needle, string item)[] BuildAttributeClues()
{
var raw = new (string phrase, string item)[]
{
("what stone of shadow wields such arm", "Powdered Onyx"),
("what stone defends the mortal clay", "Powdered Agate"),
("what heavy stone keeps adventurers healed", "Powdered Hematite"),
("what honeyed stone bids pain to leave", "Powdered Amber"),
("what draught unweaves that mages send", "Chorizite"),
("what gem of life beats deep within", "Powdered Bloodstone"),
("what ruddy gem calls vigor nigh", "Powdered Carnelian"),
("what lunar gem gives peace to mind", "Powdered Moonstone"),
("what verdant gem reveals the way", "Powdered Malachite"),
("what crystal tunes the life it soothes", "Powdered Quartz"),
("what gem of sky makes items nice", "Powdered Turquoise"),
("what vial holds my burning scar", "Brimstone"),
("which draught brings forth the fire's scent", "Turpeth"),
("race the wind yet leave no trace", "Cadmia"),
("grant the hand a dancer grace", "Cadmia"),
("no wings I bear yet fleet I flee", "Cadmia"),
("what draught awakens speed in thee", "Cadmia"),
("what deaught awakens speed in thee", "Cadmia"),
("what potion turns mana-use to one", "Cinnabar"),
("what azure draught makes thunder weep", "Cobalt"),
("what draught commands the winter's tide", "Colcothar"),
("what pale draught prevents acid's writhe", "Gypsum"),
("what liquid turns heart grey between", "Quicksilver"),
("what potion pierces the unseen end", "Realgar"),
("what shadowed draught makes swiftness lie", "Stibnite"),
("what verdant vial hides cuts unseen", "Verdigris"),
("what potion shakes both flesh and floor", "Vitriol"),
("what river wood trades life as art", "Alder Talisman"),
("what wood enchants both bane and skill", "Ashwood Talisman"),
("what pale wood casts the striker's bane", "Birch Talisman"),
("what sacred stem keeps harm outside", "Cedar Talisman"),
("what dark wood diminishes the foe's own tune", "Blackthorn Talisman"),
("what hardwood charm makes others stand", "Ebony Talisman"),
("what aged branch makes circles run", "Elder Talisman"),
("what mystic bough binds here to yore", "Hazel Talisman"),
("what poisoned branch brings creeping death", "Hemlock Talisman"),
("what steadfast wood makes volleys rained", "Oak Talisman"),
("what living wand makes allies mend", "Poplar Talisman"),
("what sacred wood the self amends", "Rowan Talisman"),
("what supple wood restores me here", "Willow Talisman"),
("what ancient bough lets lifeblood grow", "Yew Talisman"),
};
return raw
.Select(t => (NormalizePhrase(t.phrase), t.item))
.OrderByDescending(t => t.Item1.Length)
.ToArray();
}
private static string NormalizePhrase(string s)
{
if (string.IsNullOrWhiteSpace(s))
return "";
string lower = s.Trim().ToLowerInvariant().Replace('’', '\'');
var sb = new StringBuilder(lower.Length);
bool pendingSpace = false;
foreach (char c in lower)
{
bool wordCh = (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '\'';
if (!wordCh)
{
pendingSpace = true;
continue;
}
if (pendingSpace && sb.Length > 0)
{
sb.Append(' ');
pendingSpace = false;
}
sb.Append(c);
}
return sb.ToString().Trim();
}
/// <summary>Resolves pasted guardian dialog to a commodity name, or a short help string.</summary>
public static string Translate(string raw)
{
if (string.IsNullOrWhiteSpace(raw))
return "Paste a spell word or riddle text, then Translate.";
string blob = NormalizePhrase(raw);
if (blob.Length == 0)
return "Paste a spell word or riddle text, then Translate.";
List<string> tokens = Regex.Split(blob, @"[^a-z0-9']+")
.Where(t => t.Length > 0)
.ToList();
foreach (KeyValuePair<string, string> pair in TempleSpells.OrderByDescending(p => p.Key.Length))
{
if (tokens.Any(t => string.Equals(t, pair.Key, StringComparison.OrdinalIgnoreCase)))
return pair.Value;
}
foreach (KeyValuePair<string, string> pair in TempleSpells.OrderByDescending(p => p.Key.Length))
{
if (blob.IndexOf(pair.Key.ToLowerInvariant(), StringComparison.Ordinal) >= 0)
return pair.Value;
}
foreach ((string needle, string item) in AttributeClues)
{
if (needle.Length > 0 && blob.Contains(needle))
return item;
}
return "No match: paste more lines from the guardian (especially the question line ending with ?).";
}
/// <summary>True when <paramref name="raw"/> looks like a full incoming tell line (paste from chat).</summary>
public static bool LooksLikeIncomingGuardianTellLine(string raw)
{
if (string.IsNullOrWhiteSpace(raw))
return false;
string t = raw.TrimStart();
return t.StartsWith(IncomingTempleTellPrefix, StringComparison.OrdinalIgnoreCase)
|| t.StartsWith(IncomingAttributeTellPrefix, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// NPC to give the resolved item to after the phrasebook resolves an item (from the incoming tell prefix).
/// </summary>
public static string TurnInNpcNameFromTell(string rawTell)
{
if (string.IsNullOrEmpty(rawTell))
return "Guardian of Attribute Enlightenment";
if (rawTell.IndexOf("Guardian of the Temple of Enlightenment", StringComparison.OrdinalIgnoreCase) >= 0)
return "Guardian of the Temple of Enlightenment";
if (rawTell.IndexOf("Guardian of Attribute Enlightenment", StringComparison.OrdinalIgnoreCase) >= 0)
return "Guardian of Attribute Enlightenment";
return "Guardian of Attribute Enlightenment";
}
/// <summary>Resolves the turn-in NPC for manual Translate + auto hand-in.</summary>
public static string HandInNpcNameFromInput(string raw)
{
if (string.IsNullOrWhiteSpace(raw))
return "Guardian of Attribute Enlightenment";
if (LooksLikeIncomingGuardianTellLine(raw))
return TurnInNpcNameFromTell(raw);
if (raw.IndexOf("Guardian of the Temple of Enlightenment", StringComparison.OrdinalIgnoreCase) >= 0)
return "Guardian of the Temple of Enlightenment";
if (raw.IndexOf("Guardian of Attribute Enlightenment", StringComparison.OrdinalIgnoreCase) >= 0)
return "Guardian of Attribute Enlightenment";
foreach (string spellWord in TempleSpells.Keys)
{
if (raw.IndexOf(spellWord, StringComparison.OrdinalIgnoreCase) >= 0)
return "Guardian of the Temple of Enlightenment";
}
return "Guardian of Attribute Enlightenment";
}
/// <summary>True when chat text likely contains a Temple spell word or attribute riddle.</summary>
public static bool LooksLikeGuardianChatLine(string raw)
{
if (string.IsNullOrWhiteSpace(raw))
return false;
string blob = NormalizePhrase(raw);
if (blob.Contains('?') && blob.Length >= 18)
return true;
foreach (string spellWord in TempleSpells.Keys)
{
if (raw.IndexOf(spellWord, StringComparison.OrdinalIgnoreCase) >= 0)
return true;
}
foreach ((string needle, _) in AttributeClues)
{
if (needle.Length > 0 && blob.Contains(needle))
return true;
}
return false;
}
}

View file

@ -0,0 +1,120 @@
using System;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.UbRythai;
/// <summary>
/// UB-ILT XPMeter parity without native client hooks. Since 3.1.13 (2026-10-13) it counts the way
/// every other tracker does:
/// <list type="bullet">
/// <item>With RynthAi loaded it shows RynthAi's own session (the Mini Remote's Session Stats, read
/// through "RynthAi.Hub"), so the meter, the Mini Remote, the Tracker panel, RynthOracle and RynthILT
/// all show one session; "/ub xpmeter reset" then starts that session over.</item>
/// <item>Without RynthAi it runs the shared SessionStats code (Plugins\Shared, the same code RynthAi
/// and RynthTracker use) on the player's properties: earned XP from TotalExperience rises, and
/// luminance from AvailableLuminance or, on ACECustom, the bank (9005) with deposits and transfers
/// left out, plus Aelrynth's bank totals (9102 / 9103).</item>
/// </list>
/// Tick and OnChat run on the pump; the overlay (render thread) reads the published <see cref="Reading"/>.
/// </summary>
internal sealed class UbRythaiXpMeterState
{
// ACE.Entity.Enum.Properties.PropertyInt64 (ushort values passed through the host as uint stype).
private const uint PropertyTotalExperience = 1;
private const uint PropertyAvailableLuminance = 6;
private const uint PropertyMaximumLuminance = 7;
private const uint PropertyBankedLuminance = 9005; // ACECustom bank
private const uint PropertyRadianceEarned = 9101; // Aelrynth Bank mod session totals
private const uint PropertyLuminanceBanked = 9102;
private const uint PropertyLuminanceDrawn = 9103;
private const long PollIntervalMs = 500;
/// <summary>What the overlay and "/ub xpmeter status" show (immutable; swapped after each poll).</summary>
internal sealed record Reading(long Xp, long Lum, double Seconds, double XpPerHour, double LumPerHour, bool HasLuminance, bool FromRynthAi)
{
public static readonly Reading Empty = new(0, 0, 0, 0, 0, false, false);
}
private readonly SessionStats _stats = new();
private readonly RynthAiSessionClient _ai = new();
private uint _playerId;
private long _nextPollMs;
private bool _hasLuminance;
private volatile Reading _reading = Reading.Empty;
public long AccumulatedXp => _reading.Xp;
public long AccumulatedLum => _reading.Lum;
public bool HasLuminance => _reading.HasLuminance;
/// <summary>True while the numbers are RynthAi's session (one session for every tracker).</summary>
public bool FromRynthAi => _reading.FromRynthAi;
/// <summary>The session's length in seconds (floored at one second, as the rates are).</summary>
public double RunTimeSeconds() => Math.Max(1.0, _reading.Seconds);
public double XpPerHour() => _reading.XpPerHour;
public double LumPerHour() => _reading.LumPerHour;
/// <summary>
/// Starts the session over: RynthAi's when it is the one shown (so every tracker restarts
/// together), and the meter's own either way. Pump thread.
/// </summary>
public void Reset(RynthCoreHost host)
{
if (_reading.FromRynthAi) _ai.ResetSession(host, Environment.TickCount64);
_stats.Reset(DateTime.UtcNow);
_reading = Reading.Empty;
_nextPollMs = 0;
}
/// <summary>Login (or a reset): a fresh session whose first poll sets the baselines.</summary>
public void SeedFromPlayer(RynthCoreHost host, uint playerId)
{
_playerId = playerId;
_ai.Reset();
_stats.Reset(DateTime.UtcNow);
_reading = Reading.Empty;
_nextPollMs = 0;
_hasLuminance = playerId != 0 && host.HasGetObjectQuadProperty
&& host.TryGetObjectQuadProperty(playerId, PropertyMaximumLuminance, out long maxLum) && maxLum > 0;
Tick(host, playerId);
}
/// <summary>The server's luminance lines (deposits and transfers into the bank aren't earnings). Pump thread.</summary>
public void OnChat(string? text) => _stats.OnChat(text, DateTime.UtcNow);
/// <summary>Polls the player's properties every half second and publishes the reading. Pump thread.</summary>
public void Tick(RynthCoreHost host, uint playerId)
{
if (playerId == 0 || !host.HasGetObjectQuadProperty) return;
if (playerId != _playerId)
{
SeedFromPlayer(host, playerId);
return;
}
long nowMs = Environment.TickCount64;
if (nowMs < _nextPollMs) return;
_nextPollMs = nowMs + PollIntervalMs;
DateTime now = DateTime.UtcNow;
_stats.Sample(new SessionSample(
Read(host, PropertyTotalExperience),
Read(host, PropertyAvailableLuminance),
Read(host, PropertyBankedLuminance),
Read(host, PropertyLuminanceBanked),
Read(host, PropertyLuminanceDrawn),
Read(host, PropertyRadianceEarned)), now);
if (_ai.TryGet(host, nowMs, out SessionStatsV1 s))
{
_reading = new Reading(s.Xp, s.Lum, s.SessionSeconds, s.XpPerHour, s.LumPerHour, _hasLuminance || s.Lum > 0, true);
return;
}
SessionStatsView v = _stats.View(now);
_reading = new Reading(v.Xp, v.Lum, v.SessionSeconds, v.XpPerHour, v.LumPerHour, _hasLuminance || v.PassUpTracked || v.Lum > 0, false);
}
private long? Read(RynthCoreHost host, uint stype)
=> host.TryGetObjectQuadProperty(_playerId, stype, out long value) ? value : null;
}