feat: SK backlog from test through 2026.11.22.48 (Trade Shop, Oracle, quests, loot, nav)

Squash of test/main-merge-2026-10-25 onto aelrynth main 2026.11.19.1 for the standing sk PR. Includes Trade Shop, Oracle wiki/ILT tracker, quest runs, loot checklist, RynthNav, VTank import. HandWrittenVersion remains 0.5.0-legacy-ui. See Changelog/2026-11-22-sk-backlog-test-merge.md.
This commit is contained in:
BlankenshipG 2026-11-23 00:08:38 -05:00
commit dc08e1abba
521 changed files with 47247 additions and 795 deletions

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" />
<Compile Include="..\..\Shared\SavedWindow.cs" Link="Shared\SavedWindow.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" />
<!-- 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;
}