Snapshot for release 2026.10.28.3 (internal db7f094)

This commit is contained in:
Tom Bohar 2026-10-28 23:23:42 -04:00
commit e6642d0e10
102 changed files with 4821 additions and 782 deletions

View file

@ -86,5 +86,6 @@ public partial class BuffManager
_swapTestAt = Now;
LastWandSwapTrail = "";
_host.Log($"[SwapTest] start: '{name}' (mode {CurrentCombatMode})");
_host.WriteToChat($"[RynthAi] Swap test: {name}; the result follows.", 1); // /ra swaptest's answer
}
}

View file

@ -0,0 +1,175 @@
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// What a chat command (/ra, /ub, /mt, /vt) says back: the one place the rule lives (2026-10-28).
/// <list type="bullet">
/// <item>A command the player typed answers in chat, in one line (more only for lists, status and help):
/// <see cref="Ok"/> says what changed and the value now, <see cref="Fail"/> why it didn't work and the
/// usage. A typed command that said nothing at all still gets a line (<see cref="Run"/>).</item>
/// <item>A command a meta, a nav route or a script sent is quiet when it works (the log has the line),
/// so metas don't flood chat. Its errors still show in chat, each distinct one at most once a minute.</item>
/// <item><see cref="Info"/> is output the command was asked for (a list, a status, help): shown either way.</item>
/// </list>
/// Who sent the line is per thread: a command is handled start to finish on the thread it came in on.
/// </summary>
internal sealed class CommandReply
{
/// <summary>AC chat types: RynthAi's usual lines, and its error lines (AutoVendor, salvage, pack full).</summary>
public const int OkColor = 1, FailColor = 2;
/// <summary>A meta repeating the same error says it in chat at most this often (the log has every one).</summary>
public const long FailRepeatMs = 60_000;
/// <summary>The line a typed command that answered nothing gets (the log says which command).</summary>
public const string RanPrefix = "[RynthAi] Ran: ";
private readonly Action<string, int> _chat;
private readonly Action<string> _log;
private readonly Func<bool> _metaActive;
private readonly Dictionary<string, long> _failSaidAt = new(StringComparer.Ordinal);
/// <summary>Milliseconds, for the once-a-minute error repeat (tests set it).</summary>
internal Func<long> Clock { get; set; } = () => Environment.TickCount64;
[ThreadStatic] private static int t_scriptDepth; // AsScript on the stack: a script's or a route's line
[ThreadStatic] private static int t_queued; // RunQueued: 0 none, 1 sent by a script, 2 typed
[ThreadStatic] private static int t_runDepth; // Run on the stack
[ThreadStatic] private static bool t_answered; // the command being run has said something
/// <param name="chat">Writes a chat line in a colour.</param>
/// <param name="log">Writes a log line.</param>
/// <param name="metaActive">True while a meta's action or chat command is being run.</param>
public CommandReply(Action<string, int> chat, Action<string> log, Func<bool> metaActive)
{
_chat = chat;
_log = log;
_metaActive = metaActive;
}
/// <summary>True when a meta, a route or a script sent the line being handled, not the player.</summary>
public bool FromScript => t_queued switch
{
1 => true,
2 => false,
_ => t_scriptDepth > 0 || _metaActive(),
};
/// <summary>It worked: what changed and the value now. Chat when typed; the log only for a meta or script.</summary>
public void Ok(string text)
{
t_answered = true;
if (FromScript) _log(text);
else _chat(text, OkColor);
}
/// <summary>It didn't work: why, and the usage. Always logged; in chat when typed, and for a meta or
/// script the first time in a minute that this exact line comes up.</summary>
public void Fail(string text)
{
t_answered = true;
_log(text);
if (FromScript && !FirstInAMinute(text)) return;
_chat(text, FailColor);
}
/// <summary>
/// Accepted and ignored on purpose (a VTank or UtilityBelt verb with no RynthAi equivalent): said
/// as a failure when typed, so the player knows nothing happened; only logged for a meta, which
/// sends it on every pass and is meant to keep running.
/// </summary>
public void Ignored(string text)
{
if (FromScript) { t_answered = true; _log(text); }
else Fail(text);
}
/// <summary>Output the command was asked for (a list, a status, help, a lookup): chat either way.</summary>
public void Info(string text)
{
t_answered = true;
_chat(text, OkColor);
}
/// <summary>The command's answer comes another way: a later line (a queued action that says what
/// it did), the server, the engine, or the plugin the command was handed to.</summary>
public void Answered() => t_answered = true;
/// <summary>
/// Handles one command line. A typed command that said nothing gets one line anyway (and the
/// log names it, so it can get a proper answer); one that threw says so instead of nothing.
/// A meta's or a script's line runs as it is.
/// </summary>
public void Run(string line, Action handle)
{
bool outer = t_runDepth == 0;
bool savedAnswered = t_answered;
if (outer) t_answered = false;
bool typed = !FromScript;
t_runDepth++;
try
{
handle();
}
catch (Exception ex) when (outer && typed)
{
_log($"[CmdReply] '{line}' threw: {ex}");
Fail($"[RynthAi] {line}: failed ({ex.GetType().Name}: {ex.Message}).");
}
finally
{
t_runDepth--;
if (outer)
{
if (typed && !t_answered)
{
_log($"[CmdReply] '{line}' gave no reply of its own; said \"{RanPrefix}{line}\" for it.");
_chat(RanPrefix + line, OkColor);
}
t_answered = savedAnswered;
}
}
}
/// <summary>Runs <paramref name="action"/> as a line a script or a nav route sent (quiet when it works).</summary>
public T AsScript<T>(Func<T> action)
{
t_scriptDepth++;
try { return action(); }
finally { t_scriptDepth--; }
}
/// <summary>
/// A queued command (run later on the tick) answers as the line that queued it would have:
/// <paramref name="fromScript"/> is <see cref="FromScript"/> when it was queued.
/// </summary>
public void RunQueued(bool fromScript, Action action)
{
int saved = t_queued;
t_queued = fromScript ? 1 : 2;
try { action(); }
finally { t_queued = saved; }
}
/// <summary>True when this error line wasn't said in the last minute (a meta repeating it says it once).</summary>
private bool FirstInAMinute(string text)
{
long now = Clock();
lock (_failSaidAt)
{
if (_failSaidAt.TryGetValue(text, out long at) && now - at < FailRepeatMs) return false;
if (_failSaidAt.Count >= 256)
{
var old = new List<string>();
foreach (var kv in _failSaidAt)
if (now - kv.Value >= FailRepeatMs) old.Add(kv.Key);
foreach (string k in old) _failSaidAt.Remove(k);
if (_failSaidAt.Count >= 256) _failSaidAt.Clear();
}
_failSaidAt[text] = now;
return true;
}
}
}

View file

@ -3849,7 +3849,7 @@ public sealed partial class RynthAiPlugin
var settings = _dashboard?.Settings;
if (settings == null || _objectCache == null || _playerId == 0)
{
ChatLine("[RynthAi] Corpse info not ready yet.");
ReplyFail("[RynthAi] Corpse info not ready yet.");
return;
}
@ -3874,14 +3874,14 @@ public sealed partial class RynthAiPlugin
var settings = _dashboard?.Settings;
if (settings == null || _objectCache == null || _playerId == 0)
{
ChatLine("[RynthAi] Corpse ownership diagnostics are not ready yet.");
ReplyFail("[RynthAi] Corpse ownership diagnostics are not ready yet.");
return;
}
string selector = parts.Length >= 3 ? parts[2].Trim().ToLowerInvariant() : string.Empty;
if (!TryResolveCorpseForDiagnostics(selector, out WorldObject? corpse, out string source))
{
ChatLine("[RynthAi] No corpse found for diagnostics. Use /ra corpsecheck [target|open|nearest].");
ReplyFail("[RynthAi] No corpse found for diagnostics. Use /ra corpsecheck [target|open|nearest].");
return;
}
@ -3911,14 +3911,14 @@ public sealed partial class RynthAiPlugin
{
if (_fellowshipTracker == null)
{
ChatLine("[RynthAi] Fellowship tracker is not ready yet.");
ReplyFail("[RynthAi] Fellowship tracker is not ready yet.");
return;
}
string fellowSub = parts.Length >= 3 ? parts[2].Trim().ToLowerInvariant() : "status";
if (!_fellowshipTracker.IsInFellowship && fellowSub != "help")
{
ChatLine("[RynthAi] Not in a fellowship.");
ReplyFail("[RynthAi] Not in a fellowship.");
return;
}
@ -3972,7 +3972,7 @@ public sealed partial class RynthAiPlugin
}
else
{
ChatLine("[RynthAi] Usage: /ra fellow ismember <name>");
ReplyFail("[RynthAi] Usage: /ra fellow ismember <name>");
}
break;
@ -3981,7 +3981,7 @@ public sealed partial class RynthAiPlugin
break;
default:
ChatLine($"[RynthAi] Unknown fellow subcommand: {fellowSub}. Try /ra fellow help");
ReplyFail($"[RynthAi] Unknown fellow subcommand: {fellowSub}. Try /ra fellow help");
break;
}
}
@ -4099,27 +4099,27 @@ public sealed partial class RynthAiPlugin
var settings = _dashboard?.Settings;
if (settings == null || _objectCache == null || _playerId == 0)
{
ChatLine("[RynthAi] Corpse opening is not ready yet.");
ReplyFail("[RynthAi] Corpse opening is not ready yet.");
return;
}
if (_openedContainerId != 0)
{
ChatLine($"[RynthAi] A container is already open: 0x{(uint)_openedContainerId:X8}");
ReplyFail($"[RynthAi] A container is already open: 0x{(uint)_openedContainerId:X8}");
return;
}
double maxMeters = GetCorpseApproachRangeMaxMeters(settings);
if (!TryFindNearestCorpse(maxMeters, out WorldObject? corpse, out double distanceMeters))
{
ChatLine("[RynthAi] No unopened corpse is within corpse max range.");
ReplyFail("[RynthAi] No unopened corpse is within corpse max range.");
return;
}
_targetCorpseId = corpse!.Id;
_corpseTargetSince = CorpseNowMs;
_lastCorpseOpenAttemptAt = 0;
ChatLine($"[RynthAi] Corpse target set to {corpse.Name} at {ConvertMetersToYards(distanceMeters):F1} yd.");
ReplyOk($"[RynthAi] Corpse target set to {corpse.Name} at {ConvertMetersToYards(distanceMeters):F1} yd.");
TickCorpseOpening();
}
}

View file

@ -17,16 +17,17 @@
// activity an inset line: what the bot is doing (coloured, with its icon) and
// the meta's state.
// controls RUN / STOP, the five subsystem keys (lit LED = on; right-click:
// their settings), Force rebuff.
// their settings), then RynthSort's auto-sort key (when it's loaded;
// right-click: its window) and Force rebuff.
// launchers a tray of window buttons (lit while open), labels when wide.
// footer FPS (coloured by rate), RynthAi's version, bot and client uptime.
// bars the vitals and the target (15 segments, coloured by health).
// Minimized keeps the header, the activity line, the controls and the bars.
// Drawers on the edges (docked only): Ranges, Loaded files, Patrol and the Mini
// Drawers on the edges, docked or popped out: Ranges, Loaded files, Patrol and the Mini
// Remote on the left, My settings on the right; a tab's right-click moves its
// drawer to the other edge. Ranges, Patrol and My settings show the Settings
// panel's rows, which RynthCore draws into them (RenderSettingsDrawer, v90).
// Popped out the pickers are in the options.
// Popped out the pickers are in the options as well.
//
// Colours: the player's theme (GetUiColor v90: Background, KeyFace, Hairline,
// Inset, Text, Muted, Faint, Accent, Highlight); health, stamina, mana and the
@ -68,6 +69,11 @@ internal interface IDashboardHost
void AdjustOpacity(float delta);
void ToggleLock();
void SelectProfile(int kind, int index);
/// <summary>RynthSort's auto-sort: -1 RynthSort not loaded (or not logged in, or too old to say), 0 off, 1 on.</summary>
int AutoSort { get; }
void SetAutoSort(bool on);
/// <summary>RynthSort's own window, shown or hidden.</summary>
void ToggleSortWindow();
void StartPatrol();
void ToggleSpells();
/// <summary>The Classic (retail) look: RynthCore's own face comes back for it.</summary>
@ -195,7 +201,10 @@ internal sealed unsafe class InstrumentDashboard
OptionsMenu(prefs);
CharMenu();
if (!popped) Drawers(prefs, origin, new Vector2(width, height));
// Popped out too (Tom 2026-10-24: "many of the settings are built into the drawers"): the
// pop-out's picture grows past the panel to hold them, and RynthCore's pop-outs take clicks
// on a window drawn there, not only on a menu.
Drawers(prefs, origin, new Vector2(width, height));
return new Vector2(width, height);
}
@ -428,18 +437,31 @@ internal sealed unsafe class InstrumentDashboard
Tracked(dl, bf, bf.FontSize, new Vector2(gx + glyph + Px(6), MathF.Round(rp.Y + (h - bf.FontSize) * 0.5f)), fg, word, track);
}
// The subsystem keys.
// The subsystem keys. With RynthSort loaded its auto-sort key sits at the right beside Force
// rebuff, and at the narrowest window every key gives up a pixel for it.
int sort = _d.AutoSort;
float kw = Px(KeyW);
if (sort >= 0)
kw = MathF.Min(kw, MathF.Floor((w - Px(RunW) - 2 * Px(Gap) - Subsystems.Length * Px(KeyGap) - Px(FrW)) / (Subsystems.Length + 1)));
float kx = x0 + Px(RunW) + Px(Gap);
bool[] on = { _r.Combat, _r.Buffing, _r.Navigation, _r.Looting, _r.Meta };
for (int i = 0; i < Subsystems.Length; i++)
{
Key(dl, i, on[i], new Vector2(kx, y), new Vector2(Px(KeyW), h));
kx += Px(KeyW) + Px(KeyGap);
Key(dl, i, on[i], new Vector2(kx, y), new Vector2(kw, h));
kx += kw + Px(KeyGap);
}
float keysEnd = kx - Px(KeyGap);
// Force rebuff, set apart at the right.
// Auto-sort, then Force rebuff, set apart at the right.
Vector2 fp = new(x0 + w - Px(FrW), y), fs = new(Px(FrW), h);
dl.AddLine(new Vector2(fp.X - Px(Gap) - 0.5f, y + (h - Px(18)) * 0.5f), new Vector2(fp.X - Px(Gap) - 0.5f, y + (h + Px(18)) * 0.5f), _line);
float group = fp.X;
if (sort >= 0)
{
group = fp.X - Px(KeyGap) - kw;
SortKey(dl, sort == 1, new Vector2(group, y), new Vector2(kw, h));
}
float lx = MathF.Round(MathF.Max(group - Px(Gap), keysEnd + (group - keysEnd) * 0.5f)) - 0.5f;
dl.AddLine(new Vector2(lx, y + (h - Px(18)) * 0.5f), new Vector2(lx, y + (h + Px(18)) * 0.5f), _line);
ImGui.SetCursorScreenPos(fp);
if (ImGui.InvisibleButton("##fr", fs, ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonRight)
&& ImGui.IsMouseReleased(ImGuiMouseButton.Left))
@ -467,6 +489,29 @@ internal sealed unsafe class InstrumentDashboard
bool right = ImGui.IsItemClicked(ImGuiMouseButton.Right);
bool hot = ImGui.IsItemHovered();
SafeImGui.SetItemTooltip((on ? s.Name + " on. Click to turn it off." : s.Name + " off. Click to turn it on.") + "\nRight-click: " + s.Right + ".");
KeyFace(dl, s.Icon, on, hot, pos, size);
if (clicked) _d.SetSubsystem(i, !on);
if (right) SubsystemSettings(i);
}
/// <summary>RynthSort's auto-sort, a key like the subsystems'. Click: on/off; right-click: RynthSort's window.</summary>
private void SortKey(ImDrawListPtr dl, bool on, Vector2 pos, Vector2 size)
{
ImGui.SetCursorScreenPos(pos);
bool clicked = ImGui.InvisibleButton("##key_sort", size, ImGuiButtonFlags.MouseButtonLeft | ImGuiButtonFlags.MouseButtonRight)
&& ImGui.IsMouseReleased(ImGuiMouseButton.Left);
bool right = ImGui.IsItemClicked(ImGuiMouseButton.Right);
bool hot = ImGui.IsItemHovered();
SafeImGui.SetItemTooltip(on ? "Auto-sort (RynthSort) on. Click to turn it off.\nRight-click: RynthSort's window."
: "Auto-sort (RynthSort) off. Click to turn it on.\nRight-click: RynthSort's window.");
KeyFace(dl, RynthIcons.SortAscending, on, hot, pos, size);
if (clicked) _d.SetAutoSort(!on);
if (right) _d.ToggleSortWindow();
}
/// <summary>A key's face: raised with its LED lit when on, flat and dim when off.</summary>
private void KeyFace(ImDrawListPtr dl, string icon, bool on, bool hot, Vector2 pos, Vector2 size)
{
float r = Px(3);
if (on)
{
@ -478,7 +523,7 @@ internal sealed unsafe class InstrumentDashboard
{
dl.AddRect(pos, pos + size, Mix(_bg, _line, 0.55f), r);
}
DrawIcon(dl, s.Icon, pos, size, Px(15), on || hot ? _text : _faint);
DrawIcon(dl, icon, pos, size, Px(15), on || hot ? _text : _faint);
// The LED, top right: lit in the accent with a glow, or dark.
Vector2 led = new(pos.X + size.X - Px(6), pos.Y + Px(6));
if (on)
@ -491,8 +536,6 @@ internal sealed unsafe class InstrumentDashboard
dl.AddCircleFilled(led, Px(2), _inset, 12);
dl.AddCircle(led, Px(2), _line, 12, 1f);
}
if (clicked) _d.SetSubsystem(i, !on);
if (right) SubsystemSettings(i);
}
/// <summary>A key's right-click: its settings.</summary>
@ -543,7 +586,7 @@ internal sealed unsafe class InstrumentDashboard
Vector2 p = new(bx, y), s = new(ex - bx, h);
bool lit = l.Label switch
{
"Patrol" => !_popped && prefs.IsOpen(DashboardPrefs.PatrolDrawer),
"Patrol" => prefs.IsOpen(DashboardPrefs.PatrolDrawer),
"Char" => host.SetPanelOpen(OracleKey, RynthPanelOpen.Ask) == 1 || host.SetPanelOpen("Mini Remote", RynthPanelOpen.Ask) == 1,
_ => host.SetPanelOpen(l.Key, RynthPanelOpen.Ask) == 1,
};
@ -598,7 +641,7 @@ internal sealed unsafe class InstrumentDashboard
{
if (label == "Patrol")
{
if (!_popped) prefs.ToggleDrawer(DashboardPrefs.PatrolDrawer);
prefs.ToggleDrawer(DashboardPrefs.PatrolDrawer);
}
else if (label == "Char")
{
@ -887,7 +930,8 @@ internal sealed unsafe class InstrumentDashboard
}
if (_popped)
{
// No drawers popped out: the pickers are here.
// Popped out the pickers are here as well (an older RynthCore's pop-out lets clicks
// beside the panel through, so its drawers can't be used).
p.Y += Px(4);
dl.AddLine(new Vector2(p.X, p.Y + 0.5f), new Vector2(p.X + w, p.Y + 0.5f), _line);
p.Y += Px(5);
@ -1059,7 +1103,7 @@ internal sealed unsafe class InstrumentDashboard
if (ImGui.MenuItem(key, command, state == 1)) host.SetPanelOpen(key, RynthPanelOpen.Toggle);
}
// ── Drawers (docked): tabs on both edges, one panel open per side ───
// ── Drawers: tabs on both edges, one panel open per side ────────────
//
// Ranges, Loaded files, Patrol and the Mini Remote start on the left edge, My settings on the
// right; a tab's right-click moves its drawer to the other edge (DashboardPrefs keeps the sides,
@ -1214,7 +1258,7 @@ internal sealed unsafe class InstrumentDashboard
ImGui.End();
}
if (si >= 0 && shown >= 1f) DrawerPanel(prefs, DrawerDefs[si], si, panelW, shown, winX, panelX, dashPos.Y, right);
if (si >= 0 && shown >= 1f) DrawerPanel(prefs, DrawerDefs[si], si, panelW, shown, winX, panelX, dashPos.Y, dashSize.Y, right);
}
private int TabsOn(DashboardPrefs prefs, bool right)
@ -1225,6 +1269,7 @@ internal sealed unsafe class InstrumentDashboard
}
private const float SlideSeconds = 0.16f;
private const float PopOutReach = 600f;
private readonly float[] _slideT = new float[2]; // left, right: 0 closed .. 1 open
private readonly string[] _slideKey = { string.Empty, string.Empty }; // the drawer whose panel draws
@ -1272,12 +1317,15 @@ internal sealed unsafe class InstrumentDashboard
/// pixels of <paramref name="panelW"/>, from <paramref name="winX"/>), the panel drawn whole at
/// <paramref name="x"/> and clipped to it.
/// </summary>
private void DrawerPanel(DashboardPrefs prefs, DrawerDef def, int di, float panelW, float shown, float winX, float x, float top, bool right)
private void DrawerPanel(DashboardPrefs prefs, DrawerDef def, int di, float panelW, float shown, float winX, float x, float top, float dashH, bool right)
{
Vector2 display = ImGui.GetIO().DisplaySize;
// The frame around the body: padding, the title row, the gap under it.
float chrome = Px(7) + Px(20) + Px(5) + Px(8);
float maxBody = display.Y > 1 ? Math.Max(Px(60), display.Y - top - chrome - Px(8)) : Px(600);
// Popped out, the picture reaches at most PopOutReach pixels past the panel (RynthCore's
// ImGuiPopOuts.MaxMargin is 640): a longer drawer scrolls.
if (_popped) maxBody = Math.Max(Px(60), Math.Min(maxBody, dashH + PopOutReach - chrome));
float body = def.Key switch
{
DashboardPrefs.FilesDrawer => FilesHeight(),

View file

@ -323,7 +323,7 @@ public sealed partial class RynthAiPlugin
private void HandleGroundLootCommand(string[] parts)
{
var settings = _dashboard?.Settings;
if (settings == null) { ChatLine("[RynthAi] Not logged in."); return; }
if (settings == null) { ReplyFail("[RynthAi] Not logged in."); return; }
string verb = parts.Length >= 3 ? parts[2].Trim().ToLowerInvariant() : "status";
switch (verb)
@ -331,17 +331,17 @@ public sealed partial class RynthAiPlugin
case "on":
settings.EnableGroundLoot = true;
_dashboard?.SaveSettings();
ChatLine("[RynthAi] Ground loot ON (uses the loot profile and the corpse max range).");
ReplyOk("[RynthAi] Ground loot ON (uses the loot profile and the corpse max range).");
break;
case "off":
settings.EnableGroundLoot = false;
ResetGroundLoot(clearCaches: true);
_dashboard?.SaveSettings();
ChatLine("[RynthAi] Ground loot OFF.");
ReplyOk("[RynthAi] Ground loot OFF.");
break;
case "scan":
ResetGroundLoot(clearCaches: true);
ChatLine("[RynthAi] Ground loot: cleared skip list; rescanning.");
ReplyOk("[RynthAi] Ground loot: cleared skip list; rescanning.");
break;
default:
double yards = settings.CorpseApproachRangeMax;

View file

@ -55,12 +55,10 @@ public sealed partial class RynthAiPlugin
private bool KeystrokesAllowed(string verb)
{
if (_dashboard?.Settings.AllowMetaKeystrokes == true) return true;
if (_keystrokeRefusalSaid.Add(verb))
{
string msg = $"[RynthAi] {verb} ignored: it sends keys or clicks to the game window, and 'Allow metas to send keystrokes (/mt send)' is off (Settings, Advanced). Said once.";
Log(msg);
ChatLine(msg);
}
string why = $"[RynthAi] {verb} ignored: it sends keys or clicks to the game window, and 'Allow metas to send keystrokes (/mt send)' is off (Settings, Advanced).";
// Typed: said every time (a typed command always answers). A meta: said once per verb.
if (!Reply.FromScript) ReplyFail(why);
else if (_keystrokeRefusalSaid.Add(verb)) ReplyFail(why + " Said once.");
return false;
}
@ -72,9 +70,7 @@ public sealed partial class RynthAiPlugin
private bool RequireRunningMeta(string verb)
{
if (MetaCommandActive) return true;
string msg = $"[RynthAi] {verb} only runs from a meta that is running (macro and Meta on); refused.";
Log(msg);
ChatLine(msg);
ReplyFail($"[RynthAi] {verb} only runs from a meta that is running (macro and Meta on); refused.");
return false;
}
@ -95,13 +91,13 @@ public sealed partial class RynthAiPlugin
case "autopack":
// Mag-Tools packs by its own rules; RynthAi's equivalent is a cram + stack pass.
_inventoryManager?.RunManual(cram: true, stack: true);
ChatLine("[RynthAi] Autopack: cramming items into side packs and stacking them.");
ReplyOk("[RynthAi] Autopack: cramming items into side packs and stacking them.");
return true;
case "dumpspells": return HandleMtDumpSpells();
case "click": return HandleMtClick(parts);
case "get":
if (parts.Length >= 3 && parts[2].Equals("xy", StringComparison.OrdinalIgnoreCase)) return HandleMtCursor();
ChatLine("[RynthAi] Usage: /mt get xy");
ReplyFail("[RynthAi] Usage: /mt get xy");
return true;
case "cursor": return HandleMtCursor();
case "movement": return HandleMtMovement(parts);
@ -124,36 +120,43 @@ public sealed partial class RynthAiPlugin
/// </summary>
private bool HandleMtSend(string[] parts, string fullCommand)
{
if (parts.Length < 3) { ChatLine("[RynthAi] Usage: /mt send enter|pause|del|space|f4|f12|cntrl+<letter>|msg <text>"); return true; }
const string usage = "[RynthAi] Usage: /mt send enter|pause|del|space|f4|f12|cntrl+<letter>|msg <text>";
if (parts.Length < 3) { ReplyFail(usage); return true; }
string arg = parts[2].ToLowerInvariant();
if (parts[2].StartsWith('/'))
{
if (Host.HasInvokeChatParser) Host.InvokeChatParser(string.Join(" ", parts, 2, parts.Length - 2));
// The command answers for itself.
if (Host.HasInvokeChatParser) { Host.InvokeChatParser(string.Join(" ", parts, 2, parts.Length - 2)); Reply.Answered(); }
else ReplyFail("[RynthAi] /mt send: the chat parser isn't available.");
return true;
}
if (!KeystrokesAllowed("/mt send")) return true;
if (!GameInput.Available) { ChatLine("[RynthAi] /mt send: the game window wasn't found."); return true; }
Log($"[RynthAi] /mt send {string.Join(" ", parts, 2, Math.Min(parts.Length - 2, 2))}: keys posted to the game window");
if (!GameInput.Available) { ReplyFail("[RynthAi] /mt send: the game window wasn't found."); return true; }
string what = string.Join(" ", parts, 2, Math.Min(parts.Length - 2, 2));
Log($"[RynthAi] /mt send {what}: keys posted to the game window");
string sent = $"[RynthAi] /mt send {what}: sent to the game window.";
switch (arg)
{
case "enter": GameInput.SendEnter(); return true;
case "pause": GameInput.SendPause(); return true;
case "del": GameInput.SendDel(); return true;
case "space": GameInput.SendSpace(); return true;
case "f4": GameInput.SendF4(); return true;
case "f12": GameInput.SendF12(); return true;
case "enter": GameInput.SendEnter(); ReplyOk(sent); return true;
case "pause": GameInput.SendPause(); ReplyOk(sent); return true;
case "del": GameInput.SendDel(); ReplyOk(sent); return true;
case "space": GameInput.SendSpace(); ReplyOk(sent); return true;
case "f4": GameInput.SendF4(); ReplyOk(sent); return true;
case "f12": GameInput.SendF12(); ReplyOk(sent); return true;
case "msg":
int at = fullCommand.IndexOf(" msg ", StringComparison.OrdinalIgnoreCase);
if (at < 0 || at + 5 >= fullCommand.Length) { ChatLine("[RynthAi] Usage: /mt send msg <text>"); return true; }
if (at < 0 || at + 5 >= fullCommand.Length) { ReplyFail("[RynthAi] Usage: /mt send msg <text>"); return true; }
GameInput.SendMsg(fullCommand[(at + 5)..]);
ReplyOk("[RynthAi] /mt send msg: typed into the game window.");
return true;
}
if (arg.StartsWith("cntrl+", StringComparison.Ordinal) && arg.Length >= 7)
{
GameInput.SendCntrl(arg[6]);
ReplyOk(sent);
return true;
}
ChatLine("[RynthAi] Usage: /mt send enter|pause|del|space|f4|f12|cntrl+<letter>|msg <text>");
ReplyFail(usage);
return true;
}
@ -171,11 +174,12 @@ public sealed partial class RynthAiPlugin
ms = Math.Clamp(ms, 0, 1000);
string letters = (w ? "w" : "") + (x ? "x" : "") + (z ? "z" : "") + (c ? "c" : "") + (shift ? "s" : "");
if (_jumper != null && _jumper.Start(letters, null, ms)) return true;
if (_jumper != null && _jumper.Start(letters, null, ms)) { ReplyOk(JumpLine(letters, null, ms)); return true; }
if (_jumper?.IsBusy == true) return true; // it said so in chat
if (!KeystrokesAllowed("/mt jump (keys)")) return true;
if (!GameInput.Available) { ChatLine("[RynthAi] /mt jump: no jump hook and no game window."); return true; }
if (!GameInput.Available) { ReplyFail("[RynthAi] /mt jump: no jump hook and no game window."); return true; }
GameInput.SendSpace(ms, shift, w, z, x, c);
ReplyOk(JumpLine(letters, null, ms) + " (the space key)");
return true;
}
@ -184,37 +188,44 @@ public sealed partial class RynthAiPlugin
/// <summary>/mt trade add|addp &lt;item&gt; | accept | decline | reset | end.</summary>
private bool HandleMtTrade(string[] parts)
{
if (parts.Length < 3) { ChatLine("[RynthAi] Usage: /mt trade add|addp <item> | accept | decline | reset | end"); return true; }
if (parts.Length < 3) { ReplyFail("[RynthAi] Usage: /mt trade add|addp <item> | accept | decline | reset | end"); return true; }
string sub = parts[2].ToLowerInvariant();
// Completing a trade is only ever a running meta's doing (checked before anything else).
if (sub == "accept" && !RequireRunningMeta("/mt trade accept")) return true;
if (!Host.HasTrade) { ChatLine("[RynthAi] Trading needs a newer RynthCore engine."); return true; }
if (!Host.HasTrade) { ReplyFail("[RynthAi] Trading needs a newer RynthCore engine."); return true; }
switch (sub)
{
case "add":
case "addp":
{
if (parts.Length < 4) { ChatLine($"[RynthAi] Usage: /mt trade {sub} <item>"); return true; }
if (parts.Length < 4) { ReplyFail($"[RynthAi] Usage: /mt trade {sub} <item>"); return true; }
string name = string.Join(" ", parts, 3, parts.Length - 3);
var item = FindObject(name, inv: true, land: false, partial: sub == "addp");
if (item == null) { ChatLine($"[RynthAi] Item not found: '{name}'"); return true; }
ChatLine(Host.TradeAdd(unchecked((uint)item.Id))
? $"[RynthAi] Added {item.Name} to the trade." : "[RynthAi] Could not add it to the trade.");
if (item == null) { ReplyFail($"[RynthAi] Item not found: '{name}'"); return true; }
if (Host.TradeAdd(unchecked((uint)item.Id))) ReplyOk($"[RynthAi] Added {item.Name} to the trade.");
else ReplyFail("[RynthAi] Could not add it to the trade.");
return true;
}
case "accept":
Log("[RynthAi] /mt trade accept (from the running meta)");
Host.TradeAccept();
TradeSaid(Host.TradeAccept(), "Accepting the trade.", "accept");
return true;
case "decline": Host.TradeDecline(); return true;
case "reset": Host.TradeReset(); return true;
case "end": Host.TradeClose(); return true;
case "decline": TradeSaid(Host.TradeDecline(), "Declining the trade.", "decline"); return true;
case "reset": TradeSaid(Host.TradeReset(), "Clearing the trade window.", "reset"); return true;
case "end": TradeSaid(Host.TradeClose(), "Closing the trade.", "close"); return true;
default:
ChatLine("[RynthAi] Usage: /mt trade add|addp <item> | accept | decline | reset | end");
ReplyFail("[RynthAi] Usage: /mt trade add|addp <item> | accept | decline | reset | end");
return true;
}
}
/// <summary>A trade action's answer: what it does, or that it couldn't be sent.</summary>
private void TradeSaid(bool sent, string ok, string what)
{
if (sent) ReplyOk("[RynthAi] " + ok);
else ReplyFail($"[RynthAi] Could not send the trade {what}.");
}
// ── vendor ───────────────────────────────────────────────────────────────────
/// <summary>
@ -224,15 +235,15 @@ public sealed partial class RynthAiPlugin
private bool HandleMtVendor(string[] parts)
{
const string usage = "[RynthAi] Usage: /mt vendor addbuy|addbuyp <item> [count] | addsell|addsellp <item> | buy | clearbuy | sell | clearsell";
if (parts.Length < 3) { ChatLine(usage); return true; }
if (parts.Length < 3) { ReplyFail(usage); return true; }
// Spending or selling is only ever a running meta's doing (checked before anything else).
string verb = parts[2].ToLowerInvariant();
if (verb == "buy" && !RequireRunningMeta("/mt vendor buy")) return true;
if (verb == "sell" && !RequireRunningMeta("/mt vendor sell")) return true;
if (!Host.HasVendorTrade) { ChatLine("[RynthAi] Vendor trading needs a newer RynthCore engine."); return true; }
if (!Host.HasVendorTrade) { ReplyFail("[RynthAi] Vendor trading needs a newer RynthCore engine."); return true; }
if (!Host.TryGetVendorInfo(out VendorInfo info) || info.VendorId == 0)
{
ChatLine("[RynthAi] No vendor is open.");
ReplyFail("[RynthAi] No vendor is open.");
return true;
}
string sub = parts[2].ToLowerInvariant();
@ -241,7 +252,7 @@ public sealed partial class RynthAiPlugin
case "addbuy":
case "addbuyp":
{
if (parts.Length < 4) { ChatLine($"[RynthAi] Usage: /mt vendor {sub} <item> [count]"); return true; }
if (parts.Length < 4) { ReplyFail($"[RynthAi] Usage: /mt vendor {sub} <item> [count]"); return true; }
var words = parts.Skip(3).ToList();
int count = 1;
if (words.Count > 1 && int.TryParse(words[^1], out int n) && n > 0) { count = n; words.RemoveAt(words.Count - 1); }
@ -250,42 +261,42 @@ public sealed partial class RynthAiPlugin
VendorItem? item = Host.GetVendorItems().FirstOrDefault(v => partial
? v.Name.IndexOf(name, StringComparison.OrdinalIgnoreCase) >= 0
: string.Equals(v.Name, name, StringComparison.OrdinalIgnoreCase));
if (item == null) { ChatLine($"[RynthAi] {info.Name} doesn't sell '{name}'."); return true; }
if (item == null) { ReplyFail($"[RynthAi] {info.Name} doesn't sell '{name}'."); return true; }
_mtBuyList.Add((item.ObjectId, item.Name, count));
ChatLine($"[RynthAi] Buy list: {count} x {item.Name} ({_mtBuyList.Count} entr{(_mtBuyList.Count == 1 ? "y" : "ies")}).");
ReplyOk($"[RynthAi] Buy list: {count} x {item.Name} ({_mtBuyList.Count} entr{(_mtBuyList.Count == 1 ? "y" : "ies")}).");
return true;
}
case "addsell":
case "addsellp":
{
if (parts.Length < 4) { ChatLine($"[RynthAi] Usage: /mt vendor {sub} <item>"); return true; }
if (parts.Length < 4) { ReplyFail($"[RynthAi] Usage: /mt vendor {sub} <item>"); return true; }
string name = string.Join(" ", parts, 3, parts.Length - 3);
var item = FindObject(name, inv: true, land: false, partial: sub == "addsellp");
if (item == null) { ChatLine($"[RynthAi] Item not found: '{name}'"); return true; }
if (item == null) { ReplyFail($"[RynthAi] Item not found: '{name}'"); return true; }
uint id = unchecked((uint)item.Id);
if (!_mtSellList.Any(s => s.Id == id)) _mtSellList.Add((id, item.Name));
ChatLine($"[RynthAi] Sell list: {item.Name} ({_mtSellList.Count} item(s)).");
ReplyOk($"[RynthAi] Sell list: {item.Name} ({_mtSellList.Count} item(s)).");
return true;
}
case "buy":
{
if (_mtBuyList.Count == 0) { ChatLine("[RynthAi] The buy list is empty (/mt vendor addbuy <item> [count])."); return true; }
if (_mtBuyList.Count == 0) { ReplyFail("[RynthAi] The buy list is empty (/mt vendor addbuy <item> [count])."); return true; }
var entries = _mtBuyList.Select(b => new VendorTradeEntryNative(b.Id, b.Amount)).ToList();
Log($"[RynthAi] /mt vendor buy (from the running meta): {_mtBuyList.Count} entr{(_mtBuyList.Count == 1 ? "y" : "ies")} from {info.Name} 0x{info.VendorId:X8}: "
+ string.Join(", ", _mtBuyList.Select(b => $"{b.Amount} x {b.Name}")));
uint sent = Host.VendorBuy(info.VendorId, entries);
ChatLine(sent != 0 ? $"[RynthAi] Buying {_mtBuyList.Count} entr{(_mtBuyList.Count == 1 ? "y" : "ies")} from {info.Name}."
: "[RynthAi] The buy could not be sent.");
if (sent != 0) ReplyOk($"[RynthAi] Buying {_mtBuyList.Count} entr{(_mtBuyList.Count == 1 ? "y" : "ies")} from {info.Name}.");
else ReplyFail("[RynthAi] The buy could not be sent.");
if (sent != 0) _mtBuyList.Clear();
return true;
}
case "clearbuy":
_mtBuyList.Clear();
ChatLine("[RynthAi] Buy list cleared.");
ReplyOk("[RynthAi] Buy list cleared.");
return true;
case "sell":
{
if (_mtSellList.Count == 0) { ChatLine("[RynthAi] The sell list is empty (/mt vendor addsell <item>)."); return true; }
if (_mtSellList.Count == 0) { ReplyFail("[RynthAi] The sell list is empty (/mt vendor addsell <item>)."); return true; }
// Checked again now, not only when the item was listed: it may have been worn since,
// and RynthAi's own gear and consumables are never sold by a meta.
var toSell = new List<(uint Id, string Name)>();
@ -299,22 +310,23 @@ public sealed partial class RynthAiPlugin
if (toSell.Count == 0)
{
_mtSellList.Clear();
ChatLine("[RynthAi] Nothing left to sell: every listed item is protected.");
ReplyFail("[RynthAi] Nothing left to sell: every listed item is protected.");
return true;
}
Log($"[RynthAi] /mt vendor sell (from the running meta): {toSell.Count} item(s) to {info.Name} 0x{info.VendorId:X8}: "
+ string.Join(", ", toSell.Select(s => s.Name)));
uint sent = Host.VendorSell(info.VendorId, toSell.Select(s => s.Id).ToList());
ChatLine(sent != 0 ? $"[RynthAi] Selling {toSell.Count} item(s) to {info.Name}." : "[RynthAi] The sell could not be sent.");
if (sent != 0) ReplyOk($"[RynthAi] Selling {toSell.Count} item(s) to {info.Name}.");
else ReplyFail("[RynthAi] The sell could not be sent.");
if (sent != 0) _mtSellList.Clear();
return true;
}
case "clearsell":
_mtSellList.Clear();
ChatLine("[RynthAi] Sell list cleared.");
ReplyOk("[RynthAi] Sell list cleared.");
return true;
default:
ChatLine(usage);
ReplyFail(usage);
return true;
}
}
@ -374,9 +386,9 @@ public sealed partial class RynthAiPlugin
w.WriteLine($"{id}\t{name}\t{family}\t{difficulty}");
}
}
ChatLine($"[RynthAi] {rows.Count} spells written to {path}");
ReplyOk($"[RynthAi] {rows.Count} spells written to {path}");
}
catch (Exception ex) { ChatLine($"[RynthAi] /mt dumpspells failed: {ex.Message}"); }
catch (Exception ex) { ReplyFail($"[RynthAi] /mt dumpspells failed: {ex.Message}"); }
return true;
}
@ -390,9 +402,9 @@ public sealed partial class RynthAiPlugin
/// </summary>
private void HandleEquipForCommand(string[] parts)
{
if (parts.Length < 3) { ChatLine("[RynthAi] Usage: /ra equipfor <monster name>"); return; }
if (parts.Length < 3) { ReplyFail("[RynthAi] Usage: /ra equipfor <monster name>"); return; }
var rules = _dashboard?.Settings?.MonsterRules;
if (rules == null || rules.Count == 0) { ChatLine("[RynthAi] No monster rules loaded."); return; }
if (rules == null || rules.Count == 0) { ReplyFail("[RynthAi] No monster rules loaded."); return; }
string monster = string.Join(" ", parts, 2, parts.Length - 2).Trim();
var rule = rules.FirstOrDefault(r => string.Equals(r.Name, monster, StringComparison.OrdinalIgnoreCase))
@ -400,28 +412,28 @@ public sealed partial class RynthAiPlugin
&& r.Name.Length > 0 && monster.IndexOf(r.Name, StringComparison.OrdinalIgnoreCase) >= 0)
.OrderByDescending(r => r.Name.Length).FirstOrDefault()
?? rules.FirstOrDefault(r => string.Equals(r.Name, "Default", StringComparison.OrdinalIgnoreCase));
if (rule == null) { ChatLine($"[RynthAi] No monster rule for '{monster}'."); return; }
if (rule == null) { ReplyFail($"[RynthAi] No monster rule for '{monster}'."); return; }
var ids = new List<int>();
if (rule.WeaponId != 0) ids.Add(rule.WeaponId);
if (rule.OffhandId != 0) ids.Add(rule.OffhandId);
if (ids.Count == 0)
{
ChatLine($"[RynthAi] '{rule.Name}' has no set weapon (combat picks one when it fights '{monster}').");
ReplyOk($"[RynthAi] '{rule.Name}' has no set weapon (combat picks one when it fights '{monster}').");
return;
}
if (!Host.HasUseObject) { ChatLine("[RynthAi] UseObject not available."); return; }
if (!Host.HasUseObject) { ReplyFail("[RynthAi] UseObject not available."); return; }
int sent = 0;
foreach (int id in ids)
{
var wo = _objectCache?[id];
if (wo == null) { ChatLine($"[RynthAi] '{rule.Name}': item 0x{(uint)id:X8} isn't carried."); continue; }
if (wo == null) { ReplyFail($"[RynthAi] '{rule.Name}': item 0x{(uint)id:X8} isn't carried."); continue; }
if (wo.Values(LongValueKey.CurrentWieldedLocation, 0) > 0) continue; // already wielded
Host.UseFor(unchecked((uint)id), "Command", "/ra equipfor", UseKind.Asked);
sent++;
}
ChatLine(sent > 0 ? $"[RynthAi] Equipping for '{monster}' ({rule.Name}): {sent} item(s)."
ReplyOk(sent > 0 ? $"[RynthAi] Equipping for '{monster}' ({rule.Name}): {sent} item(s)."
: $"[RynthAi] '{rule.Name}' gear for '{monster}' is already wielded.");
}
@ -430,21 +442,22 @@ public sealed partial class RynthAiPlugin
/// <summary>/mt click ok|yes|no|&lt;x&gt; &lt;y&gt;: a click in the game window (window coordinates).</summary>
private bool HandleMtClick(string[] parts)
{
if (parts.Length < 3) { ChatLine("[RynthAi] Usage: /mt click ok|yes|no|<x> <y>"); return true; }
if (parts.Length < 3) { ReplyFail("[RynthAi] Usage: /mt click ok|yes|no|<x> <y>"); return true; }
if (!KeystrokesAllowed("/mt click")) return true;
if (!GameInput.Available) { ChatLine("[RynthAi] /mt click: the game window wasn't found."); return true; }
if (!GameInput.Available) { ReplyFail("[RynthAi] /mt click: the game window wasn't found."); return true; }
switch (parts[2].ToLowerInvariant())
{
case "ok": GameInput.ClickOK(); return true;
case "yes": GameInput.ClickYes(); return true;
case "no": GameInput.ClickNo(); return true;
case "ok": GameInput.ClickOK(); ReplyOk("[RynthAi] Clicked OK."); return true;
case "yes": GameInput.ClickYes(); ReplyOk("[RynthAi] Clicked Yes."); return true;
case "no": GameInput.ClickNo(); ReplyOk("[RynthAi] Clicked No."); return true;
}
if (parts.Length >= 4 && int.TryParse(parts[2], out int x) && int.TryParse(parts[3], out int y))
{
GameInput.SendMouseClick(x, y);
ReplyOk($"[RynthAi] Clicked at {x},{y} in the game window.");
return true;
}
ChatLine("[RynthAi] Usage: /mt click ok|yes|no|<x> <y>");
ReplyFail("[RynthAi] Usage: /mt click ok|yes|no|<x> <y>");
return true;
}
@ -462,12 +475,13 @@ public sealed partial class RynthAiPlugin
{
if (parts.Length != 4 || parts[2].Length != 1 || !int.TryParse(parts[3], out int ms) || ms < 0)
{
ChatLine("[RynthAi] Usage: /mt movement <key> <ms> (e.g. /mt movement w 1500)");
ReplyFail("[RynthAi] Usage: /mt movement <key> <ms> (e.g. /mt movement w 1500)");
return true;
}
if (!KeystrokesAllowed("/mt movement")) return true;
if (!GameInput.Available) { ChatLine("[RynthAi] /mt movement: the game window wasn't found."); return true; }
if (!GameInput.Available) { ReplyFail("[RynthAi] /mt movement: the game window wasn't found."); return true; }
GameInput.SendMovement(parts[2][0], ms);
ReplyOk($"[RynthAi] Holding '{parts[2][0]}' for {ms} ms.");
return true;
}
@ -476,14 +490,15 @@ public sealed partial class RynthAiPlugin
{
if (parts.Length != 4 || !int.TryParse(parts[3], out int ms) || ms < 0)
{
ChatLine("[RynthAi] Usage: /mt strafe left|l|right|r <ms>");
ReplyFail("[RynthAi] Usage: /mt strafe left|l|right|r <ms>");
return true;
}
char key = parts[2].ToLowerInvariant() switch { "left" or "l" => 'z', "right" or "r" => 'c', _ => '\0' };
if (key == '\0') { ChatLine("[RynthAi] /mt strafe: left, l, right or r."); return true; }
if (key == '\0') { ReplyFail("[RynthAi] Usage: /mt strafe left|l|right|r <ms>"); return true; }
if (!KeystrokesAllowed("/mt strafe")) return true;
if (!GameInput.Available) { ChatLine("[RynthAi] /mt strafe: the game window wasn't found."); return true; }
if (!GameInput.Available) { ReplyFail("[RynthAi] /mt strafe: the game window wasn't found."); return true; }
GameInput.SendMovement(key, ms);
ReplyOk($"[RynthAi] Strafing {(key == 'z' ? "left" : "right")} for {ms} ms.");
return true;
}
@ -493,13 +508,13 @@ public sealed partial class RynthAiPlugin
string sub = parts.Length >= 3 ? parts[2].ToLowerInvariant() : "";
switch (sub)
{
case "minimize": if (KeystrokesAllowed("/mt client")) GameInput.Minimize(); return true;
case "restore": if (KeystrokesAllowed("/mt client")) GameInput.Restore(); return true;
case "minimize": if (KeystrokesAllowed("/mt client")) { GameInput.Minimize(); ReplyOk("[RynthAi] Game window minimized."); } return true;
case "restore": if (KeystrokesAllowed("/mt client")) { GameInput.Restore(); ReplyOk("[RynthAi] Game window restored."); } return true;
case "frame":
ChatLine("[RynthAi] The window frame is RynthCore's: Settings > Display (Borderless Windowed, Reset Window Borders) or /rc window reset.");
ChatLine("[RynthAi] The window frame is RynthCore's: Settings > Display, Borderless Windowed (there is no chat command for it).");
return true;
default:
ChatLine("[RynthAi] Usage: /mt client minimize | restore");
ReplyFail("[RynthAi] Usage: /mt client minimize | restore");
return true;
}
}

View file

@ -82,14 +82,16 @@ public sealed partial class RynthAiPlugin
// ── Session ──────────────────────────────────────────────────────
case "logoff":
case "logout":
if (Host.HasInvokeChatParser) Host.InvokeChatParser("/logout");
if (Host.HasInvokeChatParser) { Host.InvokeChatParser("/logout"); Reply.Answered(); } // the client logs out
else ReplyFail("[RynthAi] Can't log out: the chat parser isn't available.");
return true;
case "quit":
case "exit":
// Close the client (also /ub quit|exit, which land here). "/quit" is not an AC
// client command and did nothing; the engine's /rc quit closes the client the way
// its close button does, logging the character off.
if (Host.HasInvokeChatParser) Host.InvokeChatParser("/rc quit");
if (Host.HasInvokeChatParser) { Host.InvokeChatParser("/rc quit"); Reply.Answered(); } // the client closes
else ReplyFail("[RynthAi] Can't close the client: the chat parser isn't available.");
return true;
// ── Keys in the game window (Mag-Tools /mt send); a "/" line is still sent as a command ──
@ -119,7 +121,7 @@ public sealed partial class RynthAiPlugin
if (sub == "list")
{
var map = _metaManager?.Expressions?.BuildSettingsMapPublic();
if (map == null) { ChatLine("[RynthAi] Settings not ready."); return true; }
if (map == null) { ReplyFail("[RynthAi] Settings not ready."); return true; }
ChatLine("[RynthAi] === Options ===");
foreach (var kvp in map)
ChatLine($"[RynthAi] {kvp.Key} = {kvp.Value.Get()}");
@ -130,9 +132,8 @@ public sealed partial class RynthAiPlugin
{
string optName = parts[3];
string? val = GetOptionValue(optName);
ChatLine(val != null
? $"[RynthAi] {optName} = {val}"
: $"[RynthAi] Unknown option: {optName}");
if (val != null && OptionKnown(optName)) ChatLine($"[RynthAi] {optName} = {val}");
else ReplyFail($"[RynthAi] Unknown option: {optName} (/mt opt list shows them).");
return true;
}
@ -140,7 +141,9 @@ public sealed partial class RynthAiPlugin
{
string optName = parts[3];
string optVal = parts[4];
if (_metaManager?.Expressions == null) { ReplyFail("[RynthAi] Settings not ready (log in first)."); return true; }
SetOptionValue(optName, optVal);
ReplyOptionValue(optName, optVal);
return true;
}
@ -152,8 +155,10 @@ public sealed partial class RynthAiPlugin
if (val != null)
{
_rememberedOptions[optName.ToLower()] = val;
Host.Log($"[RynthAi] Remembered {optName} = {val}");
ReplyOk($"[RynthAi] Remembered {optName} = {val}"
+ (OptionKnown(optName) ? "" : " (not an option RynthAi maps or a meta has set)"));
}
else ReplyFail($"[RynthAi] Unknown option: {optName} (nothing to remember).");
return true;
}
@ -163,14 +168,68 @@ public sealed partial class RynthAiPlugin
if (_rememberedOptions.TryGetValue(optName.ToLower(), out string? saved))
{
SetOptionValue(optName, saved);
Host.Log($"[RynthAi] Restored {optName} = {saved}");
ReplyOk($"[RynthAi] Restored {optName} = {saved}");
}
else ReplyFail($"[RynthAi] Nothing remembered for {optName} (/mt opt remember {optName} first).");
return true;
}
return false;
}
/// <summary>A Mag-Tools / VTank option RynthAi maps, or one a meta has stored (an unknown name reads as 0).</summary>
private bool OptionKnown(string optName)
=> MtOptionMap.ContainsKey(optName) || _metaManager?.Expressions?.Options.ContainsKey(optName) == true;
/// <summary>
/// After /mt opt set (and /ub opt set): the option's value now. Bools read back as 1/0; asked as
/// true/false/on/off they show as True/False. An option RynthAi doesn't map is only kept for metas.
/// </summary>
private void ReplyOptionValue(string optName, string asked)
{
string now = GetOptionValue(optName) ?? "(not set)";
bool askedBool = asked.ToLowerInvariant() is "true" or "false" or "on" or "off";
if (askedBool && now is "1" or "0") now = now == "1" ? "True" : "False";
ReplyOk($"[RynthAi] {optName} = {now}"
+ (MtOptionMap.ContainsKey(optName) ? "" : " (not an option RynthAi maps: kept only for metas to read)"));
}
/// <summary>The /mt verbs RynthAi takes, for the usage line.</summary>
private const string MtVerbList = "opt, combatstate, face, cast[p], use[i|l][p], select[p], give[p], loot[p], drop[p], "
+ "equip[p], dequip[p], fellow, logout, quit, send, jump, trade, vendor, autopack, dumpspells, click, get xy, "
+ "cursor, movement, strafe, client, config, test";
/// <summary>How to use a /mt (or, with <paramref name="prefix"/> "/ub", a translated /ub) verb; null when it isn't one.</summary>
private static string? MtVerbUsage(string verb, string prefix) => verb switch
{
"opt" or "config" => $"{prefix} opt list | get <option> | set <option> <value> | remember <option> | restore <option>"
+ (prefix == "/ub" ? " | toggle <options>" : ""),
"combatstate" => $"{prefix} combatstate peace|melee|missile|magic",
"face" => $"{prefix} face <degrees> | {prefix} face <NS>, <EW> (e.g. 42.1N, 33.6E)",
"cast" or "castp" => $"{prefix} {verb} <spell id|name> [on <target>]",
"use" or "usep" or "usei" or "useip" or "usepi" or "usel" or "uselp" or "usepl"
=> $"{prefix} {verb} <name> [on <name2>] | {prefix} use closestnpc|closestvendor|closestportal",
"select" or "selectp" => $"{prefix} {verb} <name>",
"give" or "givep" => $"{prefix} {verb} {(prefix == "/ub" ? "[count] " : "")}<item> to <target>",
"loot" or "lootp" => $"{prefix} {verb} <item> (from the open corpse or chest)",
"drop" or "dropp" => $"{prefix} {verb} <item>",
"equip" or "equipp" => $"{prefix} {verb} <item>",
"dequip" or "dequipp" => $"{prefix} {verb} <wielded item>",
"fellow" => $"{prefix} fellow create <name> | open | close | disband | quit | recruit <name>",
_ => null,
};
/// <summary>The usage line for a /mt line RynthAi didn't take (an unknown verb or the wrong arguments).</summary>
private static string MtUsageFor(string line)
{
string[] w = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
string verb = w.Length > 1 ? w[1].ToLowerInvariant() : "";
string? usage = MtVerbUsage(verb, "/mt");
return usage != null
? "[RynthAi] Usage: " + usage
: $"[RynthAi] Unknown /mt command{(verb.Length > 0 ? $" '{verb}'" : "")}. RynthAi takes: {MtVerbList}.";
}
private readonly Dictionary<string, string> _rememberedOptions = new(StringComparer.OrdinalIgnoreCase);
// VTank/MagTools option name → RynthAi settings name
@ -279,7 +338,7 @@ public sealed partial class RynthAiPlugin
{
// /mt combatstate [magic,melee,missile,peace]
if (parts.Length < 3) return false;
if (!Host.HasChangeCombatMode) { ChatLine("[RynthAi] ChangeCombatMode not available."); return true; }
if (!Host.HasChangeCombatMode) { ReplyFail("[RynthAi] ChangeCombatMode not available."); return true; }
string mode = parts[2].ToLower();
int cm = mode switch
@ -291,9 +350,10 @@ public sealed partial class RynthAiPlugin
_ => 0
};
if (cm == 0) { ChatLine($"[RynthAi] Unknown combat mode: {mode}"); return true; }
if (cm == 0) { ReplyFail($"[RynthAi] Unknown combat mode: {mode}. Usage: /mt combatstate peace|melee|missile|magic"); return true; }
Host.ChangeCombatModeFor(cm, "Command", "/mt combat", force: true);
ReplyOk($"[RynthAi] Combat mode: {mode}.");
return true;
}
@ -316,9 +376,13 @@ public sealed partial class RynthAiPlugin
// The jumper holds navigation while it turns (nav would turn the character back) and turns
// again until it faces the heading, as ub-IT does; without it, one plain turn.
if (_jumper != null) _jumper.Face(heading);
else if (Host.HasTurnToHeading) Host.TurnToHeadingBy("Command", (float)(((heading % 360) + 360) % 360));
else ChatLine("[RynthAi] TurnToHeading not available.");
double norm = ((heading % 360) + 360) % 360;
if (_jumper != null)
{
if (_jumper.Face(heading)) ReplyOk($"[RynthAi] Facing {norm:0.#}°."); // a refusal says why itself
}
else if (Host.HasTurnToHeading) { Host.TurnToHeadingBy("Command", (float)norm); ReplyOk($"[RynthAi] Facing {norm:0.#}°."); }
else ReplyFail("[RynthAi] TurnToHeading not available.");
return true;
}
@ -353,7 +417,7 @@ public sealed partial class RynthAiPlugin
{
// /mt cast[p] <#|name> [on <target>]
if (parts.Length < 3) return false;
if (!Host.HasCastSpell) { ChatLine("[RynthAi] CastSpell not available."); return true; }
if (!Host.HasCastSpell) { ReplyFail("[RynthAi] CastSpell not available."); return true; }
string argStr = string.Join(" ", parts, 2, parts.Length - 2);
@ -370,7 +434,7 @@ public sealed partial class RynthAiPlugin
targetId = unchecked((uint)targetObj.Id);
else
{
ChatLine($"[RynthAi] Target not found: '{targetName}'");
ReplyFail($"[RynthAi] Target not found: '{targetName}'");
return true;
}
}
@ -406,7 +470,7 @@ public sealed partial class RynthAiPlugin
if (spellId == 0)
{
ChatLine($"[RynthAi] Spell not found: '{spellArg}'");
ReplyFail($"[RynthAi] Spell not found: '{spellArg}'");
return true;
}
}
@ -417,7 +481,11 @@ public sealed partial class RynthAiPlugin
targetId = Host.GetPlayerId();
}
Host.CastSpellFor(targetId, spellId, "Command", $"spell {spellId} (/mt cast)", asked: true);
bool cast = Host.CastSpellFor(targetId, spellId, "Command", $"spell {spellId} (/mt cast)", asked: true);
string spellName = SpellDatabase.HasSpell(spellId) ? SpellDatabase.GetSpellName(spellId) : $"spell {spellId}";
string on = targetId == Host.GetPlayerId() ? "yourself" : (Host.TryGetObjectName(targetId, out string tn) && tn.Length > 0 ? tn : $"0x{targetId:X8}");
if (cast) ReplyOk($"[RynthAi] Casting {spellName} on {on}.");
else ReplyFail($"[RynthAi] Couldn't cast {spellName} on {on} (the engine refused it).");
return true;
}
@ -452,11 +520,11 @@ public sealed partial class RynthAiPlugin
{
if (_objectCache == null || _playerId == 0)
{
ChatLine("[RynthAi] Not ready.");
ReplyFail("[RynthAi] Not ready.");
return true;
}
if (!Host.HasUseObject) { ChatLine("[RynthAi] UseObject not available."); return true; }
if (!Host.HasUseObject) { ReplyFail("[RynthAi] UseObject not available."); return true; }
int playerId = (int)_playerId;
WorldObject? best = null;
@ -484,12 +552,13 @@ public sealed partial class RynthAiPlugin
if (best == null)
{
ChatLine($"[RynthAi] No {type.Replace("closest", "")} found nearby.");
ReplyFail($"[RynthAi] No {type.Replace("closest", "")} found nearby.");
return true;
}
Host.UseFor(unchecked((uint)best.Id), "Command", $"/mt use {type}", UseKind.Asked);
Host.Log($"[RynthAi] /mt use {type}: {best.Name} (0x{(uint)best.Id:X8}) at {bestDist:F1}m");
ReplyOk($"[RynthAi] Using {best.Name} ({bestDist:F1} m).");
return true;
}
@ -503,7 +572,7 @@ public sealed partial class RynthAiPlugin
string argStr = string.Join(" ", parts, 2, parts.Length - 2);
int toIdx = argStr.IndexOf(" to ", StringComparison.OrdinalIgnoreCase);
if (toIdx < 0) { ChatLine("[RynthAi] Usage: /mt give[p] <item> to <target>"); return true; }
if (toIdx < 0) { ReplyFail("[RynthAi] Usage: /mt give[p] <item> to <target>"); return true; }
string itemName = argStr[..toIdx].Trim();
string targetName = argStr[(toIdx + 4)..].Trim();
@ -514,10 +583,10 @@ public sealed partial class RynthAiPlugin
? n.IndexOf(itemName, StringComparison.OrdinalIgnoreCase) >= 0
: string.Equals(n, itemName, StringComparison.OrdinalIgnoreCase));
var item = candidates.Count > 0 ? candidates[0] : null;
if (item == null) { ChatLine($"[RynthAi] Item not found: '{itemName}'"); return true; }
if (item == null) { ReplyFail($"[RynthAi] Item not found: '{itemName}'"); return true; }
var target = FindObject(targetName, inv: false, land: true, partial: true);
if (target == null) { ChatLine($"[RynthAi] Target not found: '{targetName}'"); return true; }
if (target == null) { ReplyFail($"[RynthAi] Target not found: '{targetName}'"); return true; }
// Giving to an NPC requires AC's give GameAction (Event_GiveObjectRequest).
// The old path used MoveItemExternal = move-to-CONTAINER, which does NOT
@ -528,10 +597,12 @@ public sealed partial class RynthAiPlugin
{
bool ok = Host.GiveObjectTo(unchecked((uint)item.Id), unchecked((uint)target.Id), 0);
Host.Log($"[RynthAi] /mt give: {item.Name} → {target.Name} (give ok={ok})");
if (ok) ReplyOk($"[RynthAi] Giving {item.Name} to {target.Name}.");
else ReplyFail($"[RynthAi] Couldn't give {item.Name} to {target.Name} (the engine refused it).");
}
else
{
ChatLine("[RynthAi] Give requires engine API v62+ — update the RynthCore engine.");
ReplyFail("[RynthAi] Give requires engine API v62+ — update the RynthCore engine.");
}
return true;
}
@ -654,7 +725,7 @@ public sealed partial class RynthAiPlugin
{
// Pick a named item from the currently opened corpse/container.
if (parts.Length < 3) return false;
if (!Host.HasUseObject) { ChatLine("[RynthAi] UseObject not available."); return true; }
if (!Host.HasUseObject) { ReplyFail("[RynthAi] UseObject not available."); return true; }
string name = string.Join(" ", parts, 2, parts.Length - 2).Trim();
int container = ResolveOpenLootContainer();
@ -669,6 +740,7 @@ public sealed partial class RynthAiPlugin
Host.UseFor(found.Value.Id, "Command", "/mt loot", UseKind.Asked);
Host.Log($"[RynthAi] /mt loot: {found.Value.Name} (0x{found.Value.Id:X8}) from container 0x{(uint)container:X8}");
_pendingMtLootName = null;
ReplyOk($"[RynthAi] Looting {found.Value.Name}.");
return true;
}
@ -680,9 +752,9 @@ public sealed partial class RynthAiPlugin
itemNames.Append(item.Name);
}
if (itemNames.Length > 0)
ChatLine($"[RynthAi] /mt loot: '{name}' not found. Container 0x{(uint)container:X8} contains: {itemNames}");
ReplyFail($"[RynthAi] /mt loot: '{name}' not found. Container 0x{(uint)container:X8} contains: {itemNames}");
else
ChatLine($"[RynthAi] /mt loot: '{name}' not found (container 0x{(uint)container:X8} appears empty or still loading — queuing)");
ReplyFail($"[RynthAi] /mt loot: '{name}' not found (container 0x{(uint)container:X8} appears empty or still loading — queuing)");
}
// Container not open yet, or items not in cache — queue for deferred retry.
@ -690,6 +762,8 @@ public sealed partial class RynthAiPlugin
_pendingMtLootPartial = partial;
_pendingMtLootExpiryMs = CorpseNowMs + PendingMtLootTimeoutMs;
Host.Log($"[RynthAi] /mt loot: '{name}' queued (container=0x{(uint)container:X8})");
if (container == 0)
ReplyOk($"[RynthAi] /mt loot: no container is open yet; '{name}' is taken when one opens (for {PendingMtLootTimeoutMs / 1000} s).");
return true;
}
@ -700,15 +774,16 @@ public sealed partial class RynthAiPlugin
private bool HandleMtDrop(string[] parts, bool partial)
{
if (parts.Length < 3) return false;
if (!Host.HasMoveItemExternal) { ChatLine("[RynthAi] MoveItemExternal not available."); return true; }
if (!Host.HasMoveItemExternal) { ReplyFail("[RynthAi] MoveItemExternal not available."); return true; }
string name = string.Join(" ", parts, 2, parts.Length - 2).Trim();
var item = FindObject(name, inv: true, land: false, partial: partial);
if (item == null) { ChatLine($"[RynthAi] Item not found in inventory: '{name}'"); return true; }
if (item == null) { ReplyFail($"[RynthAi] Item not found in inventory: '{name}'"); return true; }
// Drop = move to the ground (container 0)
Host.MoveItemExternal(unchecked((uint)item.Id), 0, 0);
Host.Log($"[RynthAi] /mt drop: {item.Name} (0x{(uint)item.Id:X8})");
ReplyOk($"[RynthAi] Dropping {item.Name}.");
return true;
}
@ -719,26 +794,27 @@ public sealed partial class RynthAiPlugin
private bool HandleMtEquip(string[] parts, bool partial)
{
if (parts.Length < 3) return false;
if (!Host.HasUseObject) { ChatLine("[RynthAi] UseObject not available."); return true; }
if (!Host.HasUseObject) { ReplyFail("[RynthAi] UseObject not available."); return true; }
string name = string.Join(" ", parts, 2, parts.Length - 2).Trim();
var item = FindObject(name, inv: true, land: false, partial: partial);
if (item == null) { ChatLine($"[RynthAi] Item not found: '{name}'"); return true; }
if (item == null) { ReplyFail($"[RynthAi] Item not found: '{name}'"); return true; }
Host.UseFor(unchecked((uint)item.Id), "Command", "/mt use item", UseKind.Asked);
Host.Log($"[RynthAi] /mt equip: {item.Name} (0x{(uint)item.Id:X8})");
ReplyOk($"[RynthAi] Equipping {item.Name}.");
return true;
}
private bool HandleMtDequip(string[] parts, bool partial)
{
if (parts.Length < 3) return false;
if (!Host.HasMoveItemInternal) { ChatLine("[RynthAi] MoveItemInternal not available."); return true; }
if (!Host.HasMoveItemInternal) { ReplyFail("[RynthAi] MoveItemInternal not available."); return true; }
string name = string.Join(" ", parts, 2, parts.Length - 2).Trim();
// Find a wielded item matching the name
if (_objectCache == null) { ChatLine("[RynthAi] Cache not ready."); return true; }
if (_objectCache == null) { ReplyFail("[RynthAi] Cache not ready."); return true; }
WorldObject? found = null;
foreach (var wo in _objectCache.GetInventory())
@ -750,7 +826,7 @@ public sealed partial class RynthAiPlugin
if (match) { found = wo; break; }
}
if (found == null) { ChatLine($"[RynthAi] Wielded item not found: '{name}'"); return true; }
if (found == null) { ReplyFail($"[RynthAi] Wielded item not found: '{name}'"); return true; }
// FIX (2026-06-24): MoveItemInternal with amount=0 is a silent no-op — the engine
// guard (ClientHelperHooks.cs:431 `if (amount <= 0) return false;`) rejects it, so
@ -760,11 +836,12 @@ public sealed partial class RynthAiPlugin
int dest = WorldObjectCache.FindPackFor(Host, _objectCache, includeMainPack: true, requireFree: 1);
if (dest == 0)
{
ChatLine($"[RynthAi] /mt dequip: no open pack for '{found.Name}' — inventory full.");
ReplyFail($"[RynthAi] /mt dequip: no open pack for '{found.Name}' — inventory full.");
return true;
}
Host.MoveItemInternal(unchecked((uint)found.Id), unchecked((uint)dest), 0, 1);
Host.Log($"[RynthAi] /mt dequip: {found.Name} (0x{(uint)found.Id:X8}) → pack 0x{(uint)dest:X8}");
ReplyOk($"[RynthAi] Taking off {found.Name} (into a pack).");
return true;
}
@ -784,8 +861,9 @@ public sealed partial class RynthAiPlugin
// /mt fellow recruit <name>
// Route through chat parser since AC handles these natively
if (parts.Length < 3) return false;
if (!Host.HasInvokeChatParser) { ChatLine("[RynthAi] ChatParser not available."); return true; }
if (!Host.HasInvokeChatParser) { ReplyFail("[RynthAi] ChatParser not available."); return true; }
// The server answers each of these in chat ("You have created the fellowship ...").
string sub = parts[2].ToLower();
switch (sub)
{
@ -794,26 +872,34 @@ public sealed partial class RynthAiPlugin
{
string fellowName = string.Join(" ", parts, 3, parts.Length - 3);
Host.InvokeChatParser($"/fellowship create {fellowName}");
Reply.Answered();
}
else ReplyFail($"[RynthAi] Usage: {parts[0]} fellow create <fellowship name>");
return true;
case "open":
Host.InvokeChatParser("/fellowship open");
Reply.Answered();
return true;
case "close":
Host.InvokeChatParser("/fellowship close");
Reply.Answered();
return true;
case "disband":
Host.InvokeChatParser("/fellowship disband");
Reply.Answered();
return true;
case "quit":
Host.InvokeChatParser("/fellowship quit");
Reply.Answered();
return true;
case "recruit":
if (parts.Length >= 4)
{
string playerName = string.Join(" ", parts, 3, parts.Length - 3);
Host.InvokeChatParser($"/fellowship recruit {playerName}");
Reply.Answered();
}
else ReplyFail($"[RynthAi] Usage: {parts[0]} fellow recruit <player name>");
return true;
default:
return false;

View file

@ -152,6 +152,16 @@ internal sealed class MetaManager
public void SetMtCommandHandler(Func<string, bool> handler) => _mtCommandHandler = handler;
public void SetRaCommandHandler(Action<string> handler) => _raCommandHandler = handler;
private CommandReply? _reply;
/// <summary>What /vt commands say back (CommandReply.cs). The plugin hands over its own, so a /vt
/// line answers like every other command; on its own (tests) a meta's action is the "sent by a meta" test.</summary>
internal CommandReply Reply
{
get => _reply ??= new CommandReply((text, color) => _host.WriteToChat(text, color), line => _host.Log(line), () => IsExecutingAction);
set => _reply = value;
}
/// <summary>Embedded Nav Route's "Patrol" (any case): the dungeon patrol instead of a route,
/// unless the meta or NavProfiles has a route by that name.</summary>
internal const string PatrolRoute = "Patrol";
@ -1276,7 +1286,9 @@ internal sealed class MetaManager
{
string optName = parts[3].ToLower();
string optVal = parts[4];
return TrySetVtOption(optName, optVal);
bool set = TrySetVtOption(optName, optVal);
ReplyVtOption(parts[3], optVal);
return set;
}
// /vt opt get <option> — show one option's value.
@ -1284,7 +1296,7 @@ internal sealed class MetaManager
parts[2].Equals("get", StringComparison.OrdinalIgnoreCase))
{
string optName = parts[3];
_host.WriteToChat($"[RynthAi] {optName} = {GetVtOption(optName) ?? "(not set)"}", 1);
Reply.Info($"[RynthAi] {optName} = {GetVtOption(optName) ?? "(not set)"}");
return true;
}
@ -1296,11 +1308,11 @@ internal sealed class MetaManager
foreach (string name in System.Linq.Enumerable.OrderBy(VtOptionMap.Keys, k => k, StringComparer.OrdinalIgnoreCase))
{
string item = $"{name}={GetVtOption(name) ?? "?"}";
if (line.Length + item.Length > 180) { _host.WriteToChat("[RynthAi] " + line, 1); line.Clear(); }
if (line.Length + item.Length > 180) { Reply.Info("[RynthAi] " + line); line.Clear(); }
if (line.Length > 0) line.Append(", ");
line.Append(item);
}
if (line.Length > 0) _host.WriteToChat("[RynthAi] " + line, 1);
if (line.Length > 0) Reply.Info("[RynthAi] " + line);
return true;
}
@ -1332,8 +1344,8 @@ internal sealed class MetaManager
// /vt tapjump — a quick jump with no charge.
if (sub == "tapjump")
{
if (!(_host.HasTapJump && _host.TapJump()))
_host.WriteToChat("[RynthAi] /vt tapjump: the engine's jump isn't available.", 1);
if (_host.HasTapJump && _host.TapJump()) Reply.Ok("[RynthAi] Tap jump.");
else Reply.Fail("[RynthAi] /vt tapjump: the engine's jump isn't available.");
return true;
}
@ -1364,7 +1376,10 @@ internal sealed class MetaManager
string name = string.Join(" ", parts, 3, parts.Length - 3);
// The macro was started again: the route still running keeps its place.
if (_replaying && parts[2].Equals("load", StringComparison.OrdinalIgnoreCase) && KeepRunningNavFile(name))
{
Reply.Ok($"[RynthAi] Nav '{name}' is the route already running; it keeps its place.");
return true;
}
_raCommandHandler?.Invoke($"/ra nav {parts[2].ToLowerInvariant()} {name}");
return true;
}
@ -1389,11 +1404,11 @@ internal sealed class MetaManager
}
if (!File.Exists(path))
{
_host.WriteToChat($"[RynthAi] Loot profile not found: {name}", 1);
Reply.Fail($"[RynthAi] Loot profile not found: {name}");
return true;
}
_settings.CurrentLootPath = path;
_host.WriteToChat($"[RynthAi] Loot profile set: {Path.GetFileName(path)}", 1);
Reply.Ok($"[RynthAi] Loot profile set: {Path.GetFileName(path)}");
return true;
}
@ -1403,7 +1418,7 @@ internal sealed class MetaManager
string state = string.Join(" ", parts, 2, parts.Length - 2);
_settings.CurrentState = state;
_settings.ForceStateReset = true;
_host.WriteToChat($"[RynthAi] Meta state set: {state}", 1);
Reply.Ok($"[RynthAi] Meta state set: {state}");
return true;
}
@ -1414,13 +1429,19 @@ internal sealed class MetaManager
if (parts.Length >= 4 && (parts[2].Equals("loadchar", StringComparison.OrdinalIgnoreCase)
|| parts[2].Equals("savechar", StringComparison.OrdinalIgnoreCase)))
_raCommandHandler?.Invoke($"/ra settings {parts[2].ToLowerInvariant()} {string.Join(" ", parts, 3, parts.Length - 3)}");
else
Reply.Ignored("[RynthAi] Usage: /vt settings loadchar|savechar <name> (other /vt settings verbs are VTank's own; ignored).");
return true;
}
// /vt <option> <value> — an option written as a verb (DerethExploration: "/vt navclosestoprange
// 0.005"): the same as /vt opt set, for the VTank options RynthAi maps.
if (parts.Length == 3 && (VtOptionMap.ContainsKey(sub) || IsSpecialVtOption(sub)))
return TrySetVtOption(sub, parts[2]);
{
bool set = TrySetVtOption(sub, parts[2]);
ReplyVtOption(parts[1], parts[2]);
return set;
}
// /vt <verb> aliases → existing /ra handlers (Phase 1.3 VTank-meta migration).
// Re-dispatch through the /ra path (_raCommandHandler → HandleRaCommand).
@ -1451,6 +1472,7 @@ internal sealed class MetaManager
_deleteMonsterLogged = true;
RynthLog.Write(LogCat.Meta, "[Meta] /vt deletemonster accepted and ignored (no RynthAi equivalent).");
}
Reply.Ignored("[RynthAi] /vt deletemonster has no RynthAi equivalent; accepted and ignored.");
return true;
}
@ -1464,15 +1486,16 @@ internal sealed class MetaManager
int n = route.Points.Count;
route.Points.Reverse();
_settings.ActiveNavIndex = Math.Clamp(n - 1 - _settings.ActiveNavIndex, 0, n - 1);
_host.WriteToChat($"[RynthAi] Route reversed ({n} pts).", 1);
Reply.Ok($"[RynthAi] Route reversed ({n} pts).");
}
else Reply.Fail("[RynthAi] /vt reverseroute: no route is loaded.");
return true;
}
// /vt echo <text> — local chat echo (no server send).
if (sub == "echo" && parts.Length >= 3)
{
_host.WriteToChat(string.Join(" ", parts, 2, parts.Length - 2), 1);
Reply.Info(string.Join(" ", parts, 2, parts.Length - 2));
return true;
}
@ -1486,6 +1509,49 @@ internal sealed class MetaManager
return false;
}
/// <summary>
/// After a /vt opt set (or "/vt &lt;option&gt; &lt;value&gt;"): the option's value now, and whether RynthAi
/// has a setting by that name (otherwise it is only kept for metas to read back).
/// </summary>
private void ReplyVtOption(string vtName, string asked)
{
bool known = IsSpecialVtOption(vtName) || VtOptionMap.ContainsKey(vtName)
|| Expressions.BuildSettingsMapPublic().ContainsKey(vtName);
string now = GetVtOption(vtName) ?? "(not set)";
// A switch asked for as true/false/on/off reads back as 1/0: shown the way it was asked.
if (asked.ToLowerInvariant() is "true" or "false" or "on" or "off" && now is "1" or "0" or "true" or "false")
now = now is "1" or "true" ? "True" : "False";
Reply.Ok($"[RynthAi] {vtName} = {now}"
+ (known ? "" : " (no RynthAi setting by that name: kept only as an option metas can read)"));
}
/// <summary>The /vt verbs RynthAi takes, for the usage line.</summary>
internal const string VtVerbList = "opt set|get|list, <option> <value>, start, stop, e, jump, tapjump, equipitemsfor, "
+ "meta load, nav load|save, loot load, setmetastate, settings loadchar|savechar, setattackbar, forcebuff, "
+ "cancelforcebuff, cancelbuff, addnavpt, mexec, clearbusy, testitem, propertydump, reverseroute, echo";
/// <summary>The usage line for a /vt line RynthAi didn't take (an unknown verb or the wrong arguments).</summary>
internal static string VtUsageFor(string line)
{
string[] w = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
string verb = w.Length > 1 ? w[1].ToLowerInvariant() : "";
string? usage = verb switch
{
"opt" => "/vt opt set <option> <value> | /vt opt get <option> | /vt opt list",
"meta" => "/vt meta load <name>",
"nav" => "/vt nav load <name> | /vt nav save <name>",
"loot" or "lootprofile" or "looting" => "/vt loot load <profile>",
"setmetastate" => "/vt setmetastate <state>",
"equipitemsfor" => "/vt equipitemsfor <monster name>",
"setattackbar" => "/vt setattackbar <0 to 1>",
"echo" => "/vt echo <text>",
_ => null,
};
return usage != null
? "[RynthAi] Usage: " + usage
: $"[RynthAi] Unknown /vt command{(verb.Length > 0 ? $" '{verb}'" : "")}. RynthAi takes: {VtVerbList}.";
}
/// <summary>The RynthAi setting a VTank option name maps to (EnableNav → EnableNavigation).</summary>
internal static bool TryMapVtOption(string vtName, out string raName)
{

File diff suppressed because it is too large Load diff

View file

@ -69,7 +69,7 @@ public sealed partial class RynthAiPlugin
PrintSelectedItemInfo();
return;
}
if (s == null) { ChatLine("[RynthAi] Settings not ready (log in first)."); return; }
if (s == null) { ReplyFail("[RynthAi] Settings not ready (log in first)."); return; }
switch (sub)
{
@ -83,40 +83,40 @@ public sealed partial class RynthAiPlugin
case "gui":
case "window":
s.ShowWindow = !s.ShowWindow;
ChatLine($"[RynthAi] Item info window {(s.ShowWindow ? "opened" : "closed")}.");
ReplyOk($"[RynthAi] Item info window {(s.ShowWindow ? "opened" : "closed")}.");
return;
case "value":
if (ParseOnOff(arg3) is bool v) s.ShowValueAndBurden = v;
ChatLine($"[RynthAi] Item info value/burden: {OnOff(s.ShowValueAndBurden)}");
ReplyOk($"[RynthAi] Item info value/burden: {OnOff(s.ShowValueAndBurden)}");
return;
case "verbose":
if (ParseOnOff(arg3) is bool all)
s.SpellMode = all ? MagItemInfoSettings.SpellModeAll : MagItemInfoSettings.SpellModeMag;
ChatLine($"[RynthAi] Item info all spells: {OnOff(s.SpellMode == MagItemInfoSettings.SpellModeAll)}");
ReplyOk($"[RynthAi] Item info all spells: {OnOff(s.SpellMode == MagItemInfoSettings.SpellModeAll)}");
return;
case "field":
if (!MagItemInfoCatalog.TryFindField(arg3, out MagItemInfoField field))
{
ChatLine($"[RynthAi] Unknown field '{arg3}'. /ra iteminfo fields lists them.");
ReplyFail($"[RynthAi] Unknown field '{arg3}'. /ra iteminfo fields lists them.");
return;
}
if (ParseOnOff(arg4) is bool fieldOn) s.SetHidden(field, !fieldOn);
ChatLine($"[RynthAi] Item info field {field}: {OnOff(!s.IsHidden(field))}");
ReplyOk($"[RynthAi] Item info field {field}: {OnOff(!s.IsHidden(field))}");
return;
case "rating":
int r = MagItemInfoCatalog.FindRating(arg3);
if (r < 0)
{
ChatLine($"[RynthAi] Unknown rating '{arg3}'. /ra iteminfo fields lists them.");
ReplyFail($"[RynthAi] Unknown rating '{arg3}'. /ra iteminfo fields lists them.");
return;
}
if (ParseOnOff(arg4) is bool ratingOn) s.SetRatingHidden(r, !ratingOn);
var rating = MagItemInfoCatalog.Ratings[r];
ChatLine($"[RynthAi] Item info rating {rating.Tag} ({rating.Name}): {OnOff(!s.IsRatingHidden(r))}");
ReplyOk($"[RynthAi] Item info rating {rating.Tag} ({rating.Name}): {OnOff(!s.IsRatingHidden(r))}");
return;
case "fields":
@ -131,10 +131,10 @@ public sealed partial class RynthAiPlugin
case "off": case "none": s.ClickTrigger = MagItemInfoSettings.ClickOff; break;
case "": break;
default:
ChatLine("[RynthAi] Usage: /ra iteminfo click left|right|off");
ReplyFail("[RynthAi] Usage: /ra iteminfo click left|right|off");
return;
}
ChatLine($"[RynthAi] Item info on click: {MagItemInfoCatalog.ClickTriggers[s.ClickTrigger]}");
ReplyOk($"[RynthAi] Item info on click: {MagItemInfoCatalog.ClickTriggers[s.ClickTrigger]}");
return;
case "layout":
@ -144,22 +144,22 @@ public sealed partial class RynthAiPlugin
case "line": case "mag": case "one": s.Layout = MagItemInfoSettings.LayoutOneLine; break;
case "": break;
default:
ChatLine("[RynthAi] Usage: /ra iteminfo layout pet|line");
ReplyFail("[RynthAi] Usage: /ra iteminfo layout pet|line");
return;
}
ChatLine($"[RynthAi] Item info layout: {MagItemInfoCatalog.Layouts[s.Layout]}");
ReplyOk($"[RynthAi] Item info layout: {MagItemInfoCatalog.Layouts[s.Layout]}");
return;
case "reset":
s.ResetToDefaults();
ChatLine("[RynthAi] Item info settings reset to defaults.");
ReplyOk("[RynthAi] Item info settings reset to defaults.");
return;
}
if (ParseOnOff(sub) is bool onSelect)
{
s.OnSelect = onSelect;
ChatLine($"[RynthAi] Item info on select: {OnOff(onSelect)}");
ReplyOk($"[RynthAi] Item info on select: {OnOff(onSelect)}");
return;
}
if (sub is not ("help" or "?"))
@ -168,9 +168,9 @@ public sealed partial class RynthAiPlugin
string name = string.Join(" ", parts, 2, parts.Length - 2).Trim();
uint found = FindInventoryItemByName(name);
if (found != 0) { QueueItemInfo(unchecked((int)found), requestId: true); return; }
ChatLine($"[RynthAi] Item info: no \"{name}\" in your inventory.");
ReplyFail($"[RynthAi] Item info: no \"{name}\" in your inventory.");
}
ChatLine("[RynthAi] Usage: /ra iteminfo [<item name>|me|on|off|settings|fields|field <name> on|off|rating <tag> on|off|value on|off|verbose on|off|click left|right|off|layout pet|line|reset]");
ReplyFail("[RynthAi] Usage: /ra iteminfo [<item name>|me|on|off|settings|fields|field <name> on|off|rating <tag> on|off|value on|off|verbose on|off|click left|right|off|layout pet|line|reset]");
}
/// <summary>
@ -244,9 +244,9 @@ public sealed partial class RynthAiPlugin
/// <summary>/ra iteminfo and the window's "Print to chat" button.</summary>
private void PrintSelectedItemInfo()
{
if (!Host.HasGetSelectedItemId) { ChatLine("[RynthAi] Host does not expose the selected item."); return; }
if (!Host.HasGetSelectedItemId) { ReplyFail("[RynthAi] Host does not expose the selected item."); return; }
uint selected = Host.GetSelectedItemId();
if (selected == 0) { ChatLine("[RynthAi] No item selected. Click an item first."); return; }
if (selected == 0) { ReplyFail("[RynthAi] No item selected. Click an item first."); return; }
if (IsSelf(selected)) { QueueSelfRatings(auto: false); return; }
QueueItemInfo(unchecked((int)selected), requestId: true);
}
@ -276,6 +276,7 @@ public sealed partial class RynthAiPlugin
}
if (requestId && Host.HasRequestId) Host.RequestId(uid);
ItemInfoLog($"0x{uid:X8}: waiting for ID data (requested={requestId && Host.HasRequestId})");
Reply.Answered(); // a command's item info follows when the ID data arrives
_itemInfoPendingId = itemId;
_itemInfoPendingSince = Environment.TickCount64;
}

View file

@ -36,7 +36,8 @@ public sealed partial class RynthAiPlugin
private readonly ConcurrentQueue<Action> _dashActions = new();
private readonly DateTime _dashLoadedUtc = DateTime.UtcNow;
private long _dashDrawnMs = long.MinValue / 2; // render thread writes, tick reads
private long _nextDashVitalsMs, _nextDashClassicMs, _dashSaveAtMs;
private long _nextDashVitalsMs, _nextDashClassicMs, _dashSaveAtMs, _nextDashSortMs;
private volatile int _dashSort = -1; // RynthSort's auto-sort (tick writes, render reads)
private volatile bool _classicLook; // the engine's look is Classic (its file)
private long _classicAskedMs; // "Classic look" clicked: the window steps aside now
private volatile FightTarget? _dashFight; // tick writes, render reads
@ -104,6 +105,11 @@ public sealed partial class RynthAiPlugin
_dashboard?.RefreshDashboardVitals();
_dashFight = ReadFightTarget(_dashFight);
}
if (shown && now >= _nextDashSortMs)
{
_nextDashSortMs = now + 500;
_dashSort = ReadAutoSort();
}
if (now >= _nextDashClassicMs)
{
_nextDashClassicMs = now + 2000;
@ -167,6 +173,36 @@ public sealed partial class RynthAiPlugin
QueueDashCommand("/rc dashboard classic");
}
/// <summary>RynthSort's auto-sort for the dashboard's key: -1 not loaded / not logged in / too old, 0 off, 1 on.</summary>
internal int DashAutoSort => _dashSort;
/// <summary>
/// RynthSort's auto-sort state, through the engine's JSON broker (RynthSort's
/// RynthPluginGetAutoSortJson, {"auto":-1|0|1}); -1 when RynthSort isn't loaded or predates
/// the export. Plugin tick.
/// </summary>
private int ReadAutoSort()
{
if (!Host.HasGetPluginExportJson) return -1;
string? json = Host.GetPluginExportJson("RynthSort", "RynthPluginGetAutoSortJson");
if (json == null) return -1;
return json.Contains("\"auto\":1", StringComparison.Ordinal) ? 1
: json.Contains("\"auto\":0", StringComparison.Ordinal) ? 0 : -1;
}
/// <summary>The dashboard's auto-sort key: RynthSort on or off, quietly (the key shows it). Plugin tick.</summary>
internal void SetDashAutoSort(bool on)
{
if (!SendSortCommand(on ? "on quiet" : "off quiet")) return;
// Lit at once; RynthSort runs the command on its own tick, so the next read waits a little.
_dashSort = on ? 1 : 0;
_nextDashSortMs = Environment.TickCount64 + 1000;
}
/// <summary>An /rsort command (without "/rsort") to RynthSort; false when it isn't loaded. Plugin tick.</summary>
internal bool SendSortCommand(string arg) =>
Host.HasSendPluginCommand && Host.SendPluginCommand("RynthSort", "rsort", arg);
internal void QueueDashAction(Action action)
{
if (_dashActions.Count < 64) _dashActions.Enqueue(action);
@ -215,6 +251,9 @@ internal sealed class DashboardBridge : IDashboardHost
public void AdjustOpacity(float delta) => Queue(() => { _p.DashboardRenderer?.AdjustOpacity(delta); _p.ScheduleDashSave(); });
public void ToggleLock() => Queue(() => { _p.DashboardRenderer?.TogglePanelLock(); _p.ScheduleDashSave(); });
public void SelectProfile(int kind, int index) => Queue(() => _p.DashboardRenderer?.SelectProfileAtIndex(kind, index));
public int AutoSort => _p.DashAutoSort;
public void SetAutoSort(bool on) => Queue(() => _p.SetDashAutoSort(on));
public void ToggleSortWindow() => Queue(() => _p.SendSortCommand(string.Empty));
public void StartPatrol() => Queue(_p.HandleDungeonNavPatrol);
public void ToggleSpells() => _p.EnqueueRemoteCommand("spells", "toggle");
public void UseClassicLook() => _p.UseClassicLook();

View file

@ -496,22 +496,22 @@ public sealed partial class RynthAiPlugin
/// <summary>"/ra huds|itemhud|remote|miniremote [show|hide|toggle]".</summary>
private void HandleHudCommand(string which, string mode)
{
if (_huds == null) { ChatLine("[RynthAi] HUDs not ready (log in first)."); return; }
if (_huds == null) { ReplyFail("[RynthAi] HUDs not ready (log in first)."); return; }
ChatLine("[RynthAi] " + _huds.HandleCommand(which, mode));
}
/// <summary>"/ra itemhud add &lt;name&gt;" and the inventory panel's "Add to item count HUD". Pump thread.</summary>
private void HandleItemHudAdd(string name)
{
if (_huds == null) { ChatLine("[RynthAi] HUDs not ready (log in first)."); return; }
if (string.IsNullOrWhiteSpace(name)) { ChatLine("[RynthAi] Usage: /ra itemhud add <item name>"); return; }
if (_huds == null) { ReplyFail("[RynthAi] HUDs not ready (log in first)."); return; }
if (string.IsNullOrWhiteSpace(name)) { ReplyFail("[RynthAi] Usage: /ra itemhud add <item name>"); return; }
ChatLine("[RynthAi] " + _huds.AddToItemHudAndShow(name));
}
/// <summary>/ra translate ... — forwards to the chat translator.</summary>
private void HandleTranslateCommand(string[] parts)
{
if (_translator == null) { ChatLine("[RynthAi] Chat translator not ready (log in first)."); return; }
if (_translator == null) { ReplyFail("[RynthAi] Chat translator not ready (log in first)."); return; }
_translator.HandleCommand(parts.Length > 2 ? parts[2..] : Array.Empty<string>(), ChatLine);
}
@ -529,8 +529,10 @@ public sealed partial class RynthAiPlugin
string arg = parts.Length > 2 ? parts[2] : "status";
bool? state = arg.Equals("toggle", StringComparison.OrdinalIgnoreCase) ? !RynthLog.DebugToChat : ParseOnOff(arg);
if (state.HasValue) RynthLog.DebugToChat = state.Value;
ChatLine($"[RynthAi] Debug-to-chat is {(RynthLog.DebugToChat ? "ON" : "off")}."
+ (RynthLog.DebugToChat && RynthLog.TracedCategories().Count == 0 ? " (no categories traced — see /ra trace list)" : ""));
string line = $"[RynthAi] Debug-to-chat is {(RynthLog.DebugToChat ? "ON" : "off")}."
+ (RynthLog.DebugToChat && RynthLog.TracedCategories().Count == 0 ? " (no categories traced — see /ra trace list)" : "");
if (state.HasValue) ReplyOk(line); // a change
else ChatLine(line); // the status asked for
}
/// <summary>"/ra trace &lt;cat|all|ilt|list&gt; [on|off|status]".</summary>
@ -560,13 +562,13 @@ public sealed partial class RynthAiPlugin
{
if (!state.HasValue) { foreach (string l in RynthLog.StatusLines()) ChatLine(l); return; }
int n = RynthLog.SetTracingByPrefix(string.Empty, state.Value);
ChatLine($"[RynthAi] Tracing {(state.Value ? "enabled" : "disabled")} for {n} categories.");
ReplyOk($"[RynthAi] Tracing {(state.Value ? "enabled" : "disabled")} for {n} categories.");
return;
}
if (!RynthLog.TryParseCategory(target, out LogCat cat))
{
ChatLine($"[RynthAi] Unknown trace category '{target}'. Use /ra trace list.");
ReplyFail($"[RynthAi] Unknown trace category '{target}'. Use /ra trace list.");
return;
}
@ -578,7 +580,7 @@ public sealed partial class RynthAiPlugin
bool enable = state ?? !RynthLog.IsTracing(cat);
RynthLog.SetTracing(cat, enable);
ChatLine($"[RynthAi] Trace {cat}: {(enable ? "ON" : "off")} → {RynthLog.TraceDirectory}");
ReplyOk($"[RynthAi] Trace {cat}: {(enable ? "ON" : "off")} → {RynthLog.TraceDirectory}");
}
/// <summary>"/ra logs [open|prune|flush|file on|off]".</summary>
@ -593,20 +595,22 @@ public sealed partial class RynthAiPlugin
RynthLog.Flush();
System.IO.Directory.CreateDirectory(RynthLog.Directory);
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo("explorer.exe", $"\"{RynthLog.Directory}\"") { UseShellExecute = true });
ReplyOk($"[RynthAi] Opened {RynthLog.Directory}.");
}
catch (Exception ex) { RynthLog.Exception(LogCat.Commands, ex, "logs open"); ChatLine($"[RynthAi] Could not open {RynthLog.Directory}: {ex.Message}"); }
catch (Exception ex) { RynthLog.Exception(LogCat.Commands, ex, "logs open"); ReplyFail($"[RynthAi] Could not open {RynthLog.Directory}: {ex.Message}"); }
break;
case "prune":
ChatLine($"[RynthAi] Pruned {RynthLog.Prune()} old diagnostics file(s).");
ReplyOk($"[RynthAi] Pruned {RynthLog.Prune()} old diagnostics file(s).");
break;
case "flush":
RynthLog.Flush();
ChatLine("[RynthAi] Diagnostics flushed to disk.");
ReplyOk("[RynthAi] Diagnostics flushed to disk.");
break;
case "file":
bool? state = ParseOnOff(parts.Length > 3 ? parts[3] : null);
if (state.HasValue) RynthLog.FileLogAll = state.Value;
ChatLine($"[RynthAi] Daily RynthAi log file is {(RynthLog.FileLogAll ? "ON" : "off")}.");
string fileLine = $"[RynthAi] Daily RynthAi log file is {(RynthLog.FileLogAll ? "ON" : "off")}.";
if (state.HasValue) ReplyOk(fileLine); else ChatLine(fileLine);
break;
default:
foreach (string l in RynthLog.StatusLines()) ChatLine(l);
@ -617,21 +621,21 @@ public sealed partial class RynthAiPlugin
/// <summary>/ra navrec [on|off] — toggles route recording.</summary>
private void HandleNavRecordCommand(string[] parts)
{
if (_dashboard == null) return;
if (_dashboard == null) { ReplyFail("[RynthAi] Settings not ready (log in first)."); return; }
var s = _dashboard.Settings;
string arg = parts.Length > 2 ? parts[2].ToLowerInvariant() : "";
s.IsRecordingNav = arg switch { "on" => true, "off" => false, _ => !s.IsRecordingNav };
ChatLine($"[RynthAi] Nav recording {(s.IsRecordingNav ? "ON — walk the route; portals are captured" : "OFF")}.");
ReplyOk($"[RynthAi] Nav recording {(s.IsRecordingNav ? "ON — walk the route; portals are captured" : "OFF")}.");
}
/// <summary>/ra navhud [on|off] — shows or hides the navigation HUD window.</summary>
private void HandleNavHudCommand(string[] parts)
{
if (_dashboard == null) return;
if (_dashboard == null) { ReplyFail("[RynthAi] Settings not ready (log in first)."); return; }
var o = _dashboard.Settings.NavOverlay;
string arg = parts.Length > 2 ? parts[2].ToLowerInvariant() : "";
o.ShowHud = arg switch { "on" => true, "off" => false, _ => !o.ShowHud };
ChatLine($"[RynthAi] Nav HUD {(o.ShowHud ? "shown" : "hidden")}.");
ReplyOk($"[RynthAi] Nav HUD {(o.ShowHud ? "shown" : "hidden")}.");
}
/// <summary>/ra navtrail [on|off|toggle|clear] — breadcrumb tracking switch, wipe, or a status report.</summary>
@ -641,16 +645,16 @@ public sealed partial class RynthAiPlugin
if (arg == "clear")
{
_navBreadcrumbs?.RequestClear();
ChatLine("[RynthAi] Breadcrumb trail cleared.");
ReplyOk("[RynthAi] Breadcrumb trail cleared.");
return;
}
if (arg is "on" or "off" or "toggle")
{
if (_dashboard == null) return;
if (_dashboard == null) { ReplyFail("[RynthAi] Settings not ready (log in first)."); return; }
var o = _dashboard.Settings.NavOverlay;
o.TrackBreadcrumbs = arg switch { "on" => true, "off" => false, _ => !o.TrackBreadcrumbs };
_dashboard.SaveSettings();
ChatLine($"[RynthAi] Breadcrumb tracking {(o.TrackBreadcrumbs ? "on" : "off")}.");
ReplyOk($"[RynthAi] Breadcrumb tracking {(o.TrackBreadcrumbs ? "on" : "off")}.");
return;
}
bool tracking = _dashboard?.Settings.NavOverlay.TrackBreadcrumbs ?? false;
@ -662,11 +666,11 @@ public sealed partial class RynthAiPlugin
/// <summary>/ra navoverlay [on|off] — route overlay (rings / lines, waypoint labels, guide line); no argument toggles.</summary>
private void HandleNavOverlayCommand(string[] parts)
{
if (_dashboard == null) return;
if (_dashboard == null) { ReplyFail("[RynthAi] Settings not ready (log in first)."); return; }
var o = _dashboard.Settings.NavOverlay;
string arg = parts.Length > 2 ? parts[2].ToLowerInvariant() : "";
o.ShowRouteMarkers = arg switch { "on" => true, "off" => false, _ => !o.ShowRouteMarkers };
_dashboard.SaveSettings();
ChatLine($"[RynthAi] Route overlay {(o.ShowRouteMarkers ? "on" : "off")}.");
ReplyOk($"[RynthAi] Route overlay {(o.ShowRouteMarkers ? "on" : "off")}.");
}
}

View file

@ -11,7 +11,10 @@ public sealed partial class RynthAiPlugin
{
string rest = parts.Length > 2 ? string.Join(" ", parts, 2, parts.Length - 2) : "";
if (Host.HasSendPluginCommand && Host.SendPluginCommand("RynthLua", "lua", rest))
{
Reply.Answered(); // RynthLua answers its own /lua verbs
return;
ChatLine("[RynthAi] Lua scripting is now the RynthLua plugin. Add RynthCore.Plugin.RynthLua.dll in the launcher's Plugins tab, then use /lua (or /ra lua).");
}
ReplyFail("[RynthAi] Lua scripting is now the RynthLua plugin. Add RynthCore.Plugin.RynthLua.dll in the launcher's Plugins tab, then use /lua (or /ra lua).");
}
}

View file

@ -23,7 +23,8 @@ public sealed partial class RynthAiPlugin
// Chat-bar events and /ra metamgr may arrive off the pump: flags and a queue, drained on it.
private int _mmTypedQuery; // a "/myquests" passed through the chat bar (maybe our own echo)
private int _mmShownQuery; // RynthAi's quest refresh sent /myquests: show that reply
private readonly ConcurrentQueue<string[]> _metaMgrCommands = new();
// FromScript: a meta (or script) sent the line, so its answer is quiet when it works (CommandReply.cs).
private readonly ConcurrentQueue<(string[] Parts, bool FromScript)> _metaMgrCommands = new();
/// <summary>OnLoginComplete: hook the dashboard (panel snapshot and ops) and the quest refresh.</summary>
private void WireMetaSchedule()
@ -104,9 +105,9 @@ public sealed partial class RynthAiPlugin
}
if (folder.Length == 0) return; // no character settings yet: nothing to save to
while (_metaMgrCommands.TryDequeue(out var parts))
while (_metaMgrCommands.TryDequeue(out var queued))
{
try { HandleMetaMgrCommand(parts); }
try { Reply.RunQueued(queued.FromScript, () => HandleMetaMgrCommand(queued.Parts)); }
catch (Exception ex) { Host.Log($"[RynthAi] /ra metamgr failed: {ex.Message}"); }
}
@ -184,7 +185,7 @@ public sealed partial class RynthAiPlugin
// /ra metamgr (queued to the pump by DispatchRaCommand)
// =====================================================================
private void QueueMetaMgrCommand(string[] parts) => _metaMgrCommands.Enqueue(parts);
private void QueueMetaMgrCommand(string[] parts) => _metaMgrCommands.Enqueue((parts, Reply.FromScript));
private void HandleMetaMgrCommand(string[] parts)
{
@ -196,7 +197,7 @@ public sealed partial class RynthAiPlugin
case "on":
case "off":
_metaScheduler.SetEnabled(sub == "on");
ChatLine(sub == "on"
ReplyOk(sub == "on"
? $"[RynthAi] Meta Manager ON ({_metaScheduler.Config.Rules.Count} rule(s))."
: "[RynthAi] Meta Manager OFF.");
break;
@ -206,9 +207,9 @@ public sealed partial class RynthAiPlugin
if (int.TryParse(parts[3], NumberStyles.Integer, CultureInfo.InvariantCulture, out int m))
{
_metaScheduler.SetPollMinutes(m);
ChatLine($"[RynthAi] Meta Manager: /myquests every {_metaScheduler.Config.PollMinutes} min.");
ReplyOk($"[RynthAi] Meta Manager: /myquests every {_metaScheduler.Config.PollMinutes} min.");
}
else ChatLine("[RynthAi] Usage: /ra metamgr poll [minutes]");
else ReplyFail("[RynthAi] Usage: /ra metamgr poll [minutes]");
break;
}
_metaScheduler.RequestPoll();
@ -220,17 +221,17 @@ public sealed partial class RynthAiPlugin
case "stop":
case "reset":
{
if (parts.Length < 4) { ChatLine($"[RynthAi] Usage: /ra metamgr {sub} <rule #>{(sub == "start" ? " [minutes]" : sub == "reset" ? "|all" : "")}"); break; }
if (parts.Length < 4) { ReplyFail($"[RynthAi] Usage: /ra metamgr {sub} <rule #>{(sub == "start" ? " [minutes]" : sub == "reset" ? "|all" : "")}"); break; }
if (sub == "reset" && parts[3].Equals("all", StringComparison.OrdinalIgnoreCase))
{
for (int i = 0; i < _metaScheduler.Config.Rules.Count; i++) _metaScheduler.ResetRule(i);
ChatLine("[RynthAi] Meta Manager: every rule re-armed.");
ReplyOk("[RynthAi] Meta Manager: every rule re-armed.");
break;
}
if (!int.TryParse(parts[3], NumberStyles.Integer, CultureInfo.InvariantCulture, out int n)
|| n < 1 || n > _metaScheduler.Config.Rules.Count)
{
ChatLine($"[RynthAi] Meta Manager: no rule #{parts[3]} (there are {_metaScheduler.Config.Rules.Count}).");
ReplyFail($"[RynthAi] Meta Manager: no rule #{parts[3]} (there are {_metaScheduler.Config.Rules.Count}).");
break;
}
int idx = n - 1;
@ -238,18 +239,18 @@ public sealed partial class RynthAiPlugin
{
double? mins = null;
if (parts.Length >= 5 && double.TryParse(parts[4], NumberStyles.Float, CultureInfo.InvariantCulture, out double mm) && mm > 0) mins = mm;
ChatLine(_metaScheduler.StartCountdown(idx, mins, now)
ReplyOk(_metaScheduler.StartCountdown(idx, mins, now)
? $"[RynthAi] Meta Manager: rule #{n} countdown started ({(mins ?? _metaScheduler.Config.Rules[idx].Minutes).ToString("0.##", CultureInfo.InvariantCulture)} min)."
: $"[RynthAi] Meta Manager: rule #{n} is not a countdown.");
}
else if (sub == "stop")
ChatLine(_metaScheduler.StopCountdown(idx)
ReplyOk(_metaScheduler.StopCountdown(idx)
? $"[RynthAi] Meta Manager: rule #{n} countdown stopped."
: $"[RynthAi] Meta Manager: rule #{n} has no countdown running.");
else
{
_metaScheduler.ResetRule(idx);
ChatLine($"[RynthAi] Meta Manager: rule #{n} re-armed.");
ReplyOk($"[RynthAi] Meta Manager: rule #{n} re-armed.");
}
break;
}
@ -257,7 +258,7 @@ public sealed partial class RynthAiPlugin
foreach (string line in _metaScheduler.StatusLines(now, meta)) ChatLine("[RynthAi] " + line);
break;
default:
ChatLine("[RynthAi] Usage: /ra metamgr on|off|status|poll [minutes]|start <#> [min]|stop <#>|reset <#|all>");
ReplyFail("[RynthAi] Usage: /ra metamgr on|off|status|poll [minutes]|start <#> [min]|stop <#>|reset <#|all>");
break;
}
SaveMetaScheduleIfDirty();

View file

@ -454,13 +454,14 @@ public sealed partial class RynthAiPlugin
string sub = parts.Length >= 3 ? parts[2].Trim().ToLowerInvariant() : string.Empty;
if (sub == "stop")
{
if (_ownCorpseTravel == OwnCorpseTravelState.None) ChatLine("[RynthAi] Own corpse: not travelling.");
if (_ownCorpseTravel == OwnCorpseTravelState.None) ReplyOk("[RynthAi] Own corpse: not travelling.");
else EndOwnCorpseTravel("stopped by /ra owncorpse stop");
return;
}
if (sub == "go")
{
StartOwnCorpseTravel(manual: true);
if (s == null) { ReplyFail("[RynthAi] Own corpse: settings not ready (log in first)."); return; }
StartOwnCorpseTravel(manual: true); // says where it goes, or why not
return;
}

View file

@ -47,7 +47,7 @@ public sealed partial class RynthAiPlugin
uint me = Host.GetPlayerId();
if (me == 0)
{
ChatLine("[RynthAi] Not logged in.");
ReplyFail("[RynthAi] Not logged in.");
return;
}
uint target = me;

View file

@ -56,7 +56,7 @@ public sealed partial class RynthAiPlugin
private void HandleSpellsCommand(string mode)
{
var settings = _dashboard?.Settings;
if (settings == null) { ChatLine("[RynthAi] Settings not ready (log in first)."); return; }
if (settings == null) { ReplyFail("[RynthAi] Settings not ready (log in first)."); return; }
EnsureSpellsUi();
settings.ShowSpellsWindow = mode.ToLowerInvariant() switch
@ -65,7 +65,7 @@ public sealed partial class RynthAiPlugin
"hide" or "close" or "off" => false,
_ => !settings.ShowSpellsWindow,
};
ChatLine($"[RynthAi] Spells window {(settings.ShowSpellsWindow ? "opened" : "closed")}.");
ReplyOk($"[RynthAi] Spells window {(settings.ShowSpellsWindow ? "opened" : "closed")}.");
}
/// <summary>
@ -75,7 +75,7 @@ public sealed partial class RynthAiPlugin
private void HandleBuffProfileCommand(string[] parts)
{
var dash = _dashboard;
if (dash == null) { ChatLine("[RynthAi] Settings not ready (log in first)."); return; }
if (dash == null) { ReplyFail("[RynthAi] Settings not ready (log in first)."); return; }
string arg = parts.Length >= 3 ? string.Join(" ", parts, 2, parts.Length - 2).Trim() : string.Empty;
if (arg.Length == 0 || arg.Equals("list", StringComparison.OrdinalIgnoreCase))
@ -96,6 +96,7 @@ public sealed partial class RynthAiPlugin
|| arg.Equals(LegacyDashboardRenderer.BuiltInBuffProfileLabel, StringComparison.OrdinalIgnoreCase))
{
dash.SetActiveBuffProfile(string.Empty);
Reply.Answered();
return; // BuffManager posts the "built-in list" chat line
}
@ -103,8 +104,9 @@ public sealed partial class RynthAiPlugin
{
if (!Path.GetFileNameWithoutExtension(file).Equals(arg, StringComparison.OrdinalIgnoreCase)) continue;
dash.SetActiveBuffProfile(Path.Combine(BuffProfileStore.Folder, file));
Reply.Answered();
return; // BuffManager posts the "profile 'X'" chat line once it loads
}
ChatLine($"[RynthAi] No buff profile named '{arg}'. /ra buffprofile list shows them.");
ReplyFail($"[RynthAi] No buff profile named '{arg}'. /ra buffprofile list shows them.");
}
}

View file

@ -36,7 +36,9 @@ public sealed partial class RynthAiPlugin
string args = parts.Length > argsFrom ? string.Join(" ", parts, argsFrom, parts.Length - argsFrom) : "";
string command = "/rc videopatch" + (args.Length > 0 ? " " + args : "");
if (!Host.HasInvokeChatParser || !Host.InvokeChatParser(command))
ChatLine("[RynthAi] The video patch is RynthCore's: type " + command + " (this engine can't run it for RynthAi).");
ReplyFail("[RynthAi] The video patch is RynthCore's: type " + command + " (this engine can't run it for RynthAi).");
else
Reply.Answered(); // the engine's /rc videopatch answers
}
/// <summary>The VTank-style /ra commands; false when <paramref name="cmd"/> isn't one of them.</summary>
@ -70,7 +72,7 @@ public sealed partial class RynthAiPlugin
case "lootprio": HandlePriorityCommand(parts, nav: false, loot: true); return true;
case "navlootprio": HandlePriorityCommand(parts, nav: true, loot: true); return true;
case "lootthis":
case "lootthiscont": RequestLootThisContainer(); return true;
case "lootthiscont": RequestLootThisContainer(); Reply.Answered(); return true; // the loot tick says what it took
default: return false;
}
}
@ -110,12 +112,12 @@ public sealed partial class RynthAiPlugin
private void HandleSetMetaStateCommand(string[] parts)
{
var s = _dashboard?.Settings;
if (s == null || _metaManager == null) { ChatLine("[RynthAi] Meta not ready (log in first)."); return; }
if (s == null || _metaManager == null) { ReplyFail("[RynthAi] Meta not ready (log in first)."); return; }
List<string> states = LoadedMetaStates();
if (parts.Length < 3)
{
ChatLine($"[RynthAi] Meta state: {s.CurrentState}. States: {(states.Count == 0 ? "(no meta loaded)" : string.Join(", ", states))}.");
ChatLine("[RynthAi] Usage: /ra setmetastate <state>");
ReplyFail("[RynthAi] Usage: /ra setmetastate <state>");
return;
}
string want = string.Join(" ", parts, 2, parts.Length - 2);
@ -123,7 +125,7 @@ public sealed partial class RynthAiPlugin
string? known = states.FirstOrDefault(x => x.Equals(want, StringComparison.OrdinalIgnoreCase));
_metaManager.TryHandleVtCommand("/vt setmetastate " + (known ?? want));
if (known == null && states.Count > 0)
ChatLine($"[RynthAi] Note: the loaded meta has no state '{want}' (states: {string.Join(", ", states)}).");
ReplyFail($"[RynthAi] Note: the loaded meta has no state '{want}' (states: {string.Join(", ", states)}).");
}
// ── Target lock ───────────────────────────────────────────────────────────
@ -131,13 +133,13 @@ public sealed partial class RynthAiPlugin
private void HandleTargetLockCommand(string[] parts)
{
var cm = _combatManager;
if (cm == null) { ChatLine("[RynthAi] Combat not ready (log in first)."); return; }
if (cm == null) { ReplyFail("[RynthAi] Combat not ready (log in first)."); return; }
string arg = parts.Length >= 3 ? parts[2].ToLowerInvariant() : "";
int current = cm.ForcedTargetId;
if (arg is "off" or "clear" or "release" or "0")
{
cm.ClearForcedTarget();
ChatLine(current == 0 ? "[RynthAi] Target lock: none set." : "[RynthAi] Target lock released.");
ReplyOk(current == 0 ? "[RynthAi] Target lock: none set." : "[RynthAi] Target lock released.");
return;
}
@ -146,13 +148,13 @@ public sealed partial class RynthAiPlugin
if (id != 0 && id == current)
{
cm.ClearForcedTarget();
ChatLine($"[RynthAi] Target lock on {_objectCache?[id]?.Name ?? $"0x{selected:X8}"} released.");
ReplyOk($"[RynthAi] Target lock on {_objectCache?[id]?.Name ?? $"0x{selected:X8}"} released.");
return;
}
string? refusal = cm.ForcedTargetRefusal(id);
if (refusal != null)
{
ChatLine($"[RynthAi] Target lock: {refusal}.");
ReplyFail($"[RynthAi] Target lock: {refusal}.");
return;
}
cm.SetForcedTarget(id);
@ -160,7 +162,7 @@ public sealed partial class RynthAiPlugin
string name = _objectCache?[id]?.Name ?? $"0x{selected:X8}";
string note = s == null ? "" : !s.IsMacroRunning ? " (the macro is off: it attacks once started)"
: !s.EnableCombat ? " (Combat is off: it attacks once Combat is on)" : "";
ChatLine($"[RynthAi] Target lock: attacking {name}{note}.");
ReplyOk($"[RynthAi] Target lock: attacking {name}{note}.");
}
// ── Melee attack height ──────────────────────────────────────────────────
@ -168,10 +170,10 @@ public sealed partial class RynthAiPlugin
private void SetMeleeAttackHeight(int height)
{
var dash = _dashboard;
if (dash?.Settings == null) { ChatLine("[RynthAi] Settings not ready."); return; }
if (dash?.Settings == null) { ReplyFail("[RynthAi] Settings not ready."); return; }
dash.Settings.MeleeAttackHeight = Math.Clamp(height, 0, 2);
dash.SaveSettings();
ChatLine($"[RynthAi] Melee attack height: {MeleeHeightNames[dash.Settings.MeleeAttackHeight]}.");
ReplyOk($"[RynthAi] Melee attack height: {MeleeHeightNames[dash.Settings.MeleeAttackHeight]}.");
}
// ── Boost Nav / Loot Priority ─────────────────────────────────────────────
@ -196,12 +198,12 @@ public sealed partial class RynthAiPlugin
{
var dash = _dashboard;
var s = dash?.Settings;
if (s == null) { ChatLine("[RynthAi] Settings not ready."); return; }
if (s == null) { ReplyFail("[RynthAi] Settings not ready."); return; }
string arg = parts.Length >= 3 ? parts[2].ToLowerInvariant() : "";
(s.BoostNavPriority, s.BoostLootPriority) = NextPriority(s.BoostNavPriority, s.BoostLootPriority, nav, loot, arg);
dash!.SaveSettings();
string On(bool b) => b ? "on" : "off";
ChatLine(nav && loot ? $"[RynthAi] Boost Nav Priority {On(s.BoostNavPriority)}, Boost Loot Priority {On(s.BoostLootPriority)}."
ReplyOk(nav && loot ? $"[RynthAi] Boost Nav Priority {On(s.BoostNavPriority)}, Boost Loot Priority {On(s.BoostLootPriority)}."
: nav ? $"[RynthAi] Boost Nav Priority {On(s.BoostNavPriority)}."
: $"[RynthAi] Boost Loot Priority {On(s.BoostLootPriority)}.");
}
@ -210,16 +212,18 @@ public sealed partial class RynthAiPlugin
private void HandleRechargeCommand()
{
if (_buffManager == null) { ChatLine("[RynthAi] Buff manager not ready (log in first)."); return; }
if (_buffManager == null) { ReplyFail("[RynthAi] Buff manager not ready (log in first)."); return; }
_buffManager.RequestRecharge(); // runs on the pump's next heartbeat, says what it did
Reply.Answered();
}
// ── One-touch heal / stamina / mana ───────────────────────────────────────
private void HandleOneTouchCommand(OneTouchVital vital)
{
if (_buffManager == null) { ChatLine("[RynthAi] Buff manager not ready (log in first)."); return; }
if (_buffManager == null) { ReplyFail("[RynthAi] Buff manager not ready (log in first)."); return; }
_buffManager.RequestOneTouch(vital); // runs on the pump's next heartbeat, says what it did
Reply.Answered();
}
// ── LootThisCont ──────────────────────────────────────────────────────────

View file

@ -25,7 +25,7 @@ public sealed partial class RynthAiPlugin
if (dash == null)
return false;
_vtankYield.Poll(Host);
if (!_vtankYield.RefuseStart(dash.Settings, ChatLine))
if (!_vtankYield.RefuseStart(dash.Settings, ReplyFail)) // a refusal: said even to a meta (once a minute)
return false;
Host.Log("[RynthAi] VTank yield: macro start refused (VTank's macro runs).");
return true;
@ -71,16 +71,18 @@ public sealed partial class RynthAiPlugin
private void HandleVTankYieldCommand(string[] parts)
{
var dash = _dashboard;
if (dash == null) { ChatLine("[RynthAi] Settings not ready."); return; }
if (dash == null) { ReplyFail("[RynthAi] Settings not ready."); return; }
if (parts.Length >= 3)
{
string v = parts[2].ToLowerInvariant();
if (v is "on" or "1" or "true") dash.Settings.YieldToVTank = true;
else if (v is "off" or "0" or "false") dash.Settings.YieldToVTank = false;
else { ChatLine("[RynthAi] Usage: /ra vtankyield [on|off]"); return; }
else { ReplyFail("[RynthAi] Usage: /ra vtankyield [on|off]"); return; }
dash.SaveSettings();
}
_vtankYield.Poll(Host);
ChatLine(_vtankYield.Describe(dash.Settings.YieldToVTank, Host.HasGetVTankState));
string line = _vtankYield.Describe(dash.Settings.YieldToVTank, Host.HasGetVTankState);
if (parts.Length >= 3) ReplyOk(line); // set: what it is now
else ChatLine(line); // the status asked for
}
}

View file

@ -566,7 +566,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
EnsureSpellsUi();
_navigationEngine = new NavigationEngine(Host, _dashboard.Settings)
{
ChatSubmit = HandleRynthChatSubmit,
// A route's chat waypoint answers as a script's line: quiet when it works (CommandReply.cs).
ChatSubmit = line => Reply.AsScript(() => { HandleRynthChatSubmit(line); return true; }),
// Jump waypoints go through the UB-style jumper (turn, charge, jump, then
// it hands navigation back). Forward jump; shift = walking jump.
Jump = (heading, shift, ms) => _jumper?.Start(shift ? "ws" : "w", heading, ms),
@ -789,6 +790,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_metaManager.SetPlayerId(_playerId);
_metaManager.SetMtCommandHandler(HandleMetaChatCommand);
_metaManager.SetRaCommandHandler(HandleRaCommand);
_metaManager.Reply = Reply; // /vt lines answer by the same rule as every command (CommandReply.cs)
if (_objectCache != null) _metaManager.SetObjectCache(_objectCache);
_metaManager.SetFellowshipTracker(_fellowshipTracker);
_metaManager.SetQuestTracker(_questTracker);
@ -832,13 +834,15 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
_scrollLearner = CreateScrollLearner(_dashboard.Settings);
_jumper = new Jumper(Host, _dashboard.Settings, s => Host.WriteToChat(s, 1));
// The jumper's own lines are refusals (busy, a bad heading or hold time, no jump hook).
_jumper = new Jumper(Host, _dashboard.Settings, ReplyFail);
if (_objectCache != null)
{
var dashForAv = _dashboard;
_autoVendor = new AutoVendorManager(Host, _dashboard.Settings, _objectCache, _playerId,
() => dashForAv?.CharFolder ?? string.Empty);
_autoVendor.Reply = Reply; // its /ub vendor answers follow the command rule (CommandReply.cs)
var avForUi = _autoVendor;
_dashboard.SetAutoVendorStatusProvider(() => avForUi.Status);
_dashboard.SetVendorProfilePathProvider(() => avForUi.OpenVendorProfilePath);
@ -3423,13 +3427,19 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
}
NoteChatBarLineForMetaSchedule(trimmed);
// Every command answers (CommandReply.cs): a typed line in one chat line, a meta's quietly
// when it works. Unknown verbs and wrong argument counts answer with the usage.
// Mag-Tools /mt command compatibility
if (trimmed.StartsWith("/mt ", StringComparison.OrdinalIgnoreCase)
|| trimmed.Equals("/mt", StringComparison.OrdinalIgnoreCase))
{
eat = 1;
if (!HandleMtCommand(trimmed))
ChatLine($"[RynthAi] Unrecognized /mt command. Try /mt opt list");
Reply.Run(trimmed, () =>
{
if (!HandleMtCommand(trimmed))
ReplyFail(MtUsageFor(trimmed));
});
return;
}
@ -3437,8 +3447,11 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
if (trimmed.StartsWith("/ub ", StringComparison.OrdinalIgnoreCase))
{
eat = 1;
if (!HandleUbCommand(trimmed))
ChatLine("[RynthAi] Unrecognized /ub command.");
Reply.Run(trimmed, () =>
{
if (!HandleUbCommand(trimmed))
ReplyFail(UbUsageFor(trimmed));
});
return;
}
@ -3450,8 +3463,11 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
|| trimmed.Equals("/vt", StringComparison.OrdinalIgnoreCase))
{
eat = 1;
if (!(_metaManager?.TryHandleVtCommand(trimmed) ?? false))
ChatLine("[RynthAi] Unrecognized /vt command.");
Reply.Run(trimmed, () =>
{
if (_metaManager == null) ReplyFail("[RynthAi] /vt commands aren't ready yet (log in first).");
else if (!_metaManager.TryHandleVtCommand(trimmed)) ReplyFail(MetaManager.VtUsageFor(trimmed));
});
return;
}
@ -3464,13 +3480,15 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
if (parts.Length < 2 || parts[1].Equals("help", StringComparison.OrdinalIgnoreCase))
{
eat = 1;
HandleHelpCommand();
Reply.Run(trimmed, HandleHelpCommand);
return;
}
string cmd = parts[1].ToLower();
eat = 1;
DispatchRaCommand(cmd, parts, ref eat);
int raEat = 1;
Reply.Run(trimmed, () => DispatchRaCommand(cmd, parts, ref raEat));
eat = raEat;
}
/// <summary>
@ -3513,7 +3531,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
int count = _pendingGives.Count + (redo.HasValue ? 1 : 0);
_pendingGives.Clear();
ResetGiveState();
ChatLine(count > 0
ReplyOk(count > 0
? $"[RynthAi] Give queue cancelled ({count} item(s) remaining)."
: "[RynthAi] Give queue is already empty.");
}
@ -3902,7 +3920,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
case "cache": HandleCacheCommand(); break;
case "cache2": HandleCache2Command(); break;
case "buffs":
if (_buffManager == null) { ChatLine("[RynthAi] BuffManager not ready (not logged in yet)."); break; }
if (_buffManager == null) { ReplyFail("[RynthAi] BuffManager not ready (not logged in yet)."); break; }
if (parts.Length >= 3 && parts[2].Equals("item", StringComparison.OrdinalIgnoreCase))
_buffManager.PrintItemBuffDebug();
else if (parts.Length >= 3 && parts[2].Equals("tiers", StringComparison.OrdinalIgnoreCase))
@ -3934,8 +3952,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
case "pets":
// The Mini Remote's verbs; "/ra guardian", "/ra bounty" and the like are the server
// plugin's (default below), as is any "/ra hub ..." verb RynthAi doesn't have.
if (_miniRemote == null) { ChatLine("[RynthAi] The Mini Remote isn't ready (log in first)."); break; }
if (_miniRemote == null) { ReplyFail("[RynthAi] The Mini Remote isn't ready (log in first)."); break; }
_miniRemote.HandleCommand(cmd, parts.Length > 2 ? parts[2..] : Array.Empty<string>());
Reply.Answered(); // the Mini Remote (or the server plugin it hands the verb to) says what it did
break;
case "itemhud" when parts.Length > 2 && parts[2].Equals("add", StringComparison.OrdinalIgnoreCase):
HandleItemHudAdd(string.Join(" ", parts, 3, parts.Length - 3));
@ -3959,7 +3978,7 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
case "lua": ForwardLuaCommand(parts); break;
case "items":
if (parts.Length >= 3 && parts[2].Equals("fill", StringComparison.OrdinalIgnoreCase))
ChatLine(_dashboard?.FillItemsFromPack(_objectCache, _playerId) ?? "[RynthAi] Settings not ready.");
ReplyResult(_dashboard?.FillItemsFromPack(_objectCache, _playerId) ?? "[RynthAi] Settings not ready.");
else if (parts.Length >= 3 && parts[2].Equals("clean", StringComparison.OrdinalIgnoreCase))
CleanMissingItems();
else
@ -3970,8 +3989,8 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
break;
case "follow": HandleFollowCommand(parts); break;
case "myquests":
case "refreshquests": _questTracker?.Refresh(); ChatLine("[RynthAi] Quest flag refresh requested."); break;
case "metamgr": QueueMetaMgrCommand(parts); break; // Meta Manager: applied on the next tick
case "refreshquests": _questTracker?.Refresh(); ReplyOk("[RynthAi] Quest flag refresh requested."); break;
case "metamgr": QueueMetaMgrCommand(parts); Reply.Answered(); break; // Meta Manager: applied (and answered) on the next tick
case "dunnav": HandleDungeonNavCommand(parts); break;
case "dunnav-patrol": HandleDungeonNavPatrolCommand(parts); break;
case "hazard": HandleHazardCommand(parts); break;
@ -4007,21 +4026,22 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
case "cancelforcebuff": HandleCancelForceBuff(); break;
case "buff": HandleBuffCommand(parts); break;
case "swaptest":
if (_buffManager == null) { ChatLine("[RynthAi] BuffManager not ready (not logged in yet)."); break; }
if (_buffManager == null) { ReplyFail("[RynthAi] BuffManager not ready (not logged in yet)."); break; }
_buffManager.RequestSwapTest(parts.Length > 2 ? string.Join(" ", parts, 2, parts.Length - 2) : "");
Reply.Answered(); // the swap test says what it does on the next heartbeat
break;
case "bufftest":
if (_buffManager == null) { ChatLine("[RynthAi] BuffManager not ready (not logged in yet)."); break; }
if (_buffManager == null) { ReplyFail("[RynthAi] BuffManager not ready (not logged in yet)."); break; }
_buffManager.EnableCastRegistryDiagnostic = !_buffManager.EnableCastRegistryDiagnostic;
if (_buffManager.EnableCastRegistryDiagnostic)
{
ChatLine("[RynthAi] BuffTest ON — fires on next item-spell cast.");
ChatLine("[RynthAi] Cast an Impen/Bane (via macro or manually). Diff logs to RynthCore.log with [BuffTest] tag.");
ChatLine("[RynthAi] Auto-disables after one cast/diff.");
ReplyOk("[RynthAi] BuffTest ON — fires on next item-spell cast.");
ReplyOk("[RynthAi] Cast an Impen/Bane (via macro or manually). Diff logs to RynthCore.log with [BuffTest] tag.");
ReplyOk("[RynthAi] Auto-disables after one cast/diff.");
}
else
{
ChatLine("[RynthAi] BuffTest OFF.");
ReplyOk("[RynthAi] BuffTest OFF.");
}
break;
case "settings": HandleSettingsCommand(parts); break;
@ -4032,7 +4052,10 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
case "busyinfo": HandleBusyInfoCommand(); break;
// /ra quit | /ra exit: close the client (the engine's /rc quit: as its close button)
case "quit":
case "exit": if (Host.HasInvokeChatParser) Host.InvokeChatParser("/rc quit"); break;
case "exit":
if (Host.HasInvokeChatParser) { Host.InvokeChatParser("/rc quit"); Reply.Answered(); } // the client closes
else ReplyFail("[RynthAi] Can't close the client: the chat parser isn't available.");
break;
// give variants — first-match (with optional count prefix)
case "give": HandleGiveCommand(parts, GiveItemMatch.Exact, partialPlayer: false); break;
case "givep": HandleGiveCommand(parts, GiveItemMatch.Partial, partialPlayer: false); break;
@ -4086,8 +4109,9 @@ public sealed partial class RynthAiPlugin : RynthPluginBase
}
// A verb RynthAi doesn't have may be the server plugin's ("/ra t11", "/ra guardian", "/ra bounty"
// are RynthILT's on Infinite Leaftide); without one it goes on to the server, as any unknown "/ra".
if (TryForwardToServerPlugin(parts)) break;
if (TryForwardToServerPlugin(parts)) { Reply.Answered(); break; } // the server plugin answers
eat = 0;
ReplyFail($"[RynthAi] Unknown command: /ra {cmd}. /ra help lists RynthAi's.");
break;
}
}

View file

@ -62,6 +62,7 @@ public sealed partial class RynthAiPlugin
return;
}
Host.RequestId(me);
Reply.Answered(); // the ratings follow when the ID data arrives
_selfRatingsRequestedAt = now;
ItemInfoLog($"self 0x{me:X8}: identify requested for the ratings");
}

View file

@ -271,5 +271,7 @@ public sealed partial class RynthAiPlugin
return !_raycast.IsTargetBlocked(Host, id, TargetingFSM.AttackType.Linear);
}
internal void ScriptSubmitCommand(string text) => HandleRynthChatSubmit(text);
/// <summary>A RynthLua script's ai.Command(text): handled as a typed line, but it answers as a script's
/// (quiet when it works, errors in chat; CommandReply.cs).</summary>
internal void ScriptSubmitCommand(string text) => Reply.AsScript(() => { HandleRynthChatSubmit(text); return true; });
}

View file

@ -36,9 +36,10 @@ public sealed partial class RynthAiPlugin
var at = _autoTrade;
if (at == null)
{
ChatLine("[RynthAi] AutoTrade isn't ready yet (log in first).");
ReplyFail("[RynthAi] AutoTrade isn't ready yet (log in first).");
return;
}
Reply.Answered(); // AutoTrade says what it did when it runs the command on the tick
at.Enqueue(() => at.Command(args));
}
@ -47,7 +48,7 @@ public sealed partial class RynthAiPlugin
{
if (!Host.HasTrade)
{
ChatLine($"[RynthAi] Player trading needs RynthCore 2026.9.x or newer (plugin API v{AutoTradeManager.RequiredApiVersion}; this engine is v{Host.Version}).");
ReplyFail($"[RynthAi] Player trading needs RynthCore 2026.9.x or newer (plugin API v{AutoTradeManager.RequiredApiVersion}; this engine is v{Host.Version}).");
return;
}
@ -62,27 +63,27 @@ public sealed partial class RynthAiPlugin
case "open":
{
uint target = ResolveTradeTarget(arg);
if (target == 0) { ChatLine("[RynthAi] Usage: /ra trade open <player name|id|sel>"); break; }
ChatLine(Host.TradeOpen(target)
? $"[RynthAi] Asked {TradeName(target)} to trade."
: "[RynthAi] Could not send the trade request.");
if (target == 0) { ReplyFail("[RynthAi] Usage: /ra trade open <player name|id|sel>"); break; }
ReplyIf(Host.TradeOpen(target),
$"[RynthAi] Asked {TradeName(target)} to trade.",
"[RynthAi] Could not send the trade request.");
break;
}
case "add":
{
uint item = ParseTradeId(arg);
if (item == 0) { ChatLine("[RynthAi] Usage: /ra trade add <item id|sel>"); break; }
ChatLine(Host.TradeAdd(item)
? $"[RynthAi] Adding {TradeName(item)} to the trade window."
: "[RynthAi] Could not send the add.");
if (item == 0) { ReplyFail("[RynthAi] Usage: /ra trade add <item id|sel>"); break; }
ReplyIf(Host.TradeAdd(item),
$"[RynthAi] Adding {TradeName(item)} to the trade window.",
"[RynthAi] Could not send the add.");
break;
}
case "accept": ChatLine(Host.TradeAccept() ? "[RynthAi] Accepting the trade." : "[RynthAi] Could not send the accept."); break;
case "decline": ChatLine(Host.TradeDecline() ? "[RynthAi] Declining the trade." : "[RynthAi] Could not send the decline."); break;
case "reset": ChatLine(Host.TradeReset() ? "[RynthAi] Clearing the trade window." : "[RynthAi] Could not send the reset."); break;
case "close": ChatLine(Host.TradeClose() ? "[RynthAi] Closing the trade." : "[RynthAi] Could not send the close."); break;
case "accept": ReplyIf(Host.TradeAccept(), "[RynthAi] Accepting the trade.", "[RynthAi] Could not send the accept."); break;
case "decline": ReplyIf(Host.TradeDecline(), "[RynthAi] Declining the trade.", "[RynthAi] Could not send the decline."); break;
case "reset": ReplyIf(Host.TradeReset(), "[RynthAi] Clearing the trade window.", "[RynthAi] Could not send the reset."); break;
case "close": ReplyIf(Host.TradeClose(), "[RynthAi] Closing the trade.", "[RynthAi] Could not send the close."); break;
default:
ChatLine("[RynthAi] Usage: /ra trade [state | open <name|id|sel> | add <id|sel> | accept | decline | reset | close]");
ReplyFail("[RynthAi] Usage: /ra trade [state | open <name|id|sel> | add <id|sel> | accept | decline | reset | close]");
break;
}
}

View file

@ -57,10 +57,10 @@ public sealed partial class RynthAiPlugin
private void UseClosestPortal()
{
if (_objectCache == null || _playerId == 0) { ChatLine("[RynthAi] Not logged in."); return; }
if (_objectCache == null || _playerId == 0) { ReplyFail("[RynthAi] Not logged in."); return; }
var best = FindNearestPositioned(IsPortalObject, out double bestD);
if (best == null) { ChatLine("[RynthAi] No portal nearby."); LogPortalMiss("closestportal"); return; }
ChatLine($"[RynthAi] Using {best.Name} ({bestD:F1} m).");
if (best == null) { ReplyFail("[RynthAi] No portal nearby."); LogPortalMiss("closestportal"); return; }
ReplyOk($"[RynthAi] Using {best.Name} ({bestD:F1} m).");
Host.UseFor(unchecked((uint)best.Id), "Command", "/ub closestportal", UseKind.Asked);
}
@ -72,8 +72,32 @@ public sealed partial class RynthAiPlugin
{
string rest = fullCommand.Length > 3 ? fullCommand.Substring(3).Trim() : "";
if (Host.HasSendPluginCommand && Host.SendPluginCommand("RynthNet", "ub", rest))
{
Reply.Answered(); // RynthNet answers its own verbs
return;
ChatLine("[RynthAi] /ub bc, /ub bct and /ub netclients need the RynthNet plugin (the launcher's Plugins tab).");
}
ReplyFail("[RynthAi] /ub bc, /ub bct and /ub netclients need the RynthNet plugin (the launcher's Plugins tab).");
}
/// <summary>
/// The usage line for a /ub line RynthAi didn't take: the verb's usage when it is one RynthAi has
/// (the wrong arguments), else "unknown" and where the list is.
/// </summary>
private static string UbUsageFor(string line)
{
string[] w = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
string verb = w.Length > 1 ? w[1].ToLowerInvariant() : "";
string? usage = MtVerbUsage(verb, "/ub") ?? verb switch
{
"follow" or "followp" => "/ub follow[p] <name>",
"ig" or "igp" => $"/ub {verb} <loot profile> to <player>",
"mexec" => "/ub mexec <expression>",
"propertydump" => "/ub propertydump [0xId]",
_ => null,
};
return usage != null
? "[RynthAi] Usage: " + usage
: $"[RynthAi] Unknown /ub command{(verb.Length > 0 ? $" '{verb}'" : "")}. /ub help lists the ones RynthAi takes.";
}
/// <summary>
@ -88,7 +112,10 @@ public sealed partial class RynthAiPlugin
// ub-Rythai's verbs: that plugin answers; handled here only in the sense of "not unknown".
if (IsUbRythaiCommand(cmd, SplitUbLine(fullCommand).Args))
{
Reply.Answered();
return true;
}
// "/ub vtsetmetastate[State]" and the like: an expression, not a verb.
if (TryHandleUbExpression(fullCommand))

View file

@ -148,9 +148,12 @@ public sealed partial class RynthAiPlugin
return true;
// ── RynthCore's window placement ────────────────────────────────────
// The engine has no chat command for it ("/rc window save" never existed and went nowhere):
// its Settings > Display saves the game window for each character and puts it back at login.
case "window":
if (sub == "save") InvokeServerCommand("/rc window save");
else UbNoEquivalent(cmd + " " + sub, "RynthCore restores the saved window at login (/rc window save|reset)");
UbNoEquivalent(cmd + (sub.Length > 0 ? " " + sub : ""), null,
$"[RynthAi] /ub window{(sub.Length > 0 ? " " + sub : "")}: RynthCore keeps the game window itself - Settings > Display, "
+ "'Remember Game Window Position' (saved for each character, put back after login), or 'Save Layout Now' there.");
return true;
// ── RynthAi's Mini Remote ───────────────────────────────────────────
@ -189,7 +192,7 @@ public sealed partial class RynthAiPlugin
private void UbClose(string kind)
{
uint open = Host.HasGetGroundContainerId ? Host.GetGroundContainerId() : 0;
if (open == 0) { ChatLine("[RynthAi] No container is currently open."); return; }
if (open == 0) { ReplyFail("[RynthAi] No container is currently open."); return; }
WorldObject? wo = _objectCache?[unchecked((int)open)];
bool fits = kind switch
{
@ -197,9 +200,17 @@ public sealed partial class RynthAiPlugin
"chest" => wo == null || wo.ObjectClass == AcObjectClass.Container,
_ => true,
};
if (!fits) return; // as ub-IT: the open container isn't that kind, nothing to do
string name = wo?.Name is { Length: > 0 } n ? n : $"0x{open:X8}";
if (!fits)
{
// As ub-IT: the open container isn't that kind, so there is nothing to do.
ReplyOk($"[RynthAi] /ub close {kind}: the open container ({name}) isn't a {kind}; left it open.");
return;
}
bool closed = Host.HasCloseContainer ? Host.CloseContainer(open) : Host.UseFor(open, "Command", "/ub close", UseKind.Asked);
Log($"[RynthAi] /ub close {kind}: 0x{open:X8} {(closed ? "closed" : "close refused")}.");
if (closed) ReplyOk($"[RynthAi] Closed {name}.");
else ReplyFail($"[RynthAi] Couldn't close {name} (the engine refused it).");
}
/// <summary>
@ -214,39 +225,45 @@ public sealed partial class RynthAiPlugin
int space = rest.IndexOf(' ');
if (bracket <= 0 || (space >= 0 && space < bracket) || !rest.EndsWith("]", StringComparison.Ordinal)) return false;
string result = EvalExpr(rest);
Log($"[RynthAi] /ub {rest} evaluated as an expression -> '{result}'.");
// A meta's (the usual sender): the log line only. Typed: the same line in chat.
ReplyOk($"[RynthAi] /ub {rest} evaluated as an expression -> '{result}'.");
return true;
}
/// <summary>Says once per session that a /ub verb is accepted and ignored; every use is logged.</summary>
private void UbNoEquivalent(string what, string? note)
/// <summary>
/// A /ub verb accepted and ignored: said every time it is typed, and once per session when a meta
/// sends it (so a meta that repeats it doesn't flood chat); every use is logged.
/// </summary>
private void UbNoEquivalent(string what, string? note, string? text = null)
{
Log($"[RynthAi] /ub {what}: no RynthAi equivalent; ignored.");
if (_ubNoEquivalentSaid.Add(what))
ChatLine($"[RynthAi] /ub {what} is a ub-IT feature with no RynthAi equivalent; it is accepted and ignored so metas keep running"
+ (note != null ? $" ({note})." : "."));
if (!Reply.FromScript || _ubNoEquivalentSaid.Add(what))
ReplyFail(text ?? $"[RynthAi] /ub {what} is a ub-IT feature with no RynthAi equivalent; it is accepted and ignored so metas keep running"
+ (note != null ? $" ({note})." : "."));
else
Reply.Answered();
}
/// <summary>Sends a chat line to the chat parser (server commands, /rc).</summary>
/// <summary>Sends a chat line to the chat parser (server commands): the server answers it.</summary>
private void InvokeServerCommand(string line)
{
if (Host.HasInvokeChatParser) Host.InvokeChatParser(line);
else ChatLine($"[RynthAi] Can't send {line}: the chat parser isn't available.");
if (Host.HasInvokeChatParser) { Host.InvokeChatParser(line); Reply.Answered(); }
else ReplyFail($"[RynthAi] Can't send {line}: the chat parser isn't available.");
}
/// <summary>A command for another plugin through the engine broker.</summary>
/// <summary>A command for another plugin through the engine broker: that plugin answers it.</summary>
private void SendToPlugin(string plugin, string action, string value, string missing)
{
if (!(Host.HasSendPluginCommand && Host.SendPluginCommand(plugin, action, value)))
ChatLine("[RynthAi] " + missing);
if (Host.HasSendPluginCommand && Host.SendPluginCommand(plugin, action, value)) Reply.Answered();
else ReplyFail("[RynthAi] " + missing);
}
/// <summary>/ub wear[p] &lt;name&gt;: wield a carried item by name, skipping copies already worn
/// (using a worn item would take it off).</summary>
private void UbWear(string name, bool partial)
{
if (string.IsNullOrWhiteSpace(name)) { ChatLine("[RynthAi] Usage: /ub wear <item name> (wearp: partial name)"); return; }
if (_objectCache == null || !Host.HasUseObject) { ChatLine("[RynthAi] /ub wear: not ready (log in first)."); return; }
if (string.IsNullOrWhiteSpace(name)) { ReplyFail("[RynthAi] Usage: /ub wear <item name> (wearp: partial name)"); return; }
if (_objectCache == null || !Host.HasUseObject) { ReplyFail("[RynthAi] /ub wear: not ready (log in first)."); return; }
bool sawWorn = false;
foreach (var wo in _objectCache.GetInventory())
@ -258,9 +275,11 @@ public sealed partial class RynthAiPlugin
if (wo.Values(LongValueKey.CurrentWieldedLocation, 0) > 0) { sawWorn = true; continue; }
Host.UseFor(unchecked((uint)wo.Id), "Command", "/ub wear", UseKind.Asked);
Log($"[RynthAi] /ub wear: {wo.Name} (0x{(uint)wo.Id:X8})");
ReplyOk($"[RynthAi] Wearing {wo.Name}.");
return;
}
ChatLine(sawWorn ? $"[RynthAi] Already wearing '{name}'." : $"[RynthAi] Item not found: '{name}'");
if (sawWorn) ReplyOk($"[RynthAi] Already wearing '{name}'.");
else ReplyFail($"[RynthAi] Item not found: '{name}'");
}
/// <summary>/ub globalframelimit|bgframelimit &lt;fps&gt;: RynthAi's frame limit (Settings, Display).
@ -268,28 +287,28 @@ public sealed partial class RynthAiPlugin
private void UbFrameLimit(bool background, string arg)
{
LegacyUiSettings? s = _dashboard?.Settings;
if (s == null) { ChatLine("[RynthAi] Settings aren't loaded yet."); return; }
if (s == null) { ReplyFail("[RynthAi] Settings aren't loaded yet."); return; }
if (!int.TryParse(arg.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out int fps) || fps < 0)
{
ChatLine($"[RynthAi] Usage: /ub {(background ? "bgframelimit" : "globalframelimit")} <frames per second>");
ReplyFail($"[RynthAi] Usage: /ub {(background ? "bgframelimit" : "globalframelimit")} <frames per second>");
return;
}
if (background)
{
s.TargetFPSBackground = fps == 0 ? 60 : Math.Clamp(fps, 5, 60);
s.EnableFPSLimit = true;
ChatLine($"[RynthAi] Background frame limit: {s.TargetFPSBackground} fps.");
ReplyOk($"[RynthAi] Background frame limit: {s.TargetFPSBackground} fps.");
}
else if (fps == 0)
{
s.EnableFPSLimit = false;
ChatLine("[RynthAi] Frame limit off.");
ReplyOk("[RynthAi] Frame limit off.");
}
else
{
s.TargetFPSFocused = Math.Clamp(fps, 10, 240);
s.EnableFPSLimit = true;
ChatLine($"[RynthAi] Frame limit: {s.TargetFPSFocused} fps.");
ReplyOk($"[RynthAi] Frame limit: {s.TargetFPSFocused} fps.");
}
try { _dashboard?.SaveSettings(); } catch { }
}
@ -298,7 +317,7 @@ public sealed partial class RynthAiPlugin
private void UbFellow(string sub, string name)
{
if (sub == "status") { HandleFellowshipCommand(new[] { "/ra", "fellow", "status" }); return; }
if (name.Length == 0) { ChatLine($"[RynthAi] Usage: /ub fellow {sub} <name>"); return; }
if (name.Length == 0) { ReplyFail($"[RynthAi] Usage: /ub fellow {sub} <name>"); return; }
bool partial = sub.EndsWith('p');
string resolved = name;
@ -324,7 +343,7 @@ public sealed partial class RynthAiPlugin
|| !double.TryParse(w[0], NumberStyles.Float, CultureInfo.InvariantCulture, out double ns)
|| !double.TryParse(w[1], NumberStyles.Float, CultureInfo.InvariantCulture, out double ew))
{
ChatLine("[RynthAi] Usage: /ub navgoto <ns> <ew> [walk|run] (south and west are negative)");
ReplyFail("[RynthAi] Usage: /ub navgoto <ns> <ew> [walk|run] (south and west are negative)");
return;
}
string coords = FormattableString.Invariant($"{Math.Abs(ns):0.0#}{(ns < 0 ? 'S' : 'N')}, {Math.Abs(ew):0.0#}{(ew < 0 ? 'W' : 'E')}");
@ -339,7 +358,7 @@ public sealed partial class RynthAiPlugin
private bool UbStormSwitch(string cmd, string sub, string vtOption, string[] w)
{
string rest = w.Length > 1 ? string.Join(" ", w, 1, w.Length - 1) : "";
if (_metaManager == null) { ChatLine("[RynthAi] Not ready (log in first)."); return true; }
if (_metaManager == null) { ReplyFail("[RynthAi] Not ready (log in first)."); return true; }
switch (sub)
{

View file

@ -55,6 +55,7 @@ public sealed partial class RynthAiPlugin
&& Host.TryGetObjectName(_playerId, out string me) && !string.IsNullOrWhiteSpace(me))
{
Host.InvokeChatParser($"/tell {me}, {msg}");
Reply.Answered(); // the tell to yourself is the answer (metas watch for it)
return;
}
ChatLine("[RynthAi] " + msg);
@ -83,9 +84,9 @@ public sealed partial class RynthAiPlugin
case "playsound": UbPlaySound(args); return true;
case "setmotion": UbSetMotion(args); return true;
case "getmotion": UbGetMotion(); return true;
case "clearmotion": EvalExpr("clearmotion[]"); ChatLine("[RynthAi] Cleared all motions."); return true;
case "autostack": _inventoryManager?.RunManual(cram: false, stack: true); ChatLine("[RynthAi] AutoStack: stacking your inventory."); return true;
case "autocram": _inventoryManager?.RunManual(cram: true, stack: false); ChatLine("[RynthAi] AutoCram: moving items into side packs."); return true;
case "clearmotion": EvalExpr("clearmotion[]"); ReplyOk("[RynthAi] Cleared all motions."); return true;
case "autostack": _inventoryManager?.RunManual(cram: false, stack: true); ReplyOk("[RynthAi] AutoStack: stacking your inventory."); return true;
case "autocram": _inventoryManager?.RunManual(cram: true, stack: false); ReplyOk("[RynthAi] AutoCram: moving items into side packs."); return true;
// /ub opt list|get|set stay on the /mt opt handler (it knows the Mag-Tools
// option aliases); only toggle, which that one lacks, is handled here.
case "opt" when args.StartsWith("toggle", StringComparison.OrdinalIgnoreCase):
@ -111,12 +112,13 @@ public sealed partial class RynthAiPlugin
int sp = args.IndexOf(' ');
if (sp <= 0 || !int.TryParse(args.AsSpan(0, sp), out int ms) || ms < 0)
{
ChatLine("[RynthAi] Usage: /ub delay <millisecondDelay> <command>");
ReplyFail("[RynthAi] Usage: /ub delay <millisecondDelay> <command>");
return;
}
string command = args.Substring(sp + 1).Trim();
if (command.Length == 0) return;
if (command.Length == 0) { ReplyFail("[RynthAi] Usage: /ub delay <millisecondDelay> <command>"); return; }
_delayedCommands.Add((Environment.TickCount64 + ms, command, MetaCommandActive));
ReplyOk($"[RynthAi] In {ms} ms: {command}");
}
// /ub count {item <name> | profile <lootProfile> | player <range>} [debug] [think]
@ -125,7 +127,7 @@ public sealed partial class RynthAiPlugin
var words = args.Split(' ', StringSplitOptions.RemoveEmptyEntries).ToList();
bool think = words.RemoveAll(w => w.Equals("think", StringComparison.OrdinalIgnoreCase)) > 0;
words.RemoveAll(w => w.Equals("debug", StringComparison.OrdinalIgnoreCase));
if (words.Count < 2) { ChatLine("[RynthAi] Usage: /ub count {item <name> | profile <lootProfile> | player <range>} [think]"); return; }
if (words.Count < 2) { ReplyFail("[RynthAi] Usage: /ub count {item <name> | profile <lootProfile> | player <range>} [think]"); return; }
string kind = words[0].ToLowerInvariant();
string what = string.Join(" ", words.Skip(1));
var inv = _objectCache?.GetDirectInventory(forceRefresh: true) ?? (IReadOnlyList<WorldObject>)Array.Empty<WorldObject>();
@ -144,7 +146,7 @@ public sealed partial class RynthAiPlugin
case "profile":
{
string path = ResolveLootProfilePath(what);
if (path.Length == 0 || !TryLoadLootProfile(path, out VTankLootProfile profile, out _)) { ChatLine($"[RynthAi] count: loot profile not found: {what}"); return; }
if (path.Length == 0 || !TryLoadLootProfile(path, out VTankLootProfile profile, out _)) { ReplyFail($"[RynthAi] count: loot profile not found: {what}"); return; }
var ctx = new VTankLootContext(Host, _playerId) { Cache = _objectCache };
int n = 0;
foreach (var wo in inv)
@ -158,7 +160,7 @@ public sealed partial class RynthAiPlugin
}
case "player":
{
if (!double.TryParse(what, NumberStyles.Float, CultureInfo.InvariantCulture, out double range)) { ChatLine("[RynthAi] count player <range>"); return; }
if (!double.TryParse(what, NumberStyles.Float, CultureInfo.InvariantCulture, out double range)) { ReplyFail("[RynthAi] Usage: /ub count player <range>"); return; }
int n = 0;
int me = unchecked((int)_playerId);
if (_objectCache != null)
@ -168,7 +170,7 @@ public sealed partial class RynthAiPlugin
break;
}
default:
ChatLine("[RynthAi] Usage: /ub count {item <name> | profile <lootProfile> | player <range>} [think]");
ReplyFail("[RynthAi] Usage: /ub count {item <name> | profile <lootProfile> | player <range>} [think]");
break;
}
}
@ -192,14 +194,14 @@ public sealed partial class RynthAiPlugin
DateTime t = utc ? DateTime.UtcNow : RynthClock.Now;
string s;
try { s = format.Length > 0 ? t.ToString(format, CultureInfo.InvariantCulture) : t.ToString(CultureInfo.InvariantCulture); }
catch (FormatException) { ChatLine($"[RynthAi] Bad date format: {format}"); return; }
catch (FormatException) { ReplyFail($"[RynthAi] Bad date format: {format}"); return; }
ChatLine("[RynthAi] " + s);
}
private void UbId()
{
uint sel = Host.GetSelectedItemId();
if (sel == 0) { ChatLine("[RynthAi] Nothing selected."); return; }
if (sel == 0) { ReplyFail("[RynthAi] Nothing selected."); return; }
string name = Host.TryGetObjectName(sel, out string n) ? n : "?";
ChatLine($"[RynthAi] {name}: id 0x{sel:X8} ({sel})");
}
@ -210,7 +212,7 @@ public sealed partial class RynthAiPlugin
if (sel == 0) sel = _playerId;
if (sel == 0 || !Host.TryGetObjectPosition(sel, out uint cell, out float x, out float y, out float z))
{
ChatLine("[RynthAi] No position for the selected object.");
ReplyFail("[RynthAi] No position for the selected object.");
return;
}
string name = Host.TryGetObjectName(sel, out string n) ? n : "?";
@ -222,14 +224,14 @@ public sealed partial class RynthAiPlugin
// /ub portal[p] <portalName>: use the nearest portal (or NPC) by name; portalp = partial.
private void UbPortal(string name, bool partial)
{
if (name.Length == 0 || _objectCache == null || _playerId == 0) { ChatLine("[RynthAi] Usage: /ub portal[p] <portalName>"); return; }
if (name.Length == 0 || _objectCache == null || _playerId == 0) { ReplyFail("[RynthAi] Usage: /ub portal[p] <portalName>"); return; }
var best = FindNearestPositioned(wo =>
(partial ? wo.Name.IndexOf(name, StringComparison.OrdinalIgnoreCase) >= 0
: wo.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
&& (IsPortalObject(wo) || wo.ObjectClass == AcObjectClass.Npc), out double bestD);
if (best == null) { ChatLine($"[RynthAi] No portal named {(partial ? "like " : "")}'{name}' nearby."); LogPortalMiss("portal " + name); return; }
if (best == null) { ReplyFail($"[RynthAi] No portal named {(partial ? "like " : "")}'{name}' nearby."); LogPortalMiss("portal " + name); return; }
_navigationEngine?.Stop();
ChatLine($"[RynthAi] Using {best.Name} ({bestD:F1} m).");
ReplyOk($"[RynthAi] Using {best.Name} ({bestD:F1} m).");
Host.UseFor(unchecked((uint)best.Id), "Command", "/ub portal", UseKind.Asked);
}
@ -244,9 +246,13 @@ public sealed partial class RynthAiPlugin
if (sp > 0 && int.TryParse(args.AsSpan(0, sp), out _)) file = args.Substring(sp + 1).Trim();
file = file.Trim('"');
if (!Path.IsPathRooted(file)) file = Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, file);
if (!File.Exists(file)) { ChatLine($"[RynthAi] Sound file not found: {file}"); return; }
try { PlaySound(file, IntPtr.Zero, 0x00020000 /*SND_FILENAME*/ | 0x0001 /*SND_ASYNC*/); }
catch (Exception ex) { ChatLine($"[RynthAi] playsound failed: {ex.Message}"); }
if (!File.Exists(file)) { ReplyFail($"[RynthAi] Sound file not found: {file}"); return; }
try
{
if (PlaySound(file, IntPtr.Zero, 0x00020000 /*SND_FILENAME*/ | 0x0001 /*SND_ASYNC*/)) ReplyOk($"[RynthAi] Playing {Path.GetFileName(file)}.");
else ReplyFail($"[RynthAi] playsound: Windows couldn't play {file}.");
}
catch (Exception ex) { ReplyFail($"[RynthAi] playsound failed: {ex.Message}"); }
}
private static readonly string[] UbMotions = { "Forward", "Backward", "TurnRight", "TurnLeft", "StrafeRight", "StrafeLeft", "Walk" };
@ -255,8 +261,9 @@ public sealed partial class RynthAiPlugin
private void UbSetMotion(string args)
{
var w = args.Split(' ', StringSplitOptions.RemoveEmptyEntries);
if (w.Length != 2 || (w[1] != "0" && w[1] != "1")) { ChatLine("[RynthAi] Usage: /ub setmotion <" + string.Join("|", UbMotions) + "> <0|1>"); return; }
if (w.Length != 2 || (w[1] != "0" && w[1] != "1")) { ReplyFail("[RynthAi] Usage: /ub setmotion <" + string.Join("|", UbMotions) + "> <0|1>"); return; }
EvalExpr($"setmotion[`{w[0]}`,{w[1]}]");
ReplyOk($"[RynthAi] Motion {w[0]}: {(w[1] == "1" ? "on" : "off")}.");
}
private void UbGetMotion()
@ -269,7 +276,7 @@ public sealed partial class RynthAiPlugin
private void UbOpt(string args)
{
var map = _metaManager?.Expressions.BuildSettingsMapPublic();
if (map == null) { ChatLine("[RynthAi] Settings not ready."); return; }
if (map == null) { ReplyFail("[RynthAi] Settings not ready."); return; }
var w = args.Split(' ', StringSplitOptions.RemoveEmptyEntries);
string verb = w.Length > 0 ? w[0].ToLowerInvariant() : "list";
switch (verb)
@ -279,7 +286,8 @@ public sealed partial class RynthAiPlugin
ChatLine("[RynthAi] " + string.Join(", ", chunk));
break;
case "get" when w.Length >= 2:
ChatLine(map.TryGetValue(w[1], out var g) ? $"[RynthAi] {w[1]} = {g.Get()}" : $"[RynthAi] No option '{w[1]}' (/ub opt list).");
if (map.TryGetValue(w[1], out var g)) ChatLine($"[RynthAi] {w[1]} = {g.Get()}");
else ReplyFail($"[RynthAi] No option '{w[1]}' (/ub opt list).");
break;
case "set" when w.Length >= 3:
if (map.TryGetValue(w[1], out var st))
@ -288,21 +296,21 @@ public sealed partial class RynthAiPlugin
v = v.Equals("true", StringComparison.OrdinalIgnoreCase) ? "1" : v.Equals("false", StringComparison.OrdinalIgnoreCase) ? "0" : v;
st.Set(v);
_dashboard?.SaveSettings();
ChatLine($"[RynthAi] {w[1]} = {st.Get()}");
ReplyOk($"[RynthAi] {w[1]} = {st.Get()}");
}
else ChatLine($"[RynthAi] No option '{w[1]}' (/ub opt list).");
else ReplyFail($"[RynthAi] No option '{w[1]}' (/ub opt list).");
break;
case "toggle" when w.Length >= 2:
foreach (string name in w.Skip(1))
{
if (!map.TryGetValue(name, out var tg)) { ChatLine($"[RynthAi] No option '{name}'."); continue; }
if (!map.TryGetValue(name, out var tg)) { ReplyFail($"[RynthAi] No option '{name}'."); continue; }
tg.Set(tg.Get() is "0" or "" or "False" ? "1" : "0");
ChatLine($"[RynthAi] {name} = {tg.Get()}");
ReplyOk($"[RynthAi] {name} = {tg.Get()}");
}
_dashboard?.SaveSettings();
break;
default:
ChatLine("[RynthAi] Usage: /ub opt {list | get <option> | set <option> <newValue> | toggle <options>}");
ReplyFail("[RynthAi] Usage: /ub opt {list | get <option> | set <option> <newValue> | toggle <options>}");
break;
}
}
@ -319,12 +327,13 @@ public sealed partial class RynthAiPlugin
private void UbSimpleJump(string args)
{
int ms = int.TryParse(args, out int v) ? Math.Clamp(v, 0, 1000) : 0;
_jumper?.Start("", null, ms);
if (_jumper == null) { ReplyFail("[RynthAi] Jumper not ready (not logged in yet)."); return; }
if (_jumper.Start("", null, ms)) ReplyOk(JumpLine("", null, ms)); // a refusal says why itself
}
private void UbDumpSkills()
{
if (_charSkills == null) { ChatLine("[RynthAi] Skills not ready."); return; }
if (_charSkills == null) { ReplyFail("[RynthAi] Skills not ready."); return; }
var lines = new List<string>();
foreach (AcSkillType sk in Enum.GetValues<AcSkillType>())
{
@ -341,7 +350,7 @@ public sealed partial class RynthAiPlugin
private void UbQuests(string args)
{
var w = args.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries);
if (w.Length < 2 || !w[0].Equals("check", StringComparison.OrdinalIgnoreCase)) { ChatLine("[RynthAi] Usage: /ub quests check <questFlag>"); return; }
if (w.Length < 2 || !w[0].Equals("check", StringComparison.OrdinalIgnoreCase)) { ReplyFail("[RynthAi] Usage: /ub quests check <questFlag>"); return; }
string flag = w[1].Trim();
bool has = EvalExpr($"testquestflag[`{flag}`]") == "1";
string status = EvalExpr($"getqueststatus[`{flag}`]");
@ -356,15 +365,15 @@ public sealed partial class RynthAiPlugin
if (force) w.RemoveAt(w.Count - 1);
if (w.Count != 4 || !TryParseLandblock(w[0], out uint start) || !TryParseLandblock(w[2], out uint end))
{
ChatLine("[RynthAi] Usage: /ub translateroute <startLandblock> <routeToLoad> <endLandblock> <routeToSaveAs> [force]");
ReplyFail("[RynthAi] Usage: /ub translateroute <startLandblock> <routeToLoad> <endLandblock> <routeToSaveAs> [force]");
return;
}
string navFolder = System.IO.Path.Combine(RynthCore.Install.RynthInstallPaths.RynthAiDir, "NavProfiles");
string inPath = Path.IsPathRooted(w[1]) ? w[1] : Path.Combine(navFolder, w[1]);
string outPath = Path.IsPathRooted(w[3]) ? w[3] : Path.Combine(navFolder, w[3]);
if (!outPath.EndsWith(".nav", StringComparison.OrdinalIgnoreCase)) outPath += ".nav";
if (!File.Exists(inPath)) { ChatLine($"[RynthAi] Route not found: {inPath}"); return; }
if (File.Exists(outPath) && !force) { ChatLine($"[RynthAi] {Path.GetFileName(outPath)} exists; add force to overwrite."); return; }
if (!File.Exists(inPath)) { ReplyFail($"[RynthAi] Route not found: {inPath}"); return; }
if (File.Exists(outPath) && !force) { ReplyFail($"[RynthAi] {Path.GetFileName(outPath)} exists; add force to overwrite."); return; }
// A landblock is 192 m = 0.8 nav units. Landblock id: 0xXXYY.
double dEW = (((int)(end >> 8) & 0xFF) - ((int)(start >> 8) & 0xFF)) * 0.8;
@ -376,7 +385,7 @@ public sealed partial class RynthAiPlugin
if (p.Type is NavPointType.PortalNPC or NavPointType.Npc) { p.PortalExitNS += dNS; p.PortalExitEW += dEW; }
}
route.Save(outPath);
ChatLine($"[RynthAi] Translated {route.Points.Count} points to {Path.GetFileName(outPath)} (NS {dNS:+0.0;-0.0}, EW {dEW:+0.0;-0.0}).");
ReplyOk($"[RynthAi] Translated {route.Points.Count} points to {Path.GetFileName(outPath)} (NS {dNS:+0.0;-0.0}, EW {dEW:+0.0;-0.0}).");
}
private static bool TryParseLandblock(string s, out uint lb)

View file

@ -25,15 +25,24 @@ public sealed partial class RynthAiPlugin
var av = _autoVendor;
if (av == null)
{
ChatLine("[RynthAi] AutoVendor isn't ready yet (log in first).");
ReplyFail("[RynthAi] AutoVendor isn't ready yet (log in first).");
return true;
}
string rest = AfterWords(fullCommand, 2); // everything after "/ub <verb>"
// Run on the tick, they answer there as this line would have (typed: in chat; a meta's: quiet
// when it works). Every queued command says what it did, so the line itself is answered.
bool fromScript = Reply.FromScript;
void Queue(Action command)
{
Reply.Answered();
av.Enqueue(() => Reply.RunQueued(fromScript, command));
}
if (cmd == "autovendor")
{
av.Enqueue(() => av.CommandAutoVendor(rest));
Queue(() => av.CommandAutoVendor(rest));
return true;
}
@ -50,24 +59,24 @@ public sealed partial class RynthAiPlugin
switch (action)
{
case "buy":
case "buyall": av.Enqueue(av.CommandBuyAll); break;
case "buyall": Queue(av.CommandBuyAll); break;
case "sell":
case "sellall": av.Enqueue(av.CommandSellAll); break;
case "clearbuy": av.Enqueue(av.CommandClearBuy); break;
case "clearsell": av.Enqueue(av.CommandClearSell); break;
case "sellall": Queue(av.CommandSellAll); break;
case "clearbuy": Queue(av.CommandClearBuy); break;
case "clearsell": Queue(av.CommandClearSell); break;
// UB: "open" with no name picks the nearest vendor, like openp.
case "open": av.Enqueue(() => av.CommandOpen(args, partial: args.Length == 0)); break;
case "openp": av.Enqueue(() => av.CommandOpen(args, partial: true)); break;
case "opencancel": av.Enqueue(av.CommandOpenCancel); break;
case "open": Queue(() => av.CommandOpen(args, partial: args.Length == 0)); break;
case "openp": Queue(() => av.CommandOpen(args, partial: true)); break;
case "opencancel": Queue(av.CommandOpenCancel); break;
case "addbuy":
case "addbuyp":
if (args.Length == 0) { VendorUsage(); break; }
av.Enqueue(() => av.CommandAddBuy(args, partial: action == "addbuyp"));
Queue(() => av.CommandAddBuy(args, partial: action == "addbuyp"));
break;
case "addsell":
case "addsellp":
if (args.Length == 0) { VendorUsage(); break; }
av.Enqueue(() => av.CommandAddSell(args, partial: action == "addsellp"));
Queue(() => av.CommandAddSell(args, partial: action == "addsellp"));
break;
default:
VendorUsage();
@ -90,5 +99,5 @@ public sealed partial class RynthAiPlugin
}
private void VendorUsage()
=> ChatLine("[RynthAi] Usage: /ub vendor {open[p] <vendorname,vendorid,vendorhex> | buyall | sellall | clearbuy | clearsell | opencancel | addbuy[p] [count] <item> | addsell[p] [count] <item>}");
=> ReplyFail("[RynthAi] Usage: /ub vendor {open[p] <vendorname,vendorid,vendorhex> | buyall | sellall | clearbuy | clearsell | opencancel | addbuy[p] [count] <item> | addsell[p] [count] <item>}");
}

View file

@ -257,26 +257,34 @@ internal sealed class AutoVendorManager
}
if (!_host.HasVendorTrade) { SayNeedsUpdate(); return; }
Start(0, a, explicitCommand: true);
if (_phase != Phase.Idle)
Said($"started at {_vendorName} with {Path.GetFileName(_profilePath)}{(_settings.AutoVendorTestMode ? " (TestMode: nothing is bought or sold)" : "")}.");
}
public void CommandBuyAll()
{
if (!_host.HasVendorTrade) { SayNeedsUpdate(); return; }
if (_cart.BuyList.Count == 0) { Tool("buy list is empty"); return; }
int entries = _cart.BuyList.Count;
if (_cart.BuyAll(_host, _openVendorId) == 0)
Error($"buy refused: {TradeMessage()}");
else
Said($"buying the buy list ({entries} entr{(entries == 1 ? "y" : "ies")}).");
}
public void CommandSellAll()
{
if (!_host.HasVendorTrade) { SayNeedsUpdate(); return; }
if (_cart.SellList.Count == 0) { Tool("sell list is empty"); return; }
int items = _cart.SellList.Count;
if (_cart.SellAll(_host, _openVendorId) == 0)
Error($"sell refused: {TradeMessage()}");
else
Said($"selling the sell list ({items} item(s)).");
}
public void CommandClearBuy() => _cart.ClearBuy();
public void CommandClearSell() => _cart.ClearSell();
public void CommandClearBuy() { _cart.ClearBuy(); Said("buy list cleared."); }
public void CommandClearSell() { _cart.ClearSell(); Said("sell list cleared."); }
/// <summary>/ub vendor addbuy[p] [count] name</summary>
public void CommandAddBuy(string args, bool partial)
@ -347,14 +355,17 @@ internal sealed class AutoVendorManager
_opening = true;
if (_host.HasSetAutoRun) _host.SetAutoRunBy("Vendor", false);
_host.Log($"[RynthAi] AutoVendor: attempting to open vendor {vendor.Name}");
Said($"opening {vendor.Name}.");
}
/// <summary>/ub vendor opencancel</summary>
public void CommandOpenCancel()
{
bool was = _opening;
if (_opening) CancelUse();
_opening = false;
_openHoldUntil = 0;
Said(was ? $"stopped opening {_openTargetName}." : "no vendor was being opened.");
}
// ════════════════════════════════════════════════════════════════════════
@ -1587,6 +1598,16 @@ internal sealed class AutoVendorManager
private void Tool(string msg) => _host.WriteToChat($"[RynthAi] AutoVendor: {msg}", 1);
private void Error(string msg) => _host.WriteToChat($"[RynthAi] AutoVendor: {msg}", 2);
/// <summary>The plugin's command replies (CommandReply.cs): a /ub vendor command answers by them.</summary>
internal CommandReply? Reply { get; set; }
/// <summary>A /ub vendor or /ub autovendor command worked: said when typed, only logged when a meta sent it.</summary>
private void Said(string msg)
{
if (Reply is { } r) r.Ok($"[RynthAi] AutoVendor: {msg}");
else Tool(msg);
}
/// <summary>UB Util.ThinkOrWrite: a /tell to yourself when Think is on (metas watch for it).</summary>
private void ThinkOrWrite(string msg)
{

View file

@ -0,0 +1,326 @@
// ============================================================================
// RynthDefective - Corpses/CorpseBook.cs
// Where a character's corpses are (Tom 2026-10-23: "a small panel somewhere
// that tells you where all your corpses are"). Pure: the plugin feeds it what
// it sees (RynthDefectivePlugin.Corpses.cs), tests feed it directly.
//
// What tells it:
// the death health 0: where the player stands is where the corpse lies
// (ACE puts it at the player's position).
// the server "Your corpse is located at (12.3N, 45.6E)." (ACE, outdoor deaths
// that dropped something) confirms it; "You have retained all your
// items. You do not need to recover your corpse!" means there is
// nothing to go back for, so that death is dropped. Either line
// may come before or after the health reaches 0.
// the corpse an object named "Corpse of <name>" in view: its id and exact
// place, matched to a death nearby or added as a corpse found.
// it's gone it left view (the server deletes it from the client) and
// VanishMeansGone says so: you had opened it (an emptied corpse
// rots 15 s later), or it was due to rot, or it went from right
// beside you. Otherwise it only left view (in a dungeon, around a
// corner: ACE drops what you can't see after about 25 s) and stays.
// not there you stand where it should be and it isn't (10 s, not in the
// first 2 minutes after the death, while the corpse appears).
//
// How long one lasts (ACE's Corpse.RecalculateDecayTime): a player's corpse rots
// after the player's level times 5 minutes, at least an hour; an emptied one 15
// seconds after. Other servers may differ, so the time is an estimate and a
// corpse is only dropped 10 minutes after it.
// ============================================================================
using System;
using System.Collections.Generic;
namespace RynthCore.Plugin.RynthDefective.Corpses;
/// <summary>One corpse: where, when the character died (or the corpse was found), when it rots.</summary>
internal sealed class CorpseRecord
{
/// <summary>When the character died; MinValue for a corpse found in the world with no death seen.</summary>
public DateTime DiedUtc;
/// <summary>When it should rot (an estimate); MinValue when unknown.</summary>
public DateTime RotsUtc;
/// <summary>The landcell and the position in it; Cell 0 when only the server's map coordinates are known.</summary>
public uint Cell;
public float X, Y, Z;
/// <summary>The server's map coordinates (outdoor deaths); otherwise worked out from Cell.</summary>
public double Ns, Ew;
public bool ServerCoords;
/// <summary>The corpse object, once seen (0 before).</summary>
public uint ObjectId;
public DateTime SeenUtc;
/// <summary>When the player last opened it (not saved: only the minutes after matter).</summary>
public DateTime OpenedUtc;
/// <summary>Since when the player has stood at its place without it there (not saved).</summary>
public DateTime AbsentSinceUtc;
public bool Indoors => Cell != 0 && (Cell & 0xFFFF) >= 0x100;
public uint Landblock => Cell >> 16;
/// <summary>The map coordinates: the server's, else from the landcell (meaningless in a dungeon).</summary>
public bool TryCoords(out double ns, out double ew)
{
if (ServerCoords) { ns = Ns; ew = Ew; return true; }
return CorpseBook.MapCoords(Cell, X, Y, out ns, out ew);
}
}
internal sealed class CorpseBook
{
public const int MaxCorpses = 20;
/// <summary>A death and the server's lines about it arrive within this of each other.</summary>
public static readonly TimeSpan DeathWindow = TimeSpan.FromMinutes(2);
/// <summary>A corpse is dropped this long after its estimated rot time.</summary>
public static readonly TimeSpan RotGrace = TimeSpan.FromMinutes(10);
/// <summary>A corpse with no rot estimate is dropped this long after it was last known.</summary>
public static readonly TimeSpan UnknownKeep = TimeSpan.FromHours(48);
private readonly List<CorpseRecord> _list = new();
private DateTime _nothingDroppedUtc = DateTime.MinValue;
public IReadOnlyList<CorpseRecord> Corpses => _list;
/// <summary>Bumped on every change (the plugin saves and redraws on it).</summary>
public int Revision { get; private set; }
public void Load(IEnumerable<CorpseRecord> records)
{
_list.Clear();
_list.AddRange(records);
Trim();
Revision++;
}
/// <summary>ACE's rot time for a player's corpse: level x 5 minutes, at least an hour (level 0: unknown).</summary>
public static DateTime RotTime(DateTime diedUtc, int level) =>
level <= 0 ? DateTime.MinValue : diedUtc + TimeSpan.FromSeconds(Math.Max(3600, level * 300));
/// <summary>
/// The character's health reached 0 at this place. The server's corpse line may already have come
/// (then this fills in the exact place), or "nothing to recover" (then there's no corpse to note).
/// </summary>
public void Died(DateTime now, uint cell, float x, float y, float z, int level)
{
if (now - _nothingDroppedUtc < DeathWindow) return;
CorpseRecord? recent = Recent(now);
if (recent != null && recent.Cell == 0)
{
recent.Cell = cell; recent.X = x; recent.Y = y; recent.Z = z;
Changed();
return;
}
Add(new CorpseRecord { DiedUtc = now, RotsUtc = RotTime(now, level), Cell = cell, X = x, Y = y, Z = z });
}
/// <summary>"Your corpse is located at (ns, ew)." The latest death, or a death the health didn't show.</summary>
public void ServerLine(DateTime now, double ns, double ew, int level)
{
CorpseRecord? recent = Recent(now);
if (recent != null)
{
recent.Ns = ns; recent.Ew = ew; recent.ServerCoords = true;
Changed();
return;
}
Add(new CorpseRecord { DiedUtc = now, RotsUtc = RotTime(now, level), Ns = ns, Ew = ew, ServerCoords = true });
}
/// <summary>"You do not need to recover your corpse": that death left nothing behind.</summary>
public void NothingDropped(DateTime now)
{
_nothingDroppedUtc = now;
CorpseRecord? recent = Recent(now);
if (recent != null && recent.ObjectId == 0)
{
_list.Remove(recent);
Changed();
}
}
/// <summary>
/// "Corpse of &lt;name&gt;" is in view: the corpse it is (by id, else the nearest death in the same
/// place), or one found. Returns the record.
/// </summary>
public CorpseRecord Seen(DateTime now, uint objectId, uint cell, float x, float y, float z)
{
CorpseRecord? hit = null;
foreach (CorpseRecord c in _list)
if (c.ObjectId == objectId) { hit = c; break; }
if (hit == null)
{
double best = double.MaxValue;
foreach (CorpseRecord c in _list)
{
if (c.ObjectId != 0) continue;
double d = Distance(c, cell, x, y, z);
if (d <= (c.Cell != 0 ? MatchDistance : MatchDistanceCoords) && d < best) { best = d; hit = c; }
}
}
if (hit == null)
{
hit = new CorpseRecord
{
DiedUtc = DateTime.MinValue, RotsUtc = DateTime.MinValue,
ObjectId = objectId, Cell = cell, X = x, Y = y, Z = z, SeenUtc = now,
};
Add(hit);
return hit;
}
bool moved = hit.ObjectId != objectId || hit.Cell != cell || MathF.Abs(hit.X - x) > 0.5f || MathF.Abs(hit.Y - y) > 0.5f;
hit.ObjectId = objectId;
hit.Cell = cell; hit.X = x; hit.Y = y; hit.Z = z;
hit.SeenUtc = now;
if (moved) Changed();
return hit;
}
/// <summary>The player opened a corpse (its contents came): if it's one of these, noted.</summary>
public void Opened(uint objectId, DateTime now)
{
foreach (CorpseRecord c in _list)
if (c.ObjectId == objectId) { c.OpenedUtc = now; return; }
}
/// <summary>Opened this recently, its vanishing is the looting (an emptied corpse rots 15 s later).</summary>
public static readonly TimeSpan LootedWindow = TimeSpan.FromMinutes(15);
/// <summary>Vanishing this close to the player can't be leaving view.</summary>
public const double BesideYou = 10.0;
/// <summary>
/// The corpse left view while the player was <paramref name="distance"/> metres off: gone for good
/// (looted, rotted), or only out of sight? Pure.
/// </summary>
public static bool VanishMeansGone(CorpseRecord c, double distance, DateTime now)
{
if (c.OpenedUtc != DateTime.MinValue && now - c.OpenedUtc < LootedWindow) return true;
if (c.RotsUtc != DateTime.MinValue && now >= c.RotsUtc - TimeSpan.FromMinutes(5)) return true;
return distance <= BesideYou;
}
/// <summary>Standing at its place without it there this long: it's gone.</summary>
public static readonly TimeSpan AbsentFor = TimeSpan.FromSeconds(10);
/// <summary>
/// The player is <paramref name="distance"/> metres from it and it is (or isn't) in view: true when
/// it has been missing from its place long enough to drop. Not in the first <see cref="DeathWindow"/>
/// after the death (the corpse appears a moment after it). Pure but for the record's timer.
/// </summary>
public static bool NotThere(CorpseRecord c, double distance, bool inView, DateTime now)
{
if (inView || distance > BesideYou || (c.DiedUtc != DateTime.MinValue && now - c.DiedUtc < DeathWindow))
{
c.AbsentSinceUtc = DateTime.MinValue;
return false;
}
if (c.AbsentSinceUtc == DateTime.MinValue) c.AbsentSinceUtc = now;
return now - c.AbsentSinceUtc >= AbsentFor;
}
/// <summary>The corpse object is gone for good (looted and rotted, or rotted).</summary>
public bool Gone(uint objectId)
{
int i = _list.FindIndex(c => c.ObjectId == objectId);
if (i < 0) return false;
_list.RemoveAt(i);
Changed();
return true;
}
public bool Forget(CorpseRecord record)
{
if (!_list.Remove(record)) return false;
Changed();
return true;
}
public void Clear()
{
if (_list.Count == 0) return;
_list.Clear();
Changed();
}
/// <summary>Drops the corpses that should have rotted by now. True when any went.</summary>
public bool Expire(DateTime now)
{
int n = _list.RemoveAll(c => Expired(c, now));
if (n > 0) Changed();
return n > 0;
}
public static bool Expired(CorpseRecord c, DateTime now)
{
if (c.RotsUtc != DateTime.MinValue) return now > c.RotsUtc + RotGrace;
DateTime known = c.DiedUtc > c.SeenUtc ? c.DiedUtc : c.SeenUtc;
return known != DateTime.MinValue && now > known + UnknownKeep;
}
/// <summary>
/// Within this (metres) a corpse seen is the death noted there: ACE drops it where the player
/// stood, so only a knockback in the dying moment separates them. With only the server's map
/// coordinates (rounded to a tenth, 24 m) the second, wider one.
/// </summary>
public const double MatchDistance = 15.0, MatchDistanceCoords = 25.0;
/// <summary>Metres between a corpse and a place; +inf when they can't be compared (another dungeon).</summary>
public static double Distance(CorpseRecord c, uint cell, float x, float y, float z)
{
if (c.Cell != 0)
{
bool aIn = c.Indoors, bIn = (cell & 0xFFFF) >= 0x100;
// Two dungeon places compare only in the same landblock (dungeons share no space).
if ((aIn || bIn) && c.Landblock != (cell >> 16)) return double.PositiveInfinity;
double dx = Global(c.Cell, c.X, true) - Global(cell, x, true);
double dy = Global(c.Cell, c.Y, false) - Global(cell, y, false);
double dz = c.Z - z;
return Math.Sqrt(dx * dx + dy * dy + dz * dz);
}
if (!c.ServerCoords || (cell & 0xFFFF) >= 0x100 || !MapCoords(cell, x, y, out double ns, out double ew))
return double.PositiveInfinity;
// Map coordinates: a tenth of a unit is 24 metres.
double dn = (c.Ns - ns) * 240.0, de = (c.Ew - ew) * 240.0;
return Math.Sqrt(dn * dn + de * de);
}
/// <summary>A landcell coordinate as a world one: 192 metres a landblock (the cell's high bytes).</summary>
public static double Global(uint cell, float local, bool x) =>
((x ? cell >> 24 : cell >> 16) & 0xFF) * 192.0 + local;
/// <summary>The map coordinates of a landcell position (the radar's formula: 0.1 = 24 metres).</summary>
public static bool MapCoords(uint cell, float x, float y, out double ns, out double ew)
{
ns = ew = 0;
if ((cell >> 16) == 0) return false;
ew = (((cell >> 24) & 0xFF) * 8.0 + x / 24.0 - 1019.5) / 10.0;
ns = (((cell >> 16) & 0xFF) * 8.0 + y / 24.0 - 1019.5) / 10.0;
return true;
}
/// <summary>The last death, if it was just now (the server's lines belong to it).</summary>
private CorpseRecord? Recent(DateTime now)
{
CorpseRecord? last = null;
foreach (CorpseRecord c in _list)
if (c.DiedUtc != DateTime.MinValue && now - c.DiedUtc < DeathWindow && (last == null || c.DiedUtc > last.DiedUtc))
last = c;
return last;
}
private void Add(CorpseRecord c)
{
_list.Add(c);
Trim();
Changed();
}
/// <summary>The newest first (by the death, or when a found one was first seen); at most <see cref="MaxCorpses"/>.</summary>
private void Trim()
{
_list.Sort((a, b) => When(b).CompareTo(When(a)));
if (_list.Count > MaxCorpses) _list.RemoveRange(MaxCorpses, _list.Count - MaxCorpses);
}
private static DateTime When(CorpseRecord c) => c.DiedUtc != DateTime.MinValue ? c.DiedUtc : c.SeenUtc;
private void Changed() => Revision++;
}

View file

@ -0,0 +1,35 @@
// ============================================================================
// RynthDefective - Corpses/CorpseLines.cs
// The server's two lines about a death's corpse (ACE, Creature_Death):
// "Your corpse is located at (12.3N, 45.6E)." outdoor deaths that dropped something
// "You have retained all your items. You do not need to recover your corpse!"
// Pure.
// ============================================================================
using System;
using System.Globalization;
using System.Text.RegularExpressions;
namespace RynthCore.Plugin.RynthDefective.Corpses;
internal static class CorpseLines
{
private static readonly Regex Located = new(
@"Your corpse is located at \(\s*(\d+(?:\.\d+)?)\s*([NS])\s*,\s*(\d+(?:\.\d+)?)\s*([EW])\s*\)",
RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
public static bool IsCorpseLine(string text) => Located.IsMatch(text) || IsNothingDropped(text);
public static bool IsNothingDropped(string text) =>
text.IndexOf("You do not need to recover your corpse", StringComparison.OrdinalIgnoreCase) >= 0;
public static bool TryLocated(string text, out double ns, out double ew)
{
ns = ew = 0;
Match m = Located.Match(text);
if (!m.Success) return false;
ns = double.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture) * (m.Groups[2].Value.Equals("S", StringComparison.OrdinalIgnoreCase) ? -1 : 1);
ew = double.Parse(m.Groups[3].Value, CultureInfo.InvariantCulture) * (m.Groups[4].Value.Equals("W", StringComparison.OrdinalIgnoreCase) ? -1 : 1);
return true;
}
}

View file

@ -0,0 +1,173 @@
// ============================================================================
// RynthDefective - Corpses/CorpseRows.cs
// The Corpses window's rows, built on the plugin tick from the book, the other
// characters' files and where the player stands. Pure (tests build rows).
//
// A row: the place (the dungeon's name, or the map coordinates outdoors), then
// how long ago, the rot estimate and, when the player can be measured against
// it (outdoors, or in the same dungeon), how far and which way, with an arrow
// from where the player faces.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
namespace RynthCore.Plugin.RynthDefective.Corpses;
internal sealed record CorpseRow(
string Place,
string Detail,
string Tip,
float Relative, // degrees from where the player faces (0 ahead, + to the right); NaN = no arrow
CorpseRecord? Record, // this character's corpse (click: select it; X: forget it); null for another character's
uint ObjectId);
internal sealed record CorpsesView(bool Ready, IReadOnlyList<CorpseRow> Mine, IReadOnlyList<CorpseRow> Others)
{
public static readonly CorpsesView NotReady = new(false, Array.Empty<CorpseRow>(), Array.Empty<CorpseRow>());
}
/// <summary>Where the player is, for distances and the arrow (Cell 0 = unknown).</summary>
internal readonly record struct PlayerSpot(uint Cell, float X, float Y, float Z, double FacingDeg);
internal static class CorpseRows
{
/// <summary>Beyond this (metres) a corpse gets no distance: the map coordinates say it better.</summary>
public const double MaxShownDistance = 5000;
public static CorpsesView Build(IReadOnlyList<CorpseRecord> mine, IReadOnlyList<OtherCorpses> others, PlayerSpot me, DateTime now)
{
var rows = new List<CorpseRow>(mine.Count);
foreach (CorpseRecord c in mine)
{
float rel = float.NaN;
var detail = new List<string>(3) { Age(c, now) };
string rot = Rot(c, now);
if (rot.Length > 0) detail.Add(rot);
if (Offset(c, me, out double dist, out double bearing))
{
detail.Add(Distance(dist) + " " + Compass(bearing));
if (dist >= 1.0)
{
double r = bearing - me.FacingDeg;
while (r > 180) r -= 360;
while (r < -180) r += 360;
rel = (float)r;
}
}
rows.Add(new CorpseRow(Place(c), string.Join(" · ", detail), Tip(c, null, now), rel, c, c.ObjectId));
}
var other = new List<CorpseRow>();
foreach (OtherCorpses o in others)
foreach (CorpseRecord c in o.Corpses)
{
string rot = Rot(c, now);
string detail = o.Character + " · " + Age(c, now) + (rot.Length > 0 ? " · " + rot : "");
other.Add(new CorpseRow(Place(c), detail, Tip(c, o, now), float.NaN, null, 0));
}
return new CorpsesView(true, rows, other);
}
/// <summary>"Matron Hive East", "41.2N, 33.6E", "41.2N, 33.6E (indoors)", "Dungeon 6146".</summary>
public static string Place(CorpseRecord c)
{
if (c.Indoors)
{
PlaceNames.Dungeon? d = PlaceNames.DungeonAt(c.Landblock);
if (d != null) return d.Name;
if (PlaceNames.IsMapLandblock(c.Landblock) && c.TryCoords(out double bns, out double bew)) return Coords(bns, bew) + " (indoors)";
return "Dungeon " + c.Landblock.ToString("X4", CultureInfo.InvariantCulture);
}
return c.TryCoords(out double ns, out double ew) ? Coords(ns, ew) : "Somewhere";
}
public static string Coords(double ns, double ew) =>
Math.Abs(ns).ToString("0.0", CultureInfo.InvariantCulture) + (ns >= 0 ? "N" : "S") + ", "
+ Math.Abs(ew).ToString("0.0", CultureInfo.InvariantCulture) + (ew >= 0 ? "E" : "W");
/// <summary>"died 25m ago", "found 3m ago" (a corpse seen with no death seen).</summary>
public static string Age(CorpseRecord c, DateTime now) =>
c.DiedUtc != DateTime.MinValue ? "died " + Span(now - c.DiedUtc) + " ago"
: c.SeenUtc != DateTime.MinValue ? "seen " + Span(now - c.SeenUtc) + " ago" : "";
/// <summary>"rots in ~2h 5m", "may have rotted", or "" when unknown.</summary>
public static string Rot(CorpseRecord c, DateTime now)
{
if (c.RotsUtc == DateTime.MinValue) return "";
TimeSpan left = c.RotsUtc - now;
return left > TimeSpan.Zero ? "rots in ~" + Span(left) : "may have rotted";
}
/// <summary>"40s", "25m", "3h 10m", "2d 4h".</summary>
public static string Span(TimeSpan t)
{
if (t < TimeSpan.Zero) t = TimeSpan.Zero;
if (t.TotalMinutes < 1) return ((int)t.TotalSeconds).ToString(CultureInfo.InvariantCulture) + "s";
if (t.TotalHours < 1) return ((int)t.TotalMinutes).ToString(CultureInfo.InvariantCulture) + "m";
if (t.TotalDays < 1) return ((int)t.TotalHours).ToString(CultureInfo.InvariantCulture) + "h " + t.Minutes.ToString(CultureInfo.InvariantCulture) + "m";
return ((int)t.TotalDays).ToString(CultureInfo.InvariantCulture) + "d " + t.Hours.ToString(CultureInfo.InvariantCulture) + "h";
}
public static string Distance(double metres) =>
metres < 10 ? metres.ToString("0.0", CultureInfo.InvariantCulture) + " yd"
: metres.ToString("N0", CultureInfo.InvariantCulture) + " yd";
private static readonly string[] Points = { "N", "NE", "E", "SE", "S", "SW", "W", "NW" };
public static string Compass(double bearing) => Points[(int)Math.Round(((bearing % 360) + 360) % 360 / 45.0) % 8];
/// <summary>How far and which way (degrees clockwise from north) the corpse is from the player, when they can be compared.</summary>
public static bool Offset(CorpseRecord c, PlayerSpot me, out double dist, out double bearing)
{
dist = bearing = 0;
if (me.Cell == 0) return false;
double dx, dy, dz = 0;
if (c.Cell != 0)
{
bool aIn = c.Indoors, bIn = (me.Cell & 0xFFFF) >= 0x100;
if ((aIn || bIn) && c.Landblock != (me.Cell >> 16)) return false;
dx = CorpseBook.Global(c.Cell, c.X, true) - CorpseBook.Global(me.Cell, me.X, true);
dy = CorpseBook.Global(c.Cell, c.Y, false) - CorpseBook.Global(me.Cell, me.Y, false);
dz = c.Z - me.Z;
}
else
{
if (!c.ServerCoords || (me.Cell & 0xFFFF) >= 0x100 || !CorpseBook.MapCoords(me.Cell, me.X, me.Y, out double ns, out double ew))
return false;
dx = (c.Ew - ew) * 240.0;
dy = (c.Ns - ns) * 240.0;
}
dist = Math.Sqrt(dx * dx + dy * dy + dz * dz);
if (dist > MaxShownDistance) return false;
bearing = Math.Atan2(dx, dy) * 180.0 / Math.PI;
if (bearing < 0) bearing += 360.0;
return true;
}
private static string Tip(CorpseRecord c, OtherCorpses? owner, DateTime now)
{
var sb = new StringBuilder();
if (owner != null) sb.Append(owner.Character).Append(owner.Server.Length > 0 ? " on " + owner.Server : "").Append('\n');
if (c.DiedUtc != DateTime.MinValue)
sb.Append("Died ").Append(c.DiedUtc.ToLocalTime().ToString("MMM d, h:mm tt", CultureInfo.InvariantCulture))
.Append(" (").Append(Span(now - c.DiedUtc)).Append(" ago)").Append('\n');
else if (c.SeenUtc != DateTime.MinValue)
sb.Append("Found in the world (no death seen); last seen ").Append(Span(now - c.SeenUtc)).Append(" ago").Append('\n');
if (c.RotsUtc != DateTime.MinValue)
sb.Append(c.RotsUtc > now ? "Should rot in about " + Span(c.RotsUtc - now) : "Should have rotted by now")
.Append(" (level x 5 min, at least an hour; emptied, 15 s)").Append('\n');
PlaceNames.Dungeon? d = c.Indoors ? PlaceNames.DungeonAt(c.Landblock) : null;
sb.Append("Where: ").Append(Place(c));
if (c.Cell != 0)
sb.Append(" - landblock ").Append((c.Cell >> 16).ToString("X4", CultureInfo.InvariantCulture))
.Append(", cell ").Append((c.Cell & 0xFFFF).ToString("X4", CultureInfo.InvariantCulture))
.Append(" (").Append(c.X.ToString("0.0", CultureInfo.InvariantCulture)).Append(", ")
.Append(c.Y.ToString("0.0", CultureInfo.InvariantCulture)).Append(", ")
.Append(c.Z.ToString("0.0", CultureInfo.InvariantCulture)).Append(')');
if (d != null && d.HasEntrance) sb.Append("\nEntrance: ").Append(Coords(d.Ns, d.Ew));
if (owner == null)
sb.Append(c.ObjectId != 0 ? "\nClick: select it (when it's in view). X: forget it." : "\nX: forget it.");
return sb.ToString();
}
}

View file

@ -0,0 +1,165 @@
// ============================================================================
// RynthDefective - Corpses/CorpseStore.cs
// The corpses, one file per character: <SuiteDir>\RynthDefective\corpses\
// <server_character>.json. Each client writes only its own character's file
// and reads the others' (the window lists every character's corpses on this
// PC), so clients never write the same file. Written by hand and read with
// JsonDocument, as DefStore does; a broken file reads as no corpses.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.Json;
using RynthCore.Plugin.RynthDefective.Model;
namespace RynthCore.Plugin.RynthDefective.Corpses;
/// <summary>Another character's corpses, as its file has them.</summary>
internal sealed record OtherCorpses(string Server, string Character, IReadOnlyList<CorpseRecord> Corpses);
internal sealed class CorpseStore
{
public string Root;
public CorpseStore(string defectiveRoot) => Root = Path.Combine(defectiveRoot, "corpses");
public string PathFor(string server, string character) => Path.Combine(Root, DefStore.FileStem(server, character) + ".json");
public List<CorpseRecord> Load(string server, string character, out string? problem)
{
problem = null;
string path = PathFor(server, character);
if (!File.Exists(path)) return new List<CorpseRecord>();
try
{
return Parse(File.ReadAllBytes(path), out _, out _);
}
catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException or InvalidOperationException or FormatException)
{
problem = $"{Path.GetFileName(path)}: {ex.Message}";
return new List<CorpseRecord>();
}
}
public string? Save(string server, string character, IReadOnlyList<CorpseRecord> corpses)
{
string path = PathFor(server, character);
try
{
Directory.CreateDirectory(Root);
string tmp = path + "." + Environment.ProcessId.ToString(CultureInfo.InvariantCulture) + ".tmp";
File.WriteAllText(tmp, ToJson(server, character, corpses), new UTF8Encoding(false));
File.Move(tmp, path, overwrite: true);
return null;
}
catch (Exception ex)
{
return ex.Message;
}
}
/// <summary>Every other character's corpses that haven't rotted (files that can't be read are skipped).</summary>
public List<OtherCorpses> LoadOthers(string server, string character, DateTime now)
{
var result = new List<OtherCorpses>();
if (!Directory.Exists(Root)) return result;
string own = Path.GetFullPath(PathFor(server, character));
foreach (string path in Directory.EnumerateFiles(Root, "*.json"))
{
if (string.Equals(Path.GetFullPath(path), own, StringComparison.OrdinalIgnoreCase)) continue;
try
{
List<CorpseRecord> list = Parse(File.ReadAllBytes(path), out string sv, out string ch);
list.RemoveAll(c => CorpseBook.Expired(c, now));
if (list.Count > 0 && ch.Length > 0) result.Add(new OtherCorpses(sv, ch, list));
}
catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException or InvalidOperationException or FormatException)
{
}
}
result.Sort((a, b) => string.Compare(a.Character, b.Character, StringComparison.OrdinalIgnoreCase));
return result;
}
internal static string ToJson(string server, string character, IReadOnlyList<CorpseRecord> corpses)
{
using var ms = new MemoryStream();
using (var w = new Utf8JsonWriter(ms, new JsonWriterOptions { Indented = true }))
{
w.WriteStartObject();
w.WriteNumber("version", 1);
w.WriteString("server", server);
w.WriteString("character", character);
w.WriteStartArray("corpses");
foreach (CorpseRecord c in corpses)
{
w.WriteStartObject();
if (c.DiedUtc != DateTime.MinValue) w.WriteString("died", c.DiedUtc.ToString("o", CultureInfo.InvariantCulture));
if (c.RotsUtc != DateTime.MinValue) w.WriteString("rots", c.RotsUtc.ToString("o", CultureInfo.InvariantCulture));
if (c.SeenUtc != DateTime.MinValue) w.WriteString("seen", c.SeenUtc.ToString("o", CultureInfo.InvariantCulture));
if (c.Cell != 0)
{
w.WriteString("cell", c.Cell.ToString("X8", CultureInfo.InvariantCulture));
w.WriteNumber("x", Math.Round(c.X, 2));
w.WriteNumber("y", Math.Round(c.Y, 2));
w.WriteNumber("z", Math.Round(c.Z, 2));
}
if (c.ServerCoords)
{
w.WriteNumber("ns", c.Ns);
w.WriteNumber("ew", c.Ew);
}
if (c.ObjectId != 0) w.WriteString("id", c.ObjectId.ToString("X8", CultureInfo.InvariantCulture));
w.WriteEndObject();
}
w.WriteEndArray();
w.WriteEndObject();
}
return Encoding.UTF8.GetString(ms.ToArray());
}
internal static List<CorpseRecord> Parse(byte[] json, out string server, out string character)
{
using JsonDocument doc = JsonDocument.Parse(json, new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip });
JsonElement root = doc.RootElement;
if (root.ValueKind != JsonValueKind.Object) throw new JsonException("the file isn't a JSON object");
server = Str(root, "server");
character = Str(root, "character");
var list = new List<CorpseRecord>();
if (!root.TryGetProperty("corpses", out JsonElement arr) || arr.ValueKind != JsonValueKind.Array) return list;
foreach (JsonElement e in arr.EnumerateArray())
{
if (e.ValueKind != JsonValueKind.Object) continue;
var c = new CorpseRecord
{
DiedUtc = Time(e, "died"), RotsUtc = Time(e, "rots"), SeenUtc = Time(e, "seen"),
Cell = Hex(e, "cell"), X = (float)Num(e, "x"), Y = (float)Num(e, "y"), Z = (float)Num(e, "z"),
ObjectId = Hex(e, "id"),
};
if (e.TryGetProperty("ns", out JsonElement ns) && ns.ValueKind == JsonValueKind.Number
&& e.TryGetProperty("ew", out JsonElement ew) && ew.ValueKind == JsonValueKind.Number)
{
c.Ns = ns.GetDouble(); c.Ew = ew.GetDouble(); c.ServerCoords = true;
}
if (c.Cell == 0 && !c.ServerCoords) continue; // nowhere
list.Add(c);
}
return list;
}
private static string Str(JsonElement e, string name) =>
e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : "";
private static double Num(JsonElement e, string name) =>
e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number ? v.GetDouble() : 0;
private static uint Hex(JsonElement e, string name) =>
uint.TryParse(Str(e, name), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint v) ? v : 0;
private static DateTime Time(JsonElement e, string name) =>
DateTime.TryParse(Str(e, name), CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out DateTime t)
? t.ToUniversalTime() : DateTime.MinValue;
}

View file

@ -0,0 +1,200 @@
// ============================================================================
// RynthDefective - Corpses/CorpsesWindow.cs
// Where your corpses are (Tom 2026-10-23): this character's, newest first,
// then your other characters' on this PC. A small frameless window in the
// Selection window's look (RynthCore hosts it, plugin API v90).
//
// the title row drag to move; Ctrl+wheel: bigger or smaller (30-250%);
// right-click: hide it (/rdef corpses, the bar button).
// a row the place, then how long ago, when it rots and, near it,
// how far and which way (the arrow is from where you face).
// Click: select the corpse when it's in view; X: forget it.
//
// AC's render thread; reads the view the tick built (CorpsesView).
// ============================================================================
using System;
using System.Globalization;
using System.Numerics;
using ImGuiNET;
using RynthCore.Plugin.RynthDefective.ShortcutBar;
using RynthCore.Plugin.Shared;
using RynthCore.Plugin.Shared.RynthUi;
using RynthCore.PluginSdk;
using static RynthCore.Plugin.Shared.RynthUi.RynthUi;
namespace RynthCore.Plugin.RynthDefective.Corpses;
internal sealed class CorpsesWindow
{
public const string Title = "Corpses";
private readonly RynthCoreHost _host;
private readonly Action<CorpseRow> _select, _forget;
private float _k = 1f, _r = 1f;
public CorpsesWindow(RynthCoreHost host, Action<CorpseRow> select, Action<CorpseRow> forget)
{
_host = host;
_select = select;
_forget = forget;
}
private float Px(float v) => v * _k;
private float Fs(ImFontPtr f) => f.FontSize * _r;
private void Scale()
{
float fontK = Math.Max(0.5f, Font(RynthUiFont.Ui10).FontSize / 10f);
int pct = _host.PanelScale(Title);
_k = pct > 0 ? pct / 100f : fontK;
_r = _k / fontK;
}
private const float Pad = 6, HeadH = 18, RowH = 30, Radius = 4, Mark = 14, XW = 16;
private uint _bg, _key, _inset, _line, _text, _dim, _faint, _accent;
private static uint A(uint c, float alpha) => WithAlpha(c, (uint)Math.Clamp(MathF.Round(alpha * 255f), 0f, 255f));
/// <summary>Draws the corpses into the host's window; returns the height it needs (pixels). Render thread.</summary>
public float Draw(CorpsesView v)
{
Scale();
_bg = Color(RynthUiColor.Background);
_key = Color(RynthUiColor.KeyFace);
_inset = Color(RynthUiColor.Inset);
_line = Color(RynthUiColor.Hairline);
_text = Color(RynthUiColor.Text);
_dim = Color(RynthUiColor.Muted);
_faint = Color(RynthUiColor.Faint);
_accent = Color(RynthUiColor.Accent);
Vector2 origin = ImGui.GetCursorScreenPos();
origin = new Vector2(MathF.Round(origin.X), MathF.Round(origin.Y));
float width = MathF.Floor(ImGui.GetContentRegionAvail().X);
if (width < 40) return Px(40);
ImDrawListPtr dl = ImGui.GetWindowDrawList();
float pad = Px(Pad), rowH = Px(RowH), headH = Px(HeadH);
int empty = v.Mine.Count == 0 && v.Others.Count == 0 ? 1 : 0;
float height = MathF.Ceiling(pad + headH + (v.Mine.Count + empty) * rowH
+ (v.Others.Count > 0 ? headH + v.Others.Count * rowH : 0) + pad * 0.5f);
Vector2 max = origin + new Vector2(width, height);
dl.AddRectFilled(origin, max, A(_bg, 0.94f), Px(Radius));
dl.AddRect(origin, max, _line, Px(Radius));
// The title row: the drag surface.
float y = origin.Y + pad * 0.5f;
ImGui.SetCursorScreenPos(new Vector2(origin.X, origin.Y));
ImGui.InvisibleButton("##corpses_drag", new Vector2(width, headH + pad * 0.5f));
_host.PanelDragWithLastItem();
if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) _host.SetPanelOpen(Title, RynthPanelOpen.Close);
SafeImGui.SetItemTooltip("Where your corpses are: this character's, then your other characters' on this PC.\n"
+ "Drag to move; Ctrl+wheel: bigger or smaller; right-click: hide (/rdef corpses).");
PanelButtonsWindow.DrawIcon(dl, RynthIcons.Skull, new Vector2(origin.X + pad, y), new Vector2(Px(Mark), headH), Px(12), _dim);
ImFontPtr hf = Font(RynthUiFont.NarrowBold11), sf = Font(RynthUiFont.Narrow9), nf = Font(RynthUiFont.Narrow10);
float tx = origin.X + pad + Px(Mark) + Px(4);
dl.AddText(hf, Fs(hf), new Vector2(tx, MathF.Round(y + (headH - Fs(hf)) * 0.5f)), _dim, "CORPSES");
if (v.Ready)
{
string count = v.Mine.Count.ToString(CultureInfo.InvariantCulture);
float cw = sf.CalcTextSizeA(Fs(sf), float.MaxValue, 0f, count).X;
dl.AddText(sf, Fs(sf), new Vector2(origin.X + width - pad - cw, MathF.Round(y + (headH - Fs(sf)) * 0.5f)), _faint, count);
}
y += headH;
if (empty == 1)
{
dl.AddLine(new Vector2(origin.X + pad, y), new Vector2(origin.X + width - pad, y), _line);
string msg = v.Ready ? "No corpses. Where you die shows here." : "Corpses";
Clip(dl, sf, Fs(sf), new Vector2(origin.X + pad, MathF.Round(y + (rowH - Fs(sf)) * 0.5f)), _faint, msg, width - 2 * pad);
}
for (int i = 0; i < v.Mine.Count; i++)
{
Row(dl, v.Mine[i], i, new Vector2(origin.X, y), width, rowH, nf, sf, mine: true);
y += rowH;
}
if (v.Others.Count > 0)
{
dl.AddLine(new Vector2(origin.X + pad, y + 0.5f), new Vector2(origin.X + width - pad, y + 0.5f), _line);
dl.AddText(sf, Fs(sf), new Vector2(origin.X + pad, MathF.Round(y + (headH - Fs(sf)) * 0.5f)), _faint, "OTHER CHARACTERS");
y += headH;
for (int i = 0; i < v.Others.Count; i++)
{
Row(dl, v.Others[i], 1000 + i, new Vector2(origin.X, y), width, rowH, nf, sf, mine: false);
y += rowH;
}
}
ImGui.SetCursorScreenPos(origin);
ImGui.Dummy(new Vector2(width, height));
return height;
}
private void Row(ImDrawListPtr dl, CorpseRow row, int n, Vector2 at, float width, float h, ImFontPtr nf, ImFontPtr sf, bool mine)
{
float pad = Px(Pad), xw = mine ? Px(XW) : 0f;
dl.AddLine(new Vector2(at.X + pad, at.Y + 0.5f), new Vector2(at.X + width - pad, at.Y + 0.5f), A(_line, 0.6f));
// The row: click selects the corpse (yours, while it's in view).
ImGui.SetCursorScreenPos(at);
bool click = ImGui.InvisibleButton(Id("##corpse", n), new Vector2(Math.Max(1, width - xw - pad), h));
bool hot = ImGui.IsItemHovered();
SafeImGui.SetItemTooltip(row.Tip);
if (hot && mine) dl.AddRectFilled(at + new Vector2(1, 1), at + new Vector2(width - 1, h), A(_key, 0.55f), Px(3));
if (click && mine) _select(row);
// The arrow toward it, or a pin.
Vector2 mc = new(at.X + pad + Px(Mark) * 0.5f, at.Y + h * 0.5f);
if (!float.IsNaN(row.Relative)) Arrow(dl, mc, Px(Mark) * 0.42f, row.Relative, _accent);
else PanelButtonsWindow.DrawIcon(dl, RynthIcons.MapPin, new Vector2(at.X + pad, at.Y), new Vector2(Px(Mark), h), Px(12), mine ? _dim : _faint);
float tx = at.X + pad + Px(Mark) + Px(5), room = at.X + width - pad - xw - tx;
float top = MathF.Round(at.Y + (h - Fs(nf) - Fs(sf) - Px(1)) * 0.5f);
Clip(dl, nf, Fs(nf), new Vector2(tx, top), mine ? _text : _dim, row.Place, room);
Clip(dl, sf, Fs(sf), new Vector2(tx, top + Fs(nf) + Px(1)), mine ? _dim : _faint, row.Detail, room);
if (!mine) return;
// X: forget it (shown on the row's hover, always clickable).
Vector2 xp = new(at.X + width - pad - xw, at.Y + (h - xw) * 0.5f);
ImGui.SetCursorScreenPos(xp);
bool forget = ImGui.InvisibleButton(Id("##corpse_x", n), new Vector2(xw, xw));
bool xhot = ImGui.IsItemHovered();
SafeImGui.SetItemTooltip("Forget this corpse (it's recovered, or not worth going back for).");
if (hot || xhot) PanelButtonsWindow.DrawIcon(dl, RynthIcons.X, xp, new Vector2(xw, xw), Px(10), xhot ? _text : _faint);
if (forget) _forget(row);
}
// ImGui ids with a number, made once each: no strings built every frame.
private static readonly System.Collections.Generic.Dictionary<(string, int), string> Ids = new();
private static string Id(string prefix, int n)
{
if (!Ids.TryGetValue((prefix, n), out string? id)) Ids[(prefix, n)] = id = prefix + n;
return id;
}
/// <summary>Text cut with "..." to <paramref name="room"/> pixels.</summary>
private static void Clip(ImDrawListPtr dl, ImFontPtr f, float size, Vector2 pos, uint color, string text, float room)
{
if (text.Length == 0 || room <= 4) return;
float w = f.CalcTextSizeA(size, float.MaxValue, 0f, text).X;
if (w > room)
{
int n = text.Length;
while (n > 1 && f.CalcTextSizeA(size, float.MaxValue, 0f, text[..n] + "...").X > room) n--;
text = text[..n] + "...";
}
dl.AddText(f, size, new Vector2(MathF.Round(pos.X), MathF.Round(pos.Y)), color, text);
}
/// <summary>A small arrow pointing <paramref name="degrees"/> from straight up (where the player faces), clockwise.</summary>
private static void Arrow(ImDrawListPtr dl, Vector2 c, float r, float degrees, uint color)
{
float a = degrees * MathF.PI / 180f;
Vector2 Dir(float t) => new(MathF.Sin(t), -MathF.Cos(t));
Vector2 tip = c + Dir(a) * r;
Vector2 left = c + Dir(a + 2.45f) * r * 0.85f, rightP = c + Dir(a - 2.45f) * r * 0.85f;
dl.AddTriangleFilled(tip, left, rightP, color);
}
}

View file

@ -0,0 +1,84 @@
// ============================================================================
// RynthDefective - Corpses/PlaceNames.cs
// What the Corpses window needs from RynthNav's Atlas (<CoreDir>\NavData\
// locations.json, the file RynthCore's own readers and RynthNet's Characters
// window use): the dungeons' names and entrances by landblock, and the
// landblocks with a place on the surface map (their indoor cells are buildings
// in the overworld, not a dungeon). Read once, in the background, the first
// time it's asked; until then (or with no Atlas) a dungeon is named by its
// landblock number. Any thread.
// ============================================================================
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text.Json;
using System.Threading.Tasks;
namespace RynthCore.Plugin.RynthDefective.Corpses;
internal static class PlaceNames
{
internal sealed record Dungeon(string Name, double Ns, double Ew, bool HasEntrance);
private sealed record Data(HashSet<uint> MapLandblocks, Dictionary<uint, Dungeon> Dungeons);
private static volatile Data _data = new(new HashSet<uint>(), new Dictionary<uint, Dungeon>());
private static int _started;
/// <summary>Starts the one background read (later calls do nothing).</summary>
public static void EnsureLoading()
{
if (System.Threading.Interlocked.Exchange(ref _started, 1) != 0) return;
string path = Path.Combine(RynthCore.Install.RynthInstallPaths.CoreDir, "NavData", "locations.json");
Task.Run(() =>
{
try { if (File.Exists(path)) _data = Parse(File.ReadAllText(path)); }
catch { }
});
}
/// <summary>A surface building's landblock (a cell's top 16 bits).</summary>
public static bool IsMapLandblock(uint landblock) => _data.MapLandblocks.Contains(landblock & 0xFFFF);
/// <summary>The dungeon in this landblock, or null when the Atlas doesn't name it.</summary>
public static Dungeon? DungeonAt(uint landblock) => _data.Dungeons.TryGetValue(landblock & 0xFFFF, out Dungeon? d) ? d : null;
/// <summary>For tests: the Atlas from text, at once.</summary>
internal static void LoadForTests(string json)
{
_data = Parse(json);
_started = 1;
}
/// <summary>The Atlas's surface landblocks and dungeons (RynthCore's RynthNavAtlas rules, as RynthNet reads them). Pure.</summary>
private static Data Parse(string json)
{
var lbs = new HashSet<uint>();
var dungeons = new Dictionary<uint, Dungeon>();
using JsonDocument doc = JsonDocument.Parse(json);
if (doc.RootElement.TryGetProperty("locations", out JsonElement arr) && arr.ValueKind == JsonValueKind.Array)
foreach (JsonElement e in arr.EnumerateArray())
{
if (e.ValueKind != JsonValueKind.Object) continue;
string cell = Str(e, "cell"), type = Str(e, "type"), name = Str(e, "name"), lb = Str(e, "lb");
bool onMap = TryNum(e, "ns", out double ns) & TryNum(e, "ew", out double ew);
if (onMap && cell.Length == 8 && uint.TryParse(cell.AsSpan(0, 4), NumberStyles.HexNumber, null, out uint l))
lbs.Add(l);
if (type == "Dungeon" && name.Length > 0 && uint.TryParse(lb, NumberStyles.HexNumber, null, out uint d))
dungeons.TryAdd(d, new Dungeon(name, ns, ew, onMap));
}
return new Data(lbs, dungeons);
}
private static string Str(JsonElement e, string name) =>
e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.String ? v.GetString() ?? "" : "";
private static bool TryNum(JsonElement e, string name, out double value)
{
bool ok = e.TryGetProperty(name, out JsonElement v) && v.ValueKind == JsonValueKind.Number;
value = ok ? v.GetDouble() : 0;
return ok;
}
}

View file

@ -2,7 +2,7 @@ using System;
namespace RynthCore.Plugin.RynthDefective.Model;
internal enum DefVerb { Toggle, Help, Use, Set, Clear, Bind, Unbind, Weapons, Favourite, Slots, List, Status, Error, Panels, Selection, Settings, Spell }
internal enum DefVerb { Toggle, Help, Use, Set, Clear, Bind, Unbind, Weapons, Favourite, Slots, List, Status, Error, Panels, Selection, Settings, Spell, Corpses }
/// <summary>A parsed "/rdef ..." line. Use: <see cref="Slot"/> (1-based) or <see cref="Text"/> (an item name).</summary>
internal sealed record DefCommand(DefVerb Verb, int Slot = 0, string Text = "", string Error = "");
@ -11,7 +11,7 @@ internal static class DefCommandParser
{
public const string Usage =
"/rdef [use <slot or item name> | set <slot> [item name] | spell <slot> <spell name> | clear <slot> | bind <slot> <key> | unbind <slot> | "
+ "weapons [search] | fav | slots <count> | list | status | settings | panels (the game panel buttons) | selection]";
+ "weapons [search] | fav | slots <count> | list | status | settings | panels (the game panel buttons) | selection | corpses [clear]]";
/// <summary>Parses the arguments after "/rdef" (blank = show or hide the bar).</summary>
public static DefCommand Parse(string? args)
@ -29,6 +29,7 @@ internal static class DefCommandParser
case "status": return new DefCommand(DefVerb.Status);
case "panels": case "panel": return new DefCommand(DefVerb.Panels);
case "settings": case "options": case "setup": return new DefCommand(DefVerb.Settings);
case "corpses": case "corpse": return new DefCommand(DefVerb.Corpses, Text: rest);
case "selection": case "target":
// "/rdef selection 0x80001234": select that object (a test hook for the Selection window).
return new DefCommand(DefVerb.Selection, Text: rest);

View file

@ -0,0 +1,55 @@
using System.Globalization;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthDefective.Model;
/// <summary>
/// The line /rdef answers with for the commands that used to say nothing (2026-10-28: every command
/// answers, Plugins/Shared/CommandReply.cs): a window shown or hidden, a use started, a test
/// selection. Pure, so RynthDefective.Tests checks every verb's line.
/// </summary>
internal static class DefReplies
{
/// <summary>A window after a show / hide / toggle: <paramref name="state"/> 1 shown, 0 hidden, -1 the engine can't say.</summary>
public static (bool Ok, string Text) Window(string title, int state) => state switch
{
1 => (true, CommandReply.Shown(title, true)),
0 => (true, CommandReply.Shown(title, false)),
_ => (false, $"This RynthCore has no {title} window (it needs plugin API v90)."),
};
/// <summary>A slot's use started (the result shows on the bar; a problem is said in chat).</summary>
public static string UseSlot(DefSlot slot, int number) => slot.IsSpell
? $"Casting {slot.SpellLabel} (slot {number})."
: $"Using {slot.Label} (slot {number}).";
/// <summary>"/rdef use &lt;name&gt;" started: the item is looked up when the use runs.</summary>
public static string UseName(string name) => $"Using {name.Trim()}.";
/// <summary>The weapon picker after /rdef weapons [search].</summary>
public static string Weapons(bool shown, string search) =>
!shown ? "Weapon picker hidden."
: search.Trim().Length > 0 ? $"Weapon picker shown, searching '{search.Trim()}'."
: "Weapon picker shown.";
/// <summary>
/// "/rdef selection &lt;0xId&gt;" (the Selection window's test hook): the object id (hex, "0x" optional),
/// or false with the usage in <paramref name="why"/>.
/// </summary>
public static bool TryParseSelection(string text, out uint id, out string why)
{
why = string.Empty;
string t = text.Trim();
if (uint.TryParse(t.Replace("0x", "", System.StringComparison.OrdinalIgnoreCase), NumberStyles.HexNumber, null, out id)) return true;
why = $"'{t}' isn't an object id. Usage: /rdef selection [0x80001234 | stack]";
return false;
}
/// <summary>"/rdef selection stack" with no stack in the pack.</summary>
public const string NoStack = "No stack in your pack to select.";
/// <summary>What a test selection did.</summary>
public static (bool Ok, string Text) Selected(uint id, bool selected, string? name) =>
selected ? (true, $"Selected 0x{id:X8}{(string.IsNullOrEmpty(name) ? "" : " (" + name + ")")}.")
: (false, $"The game didn't select 0x{id:X8}.");
}

View file

@ -45,6 +45,19 @@ public static unsafe class PluginExports
public static void OnUpdateHealth(uint targetId, float healthRatio, uint currentHealth, uint maxHealth) =>
Runtime.OnUpdateHealth(targetId, healthRatio, currentHealth, maxHealth);
// The Corpses window (RynthDefectivePlugin.Corpses.cs): the server's corpse lines, corpses coming into view and leaving it.
[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 = "RynthPluginOnViewObjectContents", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnViewObjectContents(uint objectId) => Runtime.OnViewObjectContents(objectId);
[UnmanagedCallersOnly(EntryPoint = "RynthPluginOnLogout", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void OnLogout() => Runtime.OnLogout();
@ -92,6 +105,7 @@ public static unsafe class PluginExports
if (name == RynthDefectivePlugin.BarSurface) result = plugin.RenderBar(popped, out wantH);
else if (name == RynthDefectivePlugin.PanelsSurface) result = plugin.RenderPanels(out wantH);
else if (name == RynthDefectivePlugin.SelectionSurface) result = plugin.RenderSelection(out wantH);
else if (name == RynthDefectivePlugin.CorpsesSurface) result = plugin.RenderCorpses(out wantH);
else return 0;
if (result != 1) return result;
if (wantWidth != null) *wantWidth = width;

View file

@ -41,6 +41,8 @@
<Compile Include="..\Shared\RynthAiStatusApi.cs" Link="Shared\RynthAiStatusApi.cs" />
<!-- Install-folder resolver (env, HKCU, HKLM, default C:\Games). Read only; same file as RynthCore src\Shared. -->
<Compile Include="..\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
<!-- How a chat command answers (2026-10-28): the shared reply queue and colours. -->
<Compile Include="..\Shared\CommandReply.cs" Link="Shared\CommandReply.cs" />
</ItemGroup>
<ItemGroup>
<!-- Spell slots (2026-10-28): spell names and whom a spell is cast on, from RynthAi's spell table

View file

@ -64,7 +64,12 @@ public sealed partial class RynthDefectivePlugin : IBarActions
"\",\"icon\":\"\\u" + ((int)RynthIcons.Crosshair[0]).ToString("X4", CultureInfo.InvariantCulture) +
"\",\"width\":280,\"height\":46,\"minWidth\":120,\"minHeight\":24,\"bar\":false,\"edgeToEdge\":true," +
"\"chrome\":\"none\",\"fitHeight\":true,\"corner\":\"top\",\"scale\":\"draw\"}";
return "{\"version\":1,\"windows\":[" + bar + panels + selection + "]}";
// Where your corpses are (a bar button of its own).
string corpses = ",{\"id\":\"corpses\",\"title\":\"" + Corpses.CorpsesWindow.Title + "\",\"surface\":\"" + CorpsesSurface +
"\",\"icon\":\"\\u" + ((int)RynthIcons.Skull[0]).ToString("X4", CultureInfo.InvariantCulture) +
"\",\"width\":290,\"height\":80,\"minWidth\":140,\"minHeight\":30,\"bar\":true,\"edgeToEdge\":true," +
"\"chrome\":\"none\",\"fitHeight\":true,\"scale\":\"draw\"}";
return "{\"version\":1,\"windows\":[" + bar + panels + selection + corpses + "]}";
}
/// <summary>RynthPluginRenderEmbed "window:panels". 1 drawn, 0 not ready, -2 failed (three in a row). Render thread.</summary>

View file

@ -0,0 +1,313 @@
// ============================================================================
// RynthDefective - RynthDefectivePlugin.Corpses.cs
// The Corpses window (2026-10-23): where your corpses are (Corpses/CorpseBook.cs
// has the rules, Corpses/CorpsesWindow.cs draws it).
//
// Always on while logged in (a death has to be noted whether the window shows
// or not), and cheap: the health is read 10 times a second, the server's two
// corpse lines are picked out of the chat, and each object that comes into
// view is checked once for the name "Corpse of <you>". A corpse leaving view
// counts as gone (CorpseBook.VanishMeansGone) when you had opened it, it was due
// to rot, or it went from beside you, and not while portalling; otherwise you
// only walked away from it or lost sight of it.
//
// This character's corpses are saved in their own file, the other characters'
// read from theirs every 10 s while the window shows.
// ============================================================================
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using RynthCore.Plugin.RynthDefective.Corpses;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthDefective;
public sealed partial class RynthDefectivePlugin
{
internal const string CorpsesSurface = "window:corpses";
private const string CorpsePrefix = "Corpse of ";
private const uint LevelProperty = 25; // PropertyInt.Level
private readonly CorpseBook _corpseBook = new();
private CorpseStore? _corpseStore;
private CorpsesWindow? _corpsesWindow; // render thread
private volatile CorpsesView _corpsesView = CorpsesView.NotReady; // tick writes, render reads
private readonly ConcurrentQueue<uint> _createdIds = new(), _deletedIds = new(), _openedIds = new();
private readonly ConcurrentQueue<string> _corpseLines = new();
private readonly ConcurrentQueue<Action> _corpseActions = new();
private readonly List<(uint Id, long AtMs)> _corpsePending = new(); // seen, no position yet
private readonly List<(uint Id, long AtMs)> _corpseDeletes = new(); // left view: gone?
private List<OtherCorpses> _otherCorpses = new();
private bool _corpsesStarted, _deadSeen;
private string? _corpseAlias; // test hook: another name's corpses count as yours
private long _corpsesDrawnMs = long.MinValue / 2, _nextCorpseViewMs, _nextDeathCheckMs, _nextCorpseExpireMs, _nextOthersMs, _corpseSaveDueMs, _nextAbsentCheckMs;
private int _corpseRevisionSaved, _corpseRevisionShown = -1, _corpsesFailures;
/// <summary>RynthPluginRenderEmbed "window:corpses". 1 drawn, 0 not ready, -2 failed (three in a row). Render thread.</summary>
internal int RenderCorpses(out float wantHeight)
{
wantHeight = 0;
if (!UsesShortcutBar) return 0;
System.Threading.Volatile.Write(ref _corpsesDrawnMs, Environment.TickCount64);
try
{
_corpsesWindow ??= new CorpsesWindow(Host,
row => _corpseActions.Enqueue(() => SelectCorpse(row)),
row => _corpseActions.Enqueue(() => { if (row.Record != null) _corpseBook.Forget(row.Record); }));
wantHeight = _corpsesWindow.Draw(_corpsesView);
_corpsesFailures = 0;
return 1;
}
catch (Exception ex)
{
Host.Log($"[RynthDefective] corpses draw failed: {ex.GetType().Name}: {ex.Message}");
return ++_corpsesFailures >= 3 ? -2 : 0;
}
}
public override void OnCreateObject(uint objectId)
{
if (_createdIds.Count < 4096) _createdIds.Enqueue(objectId);
}
public override void OnDeleteObject(uint objectId)
{
if (_deletedIds.Count < 4096) _deletedIds.Enqueue(objectId);
}
public override void OnViewObjectContents(uint objectId)
{
if (_openedIds.Count < 256) _openedIds.Enqueue(objectId);
}
public override void OnChatWindowText(string? text, int chatType, ref int eat)
{
if (text == null || text.IndexOf("corpse", StringComparison.OrdinalIgnoreCase) < 0) return;
if (CorpseLines.IsCorpseLine(text) && _corpseLines.Count < 64) _corpseLines.Enqueue(text);
}
/// <summary>The character is known: its corpses from its file, and any of them already in view.</summary>
private void StartCorpses()
{
_corpseStore ??= new CorpseStore(_store.Root);
PlaceNames.EnsureLoading();
_corpseBook.Load(_corpseStore.Load(_server, _character, out string? problem));
if (problem != null) Host.Log($"[RynthDefective] couldn't read the corpses ({problem}); starting empty.");
_corpseRevisionSaved = _corpseBook.Revision;
_corpseRevisionShown = -1;
_corpsePending.Clear();
_corpseDeletes.Clear();
_deadSeen = false;
_nextOthersMs = 0;
_corpsesStarted = true;
if (Host.HasGetLiveObjectIds)
foreach (uint id in Host.GetLiveObjectIds()) CheckCreated(id, Environment.TickCount64);
}
private void StopCorpses()
{
SaveCorpsesNow();
_corpsesStarted = false;
_corpsesView = CorpsesView.NotReady;
while (_createdIds.TryDequeue(out _)) { }
while (_deletedIds.TryDequeue(out _)) { }
while (_openedIds.TryDequeue(out _)) { }
while (_corpseLines.TryDequeue(out _)) { }
_corpsePending.Clear();
_corpseDeletes.Clear();
}
/// <summary>Plugin tick: the death, the server's lines, corpses coming and going, the save and the window's view.</summary>
private void TickCorpses(long now)
{
if (!_corpsesStarted)
{
while (_createdIds.TryDequeue(out _)) { } // nothing to match them to yet
while (_deletedIds.TryDequeue(out _)) { }
while (_openedIds.TryDequeue(out _)) { }
return;
}
DateTime utc = DateTime.UtcNow;
while (_corpseActions.TryDequeue(out Action? act))
{
try { act(); } catch (Exception ex) { Host.Log($"[RynthDefective] corpses: {ex.Message}"); }
}
if (now >= _nextDeathCheckMs)
{
_nextDeathCheckMs = now + 100;
CheckDeath(utc);
}
while (_corpseLines.TryDequeue(out string? line))
{
if (CorpseLines.TryLocated(line, out double ns, out double ew)) _corpseBook.ServerLine(utc, ns, ew, PlayerLevel());
else if (CorpseLines.IsNothingDropped(line)) _corpseBook.NothingDropped(utc);
}
// A portal into town brings hundreds at once: a few hundred a tick, the rest on the next.
for (int n = 0; n < 256 && _createdIds.TryDequeue(out uint id); n++) CheckCreated(id, now);
while (_openedIds.TryDequeue(out uint opened)) _corpseBook.Opened(opened, utc);
for (int i = _corpsePending.Count - 1; i >= 0; i--)
{
(uint id, long until) = _corpsePending[i];
if (TrySeen(id, utc) || now > until) _corpsePending.RemoveAt(i);
}
while (_deletedIds.TryDequeue(out uint id))
foreach (CorpseRecord c in _corpseBook.Corpses)
if (c.ObjectId == id) { _corpseDeletes.Add((id, now + 2500)); break; }
for (int i = _corpseDeletes.Count - 1; i >= 0; i--)
{
if (now < _corpseDeletes[i].AtMs) continue;
uint id = _corpseDeletes[i].Id;
_corpseDeletes.RemoveAt(i);
CheckGone(id);
}
if (now >= _nextAbsentCheckMs)
{
_nextAbsentCheckMs = now + 1000;
CheckNotThere(utc);
}
if (now >= _nextCorpseExpireMs)
{
_nextCorpseExpireMs = now + 60_000;
_corpseBook.Expire(utc);
}
if (_corpseBook.Revision != _corpseRevisionSaved && _corpseSaveDueMs == 0) _corpseSaveDueMs = now + 1000;
if (_corpseSaveDueMs != 0 && now >= _corpseSaveDueMs) SaveCorpsesNow();
bool shown = now - System.Threading.Volatile.Read(ref _corpsesDrawnMs) < 2000;
if (!shown) return;
if (now >= _nextOthersMs && _corpseStore != null)
{
_nextOthersMs = now + 10_000;
_otherCorpses = _corpseStore.LoadOthers(_server, _character, utc);
_corpseRevisionShown = -1;
}
if (now >= _nextCorpseViewMs || _corpseBook.Revision != _corpseRevisionShown)
{
_nextCorpseViewMs = now + 250;
_corpseRevisionShown = _corpseBook.Revision;
_corpsesView = CorpseRows.Build(_corpseBook.Corpses, _otherCorpses, PlayerSpotNow(), utc);
}
}
/// <summary>Health 0 (the edge): where the player stands is where the corpse will lie.</summary>
private void CheckDeath(DateTime utc)
{
if (!Host.TryGetPlayerVitals(out uint hp, out uint maxHp, out _, out _, out _, out _) || maxHp == 0) return;
bool dead = hp == 0;
if (dead && !_deadSeen)
{
_deadSeen = true;
if (Host.TryGetPlayerPose(out uint cell, out float x, out float y, out float z, out _, out _, out _, out _) && cell != 0)
{
_corpseBook.Died(utc, cell, x, y, z, PlayerLevel());
Host.Log($"[RynthDefective] died at 0x{cell:X8} ({x:0.0}, {y:0.0}, {z:0.0}): noted for the Corpses window.");
}
}
else if (!dead) _deadSeen = false;
}
private int PlayerLevel()
{
uint player = Host.GetPlayerId();
return player != 0 && Host.TryGetObjectIntProperty(player, LevelProperty, out int level) ? level : 0;
}
/// <summary>An object came into view: one of this character's corpses?</summary>
private void CheckCreated(uint id, long now)
{
if (id == 0 || !Host.TryGetObjectName(id, out string name) || !name.StartsWith(CorpsePrefix, StringComparison.Ordinal)) return;
string of = name.Substring(CorpsePrefix.Length);
if (of != _character && (_corpseAlias == null || of != _corpseAlias)) return;
if (!TrySeen(id, DateTime.UtcNow)) _corpsePending.Add((id, now + 5000));
}
private bool TrySeen(uint id, DateTime utc)
{
if (!Host.TryGetObjectPosition(id, out uint cell, out float x, out float y, out float z) || cell == 0) return false;
_corpseBook.Seen(utc, id, cell, x, y, z);
return true;
}
/// <summary>A corpse left view 2.5 s ago: gone for good, or only out of sight (CorpseBook.VanishMeansGone)?</summary>
private void CheckGone(uint id)
{
if (Host.HasIsPortaling && Host.IsPortaling()) return;
if (Host.TryGetObjectPosition(id, out uint back, out _, out _, out _) && back != 0) return; // in view again
CorpseRecord? c = null;
foreach (CorpseRecord r in _corpseBook.Corpses) if (r.ObjectId == id) { c = r; break; }
if (c == null) return;
PlayerSpot me = PlayerSpotNow();
if (me.Cell == 0) return;
double d = CorpseBook.Distance(c, me.Cell, me.X, me.Y, me.Z);
bool opened = c.OpenedUtc != DateTime.MinValue;
if (CorpseBook.VanishMeansGone(c, d, DateTime.UtcNow) && _corpseBook.Gone(id))
Host.Log($"[RynthDefective] your corpse 0x{id:X8} is gone ({d:0} m away{(opened ? ", opened" : "")}).");
else
Host.Log($"[RynthDefective] your corpse 0x{id:X8} left view ({d:0} m away); kept.");
}
/// <summary>Standing where a corpse should be without it in view: after 10 s it's dropped.</summary>
private void CheckNotThere(DateTime utc)
{
if (_corpseBook.Corpses.Count == 0 || (Host.HasIsPortaling && Host.IsPortaling())) return;
PlayerSpot me = PlayerSpotNow();
if (me.Cell == 0) return;
CorpseRecord? drop = null;
double dropAt = 0;
foreach (CorpseRecord c in _corpseBook.Corpses)
{
double d = CorpseBook.Distance(c, me.Cell, me.X, me.Y, me.Z);
bool inView = c.ObjectId != 0 && Host.TryGetObjectPosition(c.ObjectId, out uint oc, out _, out _, out _) && oc != 0;
if (CorpseBook.NotThere(c, d, inView, utc)) { drop = c; dropAt = d; }
}
if (drop != null && _corpseBook.Forget(drop))
Host.Log($"[RynthDefective] a corpse isn't where it was ({dropAt:0} m from its place for {CorpseBook.AbsentFor.TotalSeconds:0} s): dropped.");
}
private PlayerSpot PlayerSpotNow()
{
if (!Host.TryGetPlayerPose(out uint pc, out float px, out float py, out float pz, out float qw, out _, out _, out float qz) || pc == 0)
return default;
double facing = ((-2.0 * Math.Atan2(qz, qw) * 180.0 / Math.PI) % 360.0 + 720.0) % 360.0;
return new PlayerSpot(pc, px, py, pz, facing);
}
private void SelectCorpse(CorpseRow row)
{
if (row.ObjectId != 0 && Host.TryGetObjectName(row.ObjectId, out _) && Host.SelectItem(row.ObjectId)) return;
Print($"That corpse isn't in view. It's at {row.Place}.");
}
/// <summary>"/rdef corpses die" and "/rdef corpses as &lt;name&gt;" (tests on a server where dying is slow).</summary>
private string CorpseTestHook(string arg)
{
if (!_corpsesStarted) return "Log in first.";
if (arg.Equals("die", StringComparison.OrdinalIgnoreCase))
{
if (!Host.TryGetPlayerPose(out uint cell, out float x, out float y, out float z, out _, out _, out _, out _) || cell == 0)
return "No position.";
_corpseBook.Died(DateTime.UtcNow, cell, x, y, z, PlayerLevel());
return $"Test: a death noted at 0x{cell:X8} ({x:0.0}, {y:0.0}, {z:0.0}).";
}
if (arg.StartsWith("as ", StringComparison.OrdinalIgnoreCase))
{
_corpseAlias = arg.Substring(3).Trim();
if (Host.HasGetLiveObjectIds)
foreach (uint id in Host.GetLiveObjectIds()) CheckCreated(id, Environment.TickCount64);
return $"Test: \"{CorpsePrefix}{_corpseAlias}\" counts as yours until the plugin reloads.";
}
return "Usage: /rdef corpses [clear]";
}
private void SaveCorpsesNow()
{
_corpseSaveDueMs = 0;
if (!_corpsesStarted || _corpseStore == null || _corpseBook.Revision == _corpseRevisionSaved) return;
_corpseRevisionSaved = _corpseBook.Revision;
string? error = _corpseStore.Save(_server, _character, _corpseBook.Corpses);
if (error != null) Host.Log("[RynthDefective] corpses save failed: " + error);
}
}

View file

@ -7,6 +7,7 @@ using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.RynthDefective.Ui;
using RynthCore.Plugin.RynthDefective.Use;
using RynthCore.Plugin.RynthDefective.Views;
using RynthCore.Plugin.Shared;
using RynthCore.PluginCore;
using RynthCore.PluginSdk;
@ -61,6 +62,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
public override int Initialize()
{
_reply = new CommandReply("[RynthDefective]", (t, c) => Host.WriteToChat(t, c), t => Host.Log(t));
_ui.Log = msg => Host.Log(msg);
// The shortcut bar (plugin API v90) draws with ImGui.NET bound to the engine's cimgui, in its look.
RynthCore.Plugin.Shared.ImGuiNativeBinding.Ensure(msg => Host.Log("[RynthDefective] " + msg));
@ -77,7 +79,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
_session.BindOwnKey = (own, key) => Host.HasKeyBinding && BindOwnSlotKey(own, key, out _);
_session.Use.Say = text => { _session.SetStatus(text); Host.Log("[RynthDefective] " + text); };
_session.Use.Warn = text => { _session.SetStatus(text, warning: true); Print(text); };
_session.Use.Warn = text => { _session.SetStatus(text, warning: true); PrintFail(text); };
_session.Use.Log = line => Host.Log(line);
_session.Use.Wielded = OnWielded;
@ -106,6 +108,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
// The engine calls this on a real login and on a freshly (re)loaded plugin already in game.
public override void OnLoginComplete()
{
if (_corpsesStarted) StopCorpses();
_inWorld = true;
_identityKnown = false;
_nextIdentityTryMs = Environment.TickCount64;
@ -116,6 +119,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
public override void OnLogout()
{
SaveNow();
StopCorpses();
_inWorld = false;
_identityKnown = false;
_session.LoggedIn = false;
@ -131,6 +135,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
public override void Shutdown()
{
SaveNow();
SaveCorpsesNow();
_session.Use.ResetSession();
_ui.SubmitEmpty(Host);
}
@ -158,54 +163,88 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
}
if (c.Verb == DefVerb.Error)
{
Print(c.Error);
PrintFail(c.Error);
return;
}
if (!_identityKnown)
{
Print("Log in first.");
PrintFail("Log in first.");
return;
}
// Every command answers (2026-10-28, Plugins/Shared/CommandReply.cs). RynthDefective can't tell a
// typed /rdef from a hotkey's or a meta's (the engine sends them all the same way), so each one does.
switch (c.Verb)
{
case DefVerb.Toggle:
if (UsesShortcutBar)
Host.SetPanelOpen(RynthCore.Plugin.RynthDefective.ShortcutBar.ShortcutBarWindow.Title, RynthPanelOpen.Toggle);
else if (_barWindow != null) { _barWindow.Visible = !_barWindow.Visible; _barWindow.NeedsPass = true; NoteNoUi(_barWindow.Visible); }
Answer(DefReplies.Window("Shortcuts bar", Host.SetPanelOpen(RynthCore.Plugin.RynthDefective.ShortcutBar.ShortcutBarWindow.Title, RynthPanelOpen.Toggle)));
else if (_barWindow != null)
{
_barWindow.Visible = !_barWindow.Visible; _barWindow.NeedsPass = true; NoteNoUi(_barWindow.Visible);
Print(CommandReply.Shown("Item bar", _barWindow.Visible));
}
break;
case DefVerb.Selection when c.Text.Length > 0:
// Test hooks: "/rdef selection 0x80001234" selects that object; "stack" the first stack in the pack.
if (c.Text.Equals("stack", StringComparison.OrdinalIgnoreCase))
{
CarriedItem? stack = null;
foreach (var it in _session.Items())
if (it.Stack > 1 && !it.Wielded) { Host.SelectItem(it.Id); break; }
if (it.Stack > 1 && !it.Wielded) { stack = it; break; }
if (stack == null) PrintFail(DefReplies.NoStack);
else Answer(DefReplies.Selected(stack.Id, Host.SelectItem(stack.Id), _session.ObjectName(stack.Id)));
}
else if (uint.TryParse(c.Text.Replace("0x", "", StringComparison.OrdinalIgnoreCase), System.Globalization.NumberStyles.HexNumber, null, out uint pick))
Host.SelectItem(pick);
else if (DefReplies.TryParseSelection(c.Text, out uint pick, out string why))
Answer(DefReplies.Selected(pick, Host.SelectItem(pick), _session.ObjectName(pick)));
else PrintFail(why);
break;
case DefVerb.Selection:
if (UsesShortcutBar) Host.SetPanelOpen(RynthCore.Plugin.RynthDefective.ShortcutBar.SelectionWindow.Title, RynthPanelOpen.Toggle);
else Print("This RynthCore can't show the selection window (it needs plugin API v90).");
if (UsesShortcutBar) Answer(DefReplies.Window("Selection window", Host.SetPanelOpen(RynthCore.Plugin.RynthDefective.ShortcutBar.SelectionWindow.Title, RynthPanelOpen.Toggle)));
else PrintFail("This RynthCore can't show the selection window (it needs plugin API v90).");
break;
case DefVerb.Settings:
ShowSettingsWindow(true);
Print("Settings shown.");
break;
case DefVerb.Corpses when c.Text.Equals("clear", StringComparison.OrdinalIgnoreCase):
_corpseBook.Clear();
Print("This character's corpses are forgotten.");
break;
case DefVerb.Corpses when c.Text.Length > 0:
// Test hooks: "die" notes a death where you stand; "as Olthoi Slayer" counts that name's corpses as yours.
Print(CorpseTestHook(c.Text));
break;
case DefVerb.Corpses:
if (UsesShortcutBar) Answer(DefReplies.Window("Corpses window", Host.SetPanelOpen(Corpses.CorpsesWindow.Title, RynthPanelOpen.Toggle)));
else PrintFail("This RynthCore can't show the corpses window (it needs plugin API v90).");
break;
case DefVerb.Panels:
if (UsesPanelButtons) Host.SetPanelOpen(RynthCore.Plugin.RynthDefective.ShortcutBar.PanelButtonsWindow.Title, RynthPanelOpen.Toggle);
else Print("This RynthCore can't open the game's panels from buttons (it needs plugin API v90).");
if (UsesPanelButtons) Answer(DefReplies.Window("Game Panels buttons", Host.SetPanelOpen(RynthCore.Plugin.RynthDefective.ShortcutBar.PanelButtonsWindow.Title, RynthPanelOpen.Toggle)));
else PrintFail("This RynthCore can't open the game's panels from buttons (it needs plugin API v90).");
break;
case DefVerb.Weapons:
{
if (c.Text.Length > 0 && _picker != null) _picker.Search = c.Text;
ShowPicker(c.Text.Length > 0 || _pickerWindow?.Visible != true);
bool show = c.Text.Length > 0 || _pickerWindow?.Visible != true;
ShowPicker(show);
Print(DefReplies.Weapons(show, c.Text));
break;
}
case DefVerb.Use:
if (c.Slot > 0)
{
string? problem = _session.UseSlot(c.Slot);
if (problem != null) { _session.SetStatus(problem, warning: true); Print(problem); }
// A use that goes is quiet (logged): slot hotkeys send /rdef use N on every press, and
// the use itself is the feedback (Tom 2026-10-28). Failures still answer.
if (problem != null) { _session.SetStatus(problem, warning: true); PrintFail(problem); }
else Reply.Ok(DefReplies.UseSlot(_session.Data.Slots[c.Slot - 1], c.Slot), quiet: true);
}
else
{
_session.UseByName(c.Text);
Reply.Ok(DefReplies.UseName(c.Text), quiet: true);
}
else _session.UseByName(c.Text);
break;
case DefVerb.Set:
Print(c.Text.Length > 0 ? _session.SetFromName(c.Slot, c.Text) : _session.SetFromSelected(c.Slot));
@ -280,11 +319,16 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
+ $"{(_session.Use.InFlight ? "an action is in flight" : _session.Use.HasPending ? "an action is waiting" : "idle")}; file {_store.PathFor(_server, _character)}");
}
private void Print(string text)
{
if (!Host.WriteToChat("[RynthDefective] " + text, 1))
Host.Log("[RynthDefective] " + text);
}
// Chat lines wait in the shared reply queue (the host drops a line written within 100 ms of
// another plugin's); the tick writes them.
private CommandReply? _reply;
private CommandReply Reply => _reply ??= new CommandReply("[RynthDefective]", (t, c) => Host.WriteToChat(t, c), t => Host.Log(t));
private void Print(string text) => Reply.Ok(text);
private void PrintFail(string text) => Reply.Fail(text);
private void Answer((bool Ok, string Text) reply) => Reply.Say(reply.Ok, reply.Text);
private void NoteNoUi(bool shown)
{
@ -367,8 +411,13 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
while (_commands.TryDequeue(out string? cmd))
{
try { RunCommand(cmd); }
catch (Exception ex) { Host.Log($"[RynthDefective] /rdef {cmd} failed: {ex.GetType().Name}: {ex.Message}"); }
catch (Exception ex)
{
Host.Log($"[RynthDefective] /rdef {cmd} failed: {ex.GetType().Name}: {ex.Message}");
PrintFail($"/rdef {cmd} failed: {ex.Message}");
}
}
Reply.Flush();
_ui.Poll(Host);
if (_inWorld)
@ -390,6 +439,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
if (_saveDueMs != 0 && now >= _saveDueMs) SaveNow();
TickBar(now);
TickSelection(now);
TickCorpses(now);
// With the shortcut bar the old script-window bar stays shut (the weapon picker is still one), and
// has no RynthBar button (one that opened a window shut again at once). Its settings have their
@ -451,6 +501,7 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
_identityKnown = true;
_revisionSeen = -1;
RefreshIconSupport();
StartCorpses();
if (_barWindow != null && _bar != null)
{
_barWindow.Visible = data.Settings.BarOpen;

View file

@ -137,7 +137,7 @@ internal sealed class PanelButtonsWindow
}
/// <summary>A Phosphor glyph centred in the box, <paramref name="px"/> across its em (from Ui18's bake).</summary>
private static unsafe void DrawIcon(ImDrawListPtr dl, string glyph, Vector2 min, Vector2 size, float px, uint color)
internal static unsafe void DrawIcon(ImDrawListPtr dl, string glyph, Vector2 min, Vector2 size, float px, uint color)
{
if (string.IsNullOrEmpty(glyph)) return;
ImFontPtr font = Font(RynthUiFont.Ui18);

View file

@ -0,0 +1,40 @@
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthInventory;
internal enum InventoryVerb { Window, Scan, Keep, Reload, Status, Help, Search }
/// <summary>
/// A parsed "/ginv ..." and the lines it answers with (2026-10-28: every command answers,
/// Plugins/Shared/CommandReply.cs). Anything that isn't a verb is a search. Pure, so
/// RynthInventory.Tests checks every word.
/// </summary>
internal readonly record struct InventoryCommand(InventoryVerb Verb, string Text = "")
{
public static InventoryCommand Parse(string? arg)
{
string a = (arg ?? string.Empty).Trim();
return a.ToLowerInvariant() switch
{
"" => new(InventoryVerb.Window),
"scan" or "rescan" => new(InventoryVerb.Scan),
"keep" => new(InventoryVerb.Keep),
"reload" => new(InventoryVerb.Reload),
"status" => new(InventoryVerb.Status),
"help" or "?" => new(InventoryVerb.Help),
_ => new(InventoryVerb.Search, a),
};
}
public const string Usage =
"/ginv (window), /ginv <text> (search), /ginv scan (rescan and save now), /ginv keep (record the open container as storage), /ginv reload, /ginv status";
public const string NoWindows =
"This RynthCore engine can't show plugin windows (it needs script windows, API v71, with ImGui on). Scanning and saving still work; /ginv status shows what was saved.";
/// <summary>/ginv alone: the window after the toggle.</summary>
public static string Window(bool shown) => CommandReply.Shown("Global Inventory", shown);
/// <summary>/ginv &lt;text&gt;: the search the window now shows.</summary>
public static string Searching(string text) => $"Global Inventory: searching for '{text.Trim()}'.";
}

View file

@ -1,5 +1,6 @@
using System;
using RynthCore.Plugin.RynthInventory.Data;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthInventory;
@ -40,9 +41,21 @@ internal sealed class InventoryContext
/// <summary>Forgets a character (moves its file aside). Returns a message for the player.</summary>
public Func<CharacterInfo, string> Forget = _ => string.Empty;
public void Print(string text)
/// <summary>
/// The plugin's chat lines, queued and written by the tick (Plugins/Shared/CommandReply.cs: the host
/// drops a line within 100 ms of another plugin's). Null before Initialize.
/// </summary>
public CommandReply? Reply;
public void Print(string text) => Print(text, ok: true);
/// <summary>A line saying a command didn't work (the failure colour).</summary>
public void PrintFail(string text) => Print(text, ok: false);
private void Print(string text, bool ok)
{
if (!Host.WriteToChat("[RynthInventory] " + text, 1))
if (Reply != null) { Reply.Say(ok, text); return; }
if (!Host.WriteToChat("[RynthInventory] " + text, ok ? CommandReply.OkChatType : CommandReply.FailChatType))
Host.Log("[RynthInventory] " + text);
}
}

View file

@ -41,6 +41,8 @@
<ItemGroup>
<!-- Storage another plugin reads for us ("storage" commands: Aelrynth's vault from RynthAelrynth). Also linked by RynthInventory.Tests. -->
<Compile Include="..\Shared\StorageFeed.cs" Link="Shared\StorageFeed.cs" />
<!-- How a chat command answers (2026-10-28): the shared reply queue and colours. -->
<Compile Include="..\Shared\CommandReply.cs" Link="Shared\CommandReply.cs" />
</ItemGroup>
</Project>

View file

@ -61,7 +61,6 @@ public sealed class RynthInventoryPlugin : RynthPluginBase
private bool _identityKnown;
private long _loginMs;
private long _nextIdentityTryMs;
private bool _noUiLogged;
private bool _oldAccountChecked;
private bool _forceWrite;
@ -88,6 +87,7 @@ public sealed class RynthInventoryPlugin : RynthPluginBase
public override int Initialize()
{
_c.Host = Host;
_c.Reply = new CommandReply("[RynthInventory]", (t, c) => Host.WriteToChat(t, c), t => Host.Log(t));
_c.Settings.Load();
_c.RequestRescan = () => { _scheduler.RequestFullScan(); _forceWrite = true; };
_c.RequestReload = () => { _reloadWanted = true; _files.Clear(); };
@ -216,43 +216,46 @@ public sealed class RynthInventoryPlugin : RynthPluginBase
private void RunCommand(string arg)
{
string lower = arg.ToLowerInvariant();
switch (lower)
// Every /ginv answers in chat (2026-10-28, InventoryCommand.cs; Plugins/Shared/CommandReply.cs).
// RynthInventory can't tell a typed /ginv from a meta's, so each one does.
InventoryCommand c = InventoryCommand.Parse(arg);
switch (c.Verb)
{
case "":
if (_window != null) { _window.Visible = !_window.Visible; _window.NeedsPass = true; }
case InventoryVerb.Window:
if (_window != null)
{
_window.Visible = !_window.Visible; _window.NeedsPass = true;
if (Host.HasUi) _c.Print(InventoryCommand.Window(_window.Visible));
}
break;
case "scan":
case "rescan":
case InventoryVerb.Scan:
_scheduler.RequestFullScan();
_forceWrite = true;
_c.Print("Rescanning this character; it saves within a few seconds.");
break;
case "keep":
case InventoryVerb.Keep:
KeepOpenContainer();
break;
case "reload":
case InventoryVerb.Reload:
_reloadWanted = true;
_files.Clear();
_c.Print("Reading the inventory files again.");
break;
case "status":
case InventoryVerb.Status:
PrintStatus();
break;
case "help":
case "?":
_c.Print("/ginv (window), /ginv <text> (search), /ginv scan (rescan and save now), /ginv keep (record the open container as storage), /ginv reload, /ginv status");
case InventoryVerb.Help:
_c.Print(InventoryCommand.Usage);
break;
default:
_view?.SetSearch(arg);
_view?.SetSearch(c.Text);
if (_window != null) { _window.Visible = true; _window.NeedsPass = true; }
if (Host.HasUi) _c.Print(InventoryCommand.Searching(c.Text));
break;
}
if (_window != null && _window.Visible && !Host.HasUi && !_noUiLogged)
{
_noUiLogged = true;
_c.Print("This RynthCore engine can't show plugin windows (it needs script windows, API v71, with ImGui on). Scanning and saving still work; /ginv status shows what was saved.");
}
// Without plugin windows the window verbs say why nothing shows (every time).
if (_window != null && _window.Visible && !Host.HasUi && c.Verb is InventoryVerb.Window or InventoryVerb.Search)
_c.PrintFail(InventoryCommand.NoWindows);
}
private void PrintStatus()
@ -269,13 +272,13 @@ public sealed class RynthInventoryPlugin : RynthPluginBase
{
if (!_identityKnown || _lastViewed == 0)
{
_c.Print("Open the container first, then type /ginv keep while it is open.");
_c.PrintFail("Open the container first, then type /ginv keep while it is open.");
return;
}
string name = Host.TryGetObjectName(_lastViewed, out string n) ? n : "container";
if (!InventoryScanner.IsStorage(Host, _lastViewed, _c.Player, Array.Empty<string>(), kept: true, out name, out string why))
{
_c.Print($"{name} can't be kept as storage ({why}).");
_c.PrintFail($"{name} can't be kept as storage ({why}).");
return;
}
string key = InventorySettings.KeepKey(_c.Server, _lastViewed);
@ -296,6 +299,7 @@ public sealed class RynthInventoryPlugin : RynthPluginBase
_c.UtcNow = DateTime.UtcNow;
while (_commands.TryDequeue(out string? cmd)) RunCommand(cmd);
_c.Reply?.Flush();
_ui.Poll(Host);
if (_c.InWorld)

View file

@ -49,6 +49,8 @@
<ItemGroup>
<!-- Install-folder resolver (env, HKCU, HKLM, default C:\Games). Read only; same file as RynthCore src\Shared. -->
<Compile Include="..\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
<!-- How a chat command answers (2026-10-28): the shared reply queue and colours. -->
<Compile Include="..\Shared\CommandReply.cs" Link="Shared\CommandReply.cs" />
</ItemGroup>
</Project>

View file

@ -90,6 +90,7 @@ public sealed partial class RynthLuaPlugin : RynthPluginBase
public override int Initialize()
{
_ = Reply;
_ai = new RynthAiBridge(Host);
// Every use logged (Plugins/Shared/UseAudit.cs). Scripts are the player's: no guard.
RynthCore.Plugin.Shared.UseAudit.Reset("RynthLua", null);
@ -133,8 +134,9 @@ public sealed partial class RynthLuaPlugin : RynthPluginBase
while (_chatCommands.TryDequeue(out string? line))
{
try { HandleLuaChatCommand(line); }
catch (Exception ex) { ChatLine("error: " + ex.Message); }
catch (Exception ex) { ChatFail("error: " + ex.Message); }
}
Reply.Flush();
// Script windows are kept apart from the scripts: a fault in the window steps is logged
// (at most every 10 s) and can't stop every script's threads from running.
try { PollHudEvents(); } // script windows: input first, so this tick's passes see it
@ -291,10 +293,16 @@ public sealed partial class RynthLuaPlugin : RynthPluginBase
_chatCommands.Enqueue("/lua " + value);
}
internal void ChatLine(string text)
{
if (Host.HasWriteToChat) Host.WriteToChat("[RynthLua] " + text, 1);
}
// Chat lines wait in the shared reply queue (Plugins/Shared/CommandReply.cs): the host drops a line
// within 100 ms of another plugin's, so /lua's two-line usage used to lose its second line.
private RynthCore.Plugin.Shared.CommandReply? _reply;
private RynthCore.Plugin.Shared.CommandReply Reply => _reply ??= new RynthCore.Plugin.Shared.CommandReply("[RynthLua]",
(t, c) => Host.HasWriteToChat && Host.WriteToChat(t, c), t => Log(t));
internal void ChatLine(string text) => Reply.Ok(text);
/// <summary>A /lua command that didn't work: why, and the usage (the failure colour).</summary>
internal void ChatFail(string text) => Reply.Fail(text);
// ── Panel ───────────────────────────────────────────────────────────────

View file

@ -285,13 +285,15 @@ public sealed partial class RynthLuaPlugin
case "start":
{
string? err = StartScript(rest);
ChatLine(err ?? $"Running {FindScript(rest)?.Name ?? rest}.");
if (err != null) ChatFail(err);
else ChatLine($"Running {FindScript(rest)?.Name ?? rest}.");
break;
}
case "restart":
{
string? err = StartScript(rest);
ChatLine(err ?? $"Restarted {FindScript(rest)?.Name ?? rest}.");
if (err != null) ChatFail(err);
else ChatLine($"Restarted {FindScript(rest)?.Name ?? rest}.");
break;
}
case "stop":
@ -301,18 +303,25 @@ public sealed partial class RynthLuaPlugin
StopAll("stopped");
ChatLine(n == 0 ? "No script is running." : $"Stopped {n} script(s).");
}
else ChatLine(StopScript(FindScript(rest)?.Name ?? rest) ? $"Stopped {rest}." : $"{rest} isn't running.");
else if (StopScript(FindScript(rest)?.Name ?? rest)) ChatLine($"Stopped {rest}.");
else ChatFail($"{rest} isn't running.");
break;
case "exec":
if (rest.Length == 0) { ChatLine("Usage: /lua exec <code>"); break; }
RunCode("exec", rest);
{
if (rest.Length == 0) { ChatFail("Usage: /lua exec <code>"); break; }
ScriptContext ran = RunCode("exec", rest);
// Its output and errors go to the script console (the Lua window); chat says whether it started.
if (ran.Host.Loaded) ChatLine("exec: started (its output is in the Lua window's console).");
else ChatFail("exec: the code didn't run" + LastConsoleError(ran));
break;
}
case "execin":
{
string[] p = rest.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries);
if (p.Length < 2) { ChatLine("Usage: /lua execin <script> <code>"); break; }
if (!_scripts.TryGetValue(p[0], out var ctx) || !ctx.Host.Loaded) { ChatLine($"{p[0]} isn't running."); break; }
ctx.Host.Exec(p[1]);
if (p.Length < 2) { ChatFail("Usage: /lua execin <script> <code>"); break; }
if (!_scripts.TryGetValue(p[0], out var ctx) || !ctx.Host.Loaded) { ChatFail($"{p[0]} isn't running."); break; }
if (ctx.Host.Exec(p[1])) ChatLine($"execin {ctx.Name}: started (its output is in {ctx.Name}'s console).");
else ChatFail($"execin {ctx.Name}: the code didn't run" + LastConsoleError(ctx));
break;
}
case "autostart":
@ -321,7 +330,7 @@ public sealed partial class RynthLuaPlugin
string mode = p.Length > 1 ? p[1].ToLowerInvariant() : "";
var e = p.Length > 0 ? FindScript(p[0]) : null;
if (e == null || mode is not ("none" or "global" or "character"))
{ ChatLine("Usage: /lua autostart <script> none|global|character"); break; }
{ ChatFail("Usage: /lua autostart <script> none|global|character"); break; }
SetAutostart(e.Name, mode);
ChatLine($"{e.Name}: autostart {mode}.");
break;
@ -340,12 +349,26 @@ public sealed partial class RynthLuaPlugin
HandleHudCommand(rest);
break;
default:
ChatLine("/lua list | start <script> | stop <script>|all | restart <script> | exec <code> | execin <script> <code> | autostart <script> none|global|character | hud list|show|hide|toggle <script>/<hud>|bench <n>|bench off");
{
// Bare /lua and /lua help: the usage. A word that is neither a verb nor a script's command: why, then the usage.
const string usage = "/lua list | start <script> | stop <script>|all | restart <script> | exec <code> | execin <script> <code> | autostart <script> none|global|character | hud list|show|hide|toggle <script>/<hud>|bench <n>|bench off";
if (sub is "" or "help" or "?") ChatLine(usage);
else ChatFail($"Unknown '/lua {sub}'. {usage}");
ChatLine("/lua <command> [args] runs a script command (game.RegisterCommand) - " + ScriptCommandsSummary());
break;
}
}
}
/// <summary>": " and the last error line in the script's console (why its code didn't run), or ".".</summary>
private static string LastConsoleError(ScriptContext ctx)
{
string[] lines = ctx.Host.ConsoleText().Split('\n');
for (int i = lines.Length - 1; i >= 0; i--)
if (lines[i].StartsWith("error", StringComparison.OrdinalIgnoreCase)) return ": " + lines[i].Trim();
return ".";
}
/// <summary>The registered script commands for the /lua usage text.</summary>
private string ScriptCommandsSummary()
{

View file

@ -793,16 +793,17 @@ public sealed partial class RynthLuaPlugin
string arg = p.Length > 1 ? p[1].Trim() : "";
if (arg.Equals("off", StringComparison.OrdinalIgnoreCase) || arg.Equals("stop", StringComparison.OrdinalIgnoreCase))
{
ChatLine(StopScript(BenchScript) ? "Bench stopped." : "The bench isn't running.");
if (StopScript(BenchScript)) ChatLine("Bench stopped.");
else ChatFail("The bench isn't running.");
break;
}
if (!int.TryParse(arg, NumberStyles.Integer, CultureInfo.InvariantCulture, out int n) || n < 1)
{
ChatLine("Usage: /lua hud bench <widgets 1-1500> | /lua hud bench off");
ChatFail("Usage: /lua hud bench <widgets 1-1500> | /lua hud bench off");
break;
}
n = Math.Min(n, 1500);
if (!UiAvailable) { ChatLine("Script windows need RynthCore API v71 with ImGui on."); break; }
if (!UiAvailable) { ChatFail("Script windows need RynthCore API v71 with ImGui on."); break; }
RunCode(BenchScript, BenchCode(n));
ChatLine($"Bench: a hud with {n} widgets. Measurements go to the log every ~10 s ('hud passes:' and 'ScriptWindows replay:'). /lua hud bench off to stop.");
break;
@ -818,7 +819,7 @@ public sealed partial class RynthLuaPlugin
ScriptHud? hud = FindHud(name, out string? problem);
if (hud == null)
{
ChatLine((problem ?? $"No hud named '{name}'.") + " " + HudListLine());
ChatFail((problem ?? $"No hud named '{name}'.") + " " + HudListLine());
break;
}
bool show = sub == "show" || sub == "toggle" && !hud.Visible;
@ -828,7 +829,8 @@ public sealed partial class RynthLuaPlugin
break;
}
default:
ChatLine("/lua hud list | show|hide|toggle <script>/<hud> | bench <widgets 1-1500> | bench off");
if (sub is "" or "help") ChatLine("/lua hud list | show|hide|toggle <script>/<hud> | bench <widgets 1-1500> | bench off");
else ChatFail($"Unknown '/lua hud {sub}'. /lua hud list | show|hide|toggle <script>/<hud> | bench <widgets 1-1500> | bench off");
break;
}
}

View file

@ -0,0 +1,34 @@
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
namespace RynthCore.Plugin.RynthNav;
/// <summary>
/// /rnav's lines for the words that used to answer nothing (2026-10-28: every command answers,
/// Plugins/Shared/CommandReply.cs): "recent" without "clear", "arrive" with no or a wrong number,
/// a word /rnav doesn't know. Pure, so RynthNav.RouteTests checks them.
/// </summary>
internal static class NavReplies
{
public const double ArriveMin = 2, ArriveMax = 200;
/// <summary>"/rnav arrive &lt;yards&gt;": the distance when it is one the arrow takes.</summary>
public static bool TryArrive(string rest, out double yards) =>
double.TryParse(rest, NumberStyles.Float, CultureInfo.InvariantCulture, out yards) && yards >= ArriveMin && yards <= ArriveMax;
public static string Arrived(double yards) => $"the arrow counts you as arrived within {yards:F0} yd";
/// <summary>"/rnav arrive" alone or with a wrong number: the value now and the usage.</summary>
public static string ArriveUsage(string rest, double now) =>
(rest.Trim().Length == 0 ? "" : $"'{rest.Trim()}' isn't {ArriveMin:F0}-{ArriveMax:F0} yd. ")
+ $"{Arrived(now)} — /rnav arrive <yards {ArriveMin:F0}-{ArriveMax:F0}>";
/// <summary>"/rnav recent": the recent places, newest first.</summary>
public static string Recent(IReadOnlyList<SavedPlace> recent) => recent.Count == 0
? "no recent places (arrow, route and go targets land here)"
: $"recent places ({recent.Count}): {string.Join(", ", recent.Select(p => p.Name))} — /rnav recent clear forgets them";
/// <summary>A word /rnav doesn't know.</summary>
public static string Unknown(string word) => $"unknown '{word}' — /rnav help";
}

View file

@ -46,6 +46,8 @@
<Compile Include="..\Shared\Nav3DText.cs" Link="Shared\Nav3DText.cs" />
<!-- Install folders (RynthAi's NavProfiles, where "save as nav route" writes). Read only. -->
<Compile Include="..\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
<!-- How a chat command answers (2026-10-28): the shared reply queue and colours. -->
<Compile Include="..\Shared\CommandReply.cs" Link="Shared\CommandReply.cs" />
<!-- RynthAi's own nav file reader/writer (uTank2 NAV 1.2), so a saved route is written exactly
the way RynthAi writes its own. Self-contained (System.IO only). -->
<Compile Include="..\RynthCore.Plugin.RynthAi\LegacyUi\NavRouteParser.cs" Link="Shared\NavRouteParser.cs" />

View file

@ -1051,6 +1051,7 @@ public sealed partial class RynthNavPlugin
case "fav": CmdFav(rest); break;
case "recent":
if (rest.Equals("clear", StringComparison.OrdinalIgnoreCase)) { _store.ClearRecent(); Say("recent places cleared"); }
else Say(NavReplies.Recent(_store.Recent));
break;
case "recalls": CmdRecalls(rest); break;
case "tie": CmdTie(rest); break;
@ -1058,10 +1059,11 @@ public sealed partial class RynthNavPlugin
case "mesh": CmdMesh(rest); break;
case "saveroute": CmdSaveRoute(rest); break;
case "arrive":
if (double.TryParse(rest, NumberStyles.Float, CultureInfo.InvariantCulture, out double yd) && yd >= 2 && yd <= 200)
{ _arrow.ArriveUnits = yd; Say($"the arrow counts you as arrived within {yd:F0} yd"); }
if (NavReplies.TryArrive(rest, out double yd)) { _arrow.ArriveUnits = yd; Say(NavReplies.Arrived(yd)); }
else if (rest.Length == 0) Say(NavReplies.ArriveUsage(rest, _arrow.ArriveUnits));
else SayFail(NavReplies.ArriveUsage(rest, _arrow.ArriveUnits));
break;
default: Say($"unknown '{cmd}' — /rnav help"); break;
default: SayFail(NavReplies.Unknown(cmd)); break;
}
}

View file

@ -136,6 +136,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
public override int Initialize()
{
_ = Reply;
_status = "initialized";
// Every use logged (Plugins/Shared/UseAudit.cs). No macro here: no door/corpse guard.
RynthCore.Plugin.Shared.UseAudit.Reset("RynthNav", null);
@ -183,7 +184,7 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
lock (_gotoGate) { _gotoPath = null; _gotoIdx = 0; }
_badTiles.Clear();
_tileRegions.Clear(); _tilePrints.Clear(); ResetCoarse();
_chatOut.Clear();
Reply.Clear();
_goNote = "";
HideMarkers("logged out");
_meshView.Clear(); _meshDunLb = 0;
@ -216,15 +217,15 @@ public sealed partial class RynthNavPlugin : RynthPluginBase
// Chat from the tick thread. The engine drops an off-thread WriteToChat that comes
// within 100 ms of any other plugin's (RynthAi writes often), so a line said here is
// queued and retried on later ticks until it goes through (one line per tick; a line
// that still can't be written after ~3 s is dropped so the queue never jams).
private readonly System.Collections.Concurrent.ConcurrentQueue<string> _chatOut = new();
private int _chatTries;
private void Say(string text) { if (_chatOut.Count < 64) _chatOut.Enqueue("[RynthNav] " + text); }
private void FlushChat()
{
if (!_chatOut.TryPeek(out string? line)) return;
if (Host.WriteToChat(line, 1) || ++_chatTries > 90) { _chatOut.TryDequeue(out _); _chatTries = 0; }
}
// that still can't be written after ~1.5 s goes to the log so the queue never jams).
// The queue is the shared one every plugin answers commands through (Plugins/Shared/CommandReply.cs).
private RynthCore.Plugin.Shared.CommandReply? _reply;
private RynthCore.Plugin.Shared.CommandReply Reply =>
_reply ??= new RynthCore.Plugin.Shared.CommandReply("[RynthNav]", (t, c) => Host.WriteToChat(t, c), t => Host.Log(t));
private void Say(string text) => Reply.Ok(text);
/// <summary>A command that didn't work: why, and the usage (the failure colour).</summary>
private void SayFail(string text) => Reply.Fail(text);
private void FlushChat() => Reply.Flush();
private uint CurrentLandblock => (_cellId >> 16) & 0xFFFF;

View file

@ -41,6 +41,8 @@
<ItemGroup>
<!-- Install-folder resolver (env, HKCU, HKLM, default C:\Games). Read only; same file as RynthCore src\Shared. -->
<Compile Include="..\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
<!-- How a chat command answers (2026-10-28): the shared reply queue and colours. -->
<Compile Include="..\Shared\CommandReply.cs" Link="Shared\CommandReply.cs" />
</ItemGroup>
<ItemGroup>
<!-- The Characters window (2026-10-21): RynthNet draws it with ImGui.NET bound to the engine's

View file

@ -44,7 +44,7 @@ public sealed partial class RynthNetPlugin
{
if (!CommandParser.TagsAndRest(args, out List<string> tags, out string after))
{
ChatLine("usage: /rn bct <tag[,tag]> [delayMs] <command>");
ChatFail("usage: /rn bct <tag[,tag]> [delayMs] <command>");
break;
}
CommandParser.DelayAndCommand(after, out int delay, out string command);
@ -57,12 +57,12 @@ public sealed partial class RynthNetPlugin
var known = node.GetPeers().Select(p => p.Identity.Character).Where(c => c.Length > 0);
if (!CommandParser.NameAndCommand(args, known, out string name, out string command))
{
ChatLine("usage: /rn tell <character>[,] <command>");
ChatFail("usage: /rn tell <character>[,] <command>");
break;
}
if (!node.GetPeers().Any(p => string.Equals(p.Identity.Character, name, StringComparison.OrdinalIgnoreCase)))
{
ChatLine($"no client is playing {name} (/rn list).");
ChatFail($"no client is playing {name} (/rn list).");
break;
}
Report(SendCommand(new NetTarget(TargetKind.Character, name), command, 0, includeSelf: false), command, name);
@ -93,7 +93,7 @@ public sealed partial class RynthNetPlugin
break;
case "followme":
{
if (!_loggedIn) { ChatLine("log in first."); break; }
if (!_loggedIn) { ChatFail("log in first."); break; }
NetTarget target = args.Length > 0 && CommandParser.TagsAndRest(args, out List<string> tags, out _)
? new NetTarget(TargetKind.Tags, string.Join(",", tags)) : NetTarget.All;
string command = "/ra follow " + _character;
@ -104,7 +104,7 @@ public sealed partial class RynthNetPlugin
case "useselected":
{
uint sel = Host.GetSelectedItemId();
if (sel == 0) { ChatLine("select something first."); break; }
if (sel == 0) { ChatFail("select something first."); break; }
NetTarget target = args.Length > 0 && CommandParser.TagsAndRest(args, out List<string> tags, out _)
? new NetTarget(TargetKind.Tags, string.Join(",", tags)) : NetTarget.All;
// The same command UtilityBelt's network window sends (RynthAi's meta expressions run it).
@ -113,7 +113,7 @@ public sealed partial class RynthNetPlugin
break;
}
default:
ChatLine($"unknown command '{verb}'. /rn help lists them.");
ChatFail($"unknown command '{verb}'. /rn help lists them.");
break;
}
}
@ -134,7 +134,7 @@ public sealed partial class RynthNetPlugin
{
if (!CommandParser.TagsAndRest(args, out List<string> tags, out string after))
{
ChatLine("usage: /ub bct <tag[,tag]> [millisecondDelay] <command>");
ChatFail("usage: /ub bct <tag[,tag]> [millisecondDelay] <command>");
break;
}
CommandParser.DelayAndCommand(after, out int delay, out string command);
@ -146,7 +146,7 @@ public sealed partial class RynthNetPlugin
ListClients(node, args);
break;
default:
ChatLine($"/ub {verb} isn't a network command.");
ChatFail($"/ub {verb} isn't a network command.");
break;
}
}
@ -154,7 +154,7 @@ public sealed partial class RynthNetPlugin
private void Report(List<string>? names, string command, string to)
{
if (names == null) return;
if (names.Count == 0) { ChatLine($"nobody to send '{command}' to ({to}). /rn list shows the clients."); return; }
if (names.Count == 0) { ChatFail($"nobody to send '{command}' to ({to}). /rn list shows the clients."); return; }
ChatLine($"'{command}' -> {string.Join(", ", names)}");
}
@ -188,7 +188,7 @@ public sealed partial class RynthNetPlugin
{
List<string> filter = new();
if (args.Length > 0) CommandParser.TagsAndRest(args, out filter, out _);
if (!node.IsRunning) { ChatLine("offline: " + (_offlineReason.Length > 0 ? _offlineReason : "stopped")); return; }
if (!node.IsRunning) { ChatFail("offline: " + (_offlineReason.Length > 0 ? _offlineReason : "stopped")); return; }
var peers = new List<PeerInfo>(node.GetPeers());
peers.Sort((a, b) => string.Compare(a.Identity.Character, b.Identity.Character, StringComparison.OrdinalIgnoreCase));
@ -252,7 +252,7 @@ public sealed partial class RynthNetPlugin
private void TagCommand(string args)
{
string verb = FirstWord(args, out string value).ToLowerInvariant();
if (!_loggedIn) { ChatLine("log in first: tags belong to a character."); return; }
if (!_loggedIn) { ChatFail("log in first: tags belong to a character."); return; }
switch (verb)
{
case "":
@ -260,12 +260,13 @@ public sealed partial class RynthNetPlugin
ChatLine(MyTags.Count > 0 ? $"{_character}'s tags: {string.Join(", ", MyTags)}" : $"{_character} has no tags. /rn tag add <tag>");
break;
case "add":
ChatLine(SetTag(value, on: true, out string whyAdd) ? $"tagged {_character}: {string.Join(", ", MyTags)}" : whyAdd);
if (SetTag(value, on: true, out string whyAdd)) ChatLine($"tagged {_character}: {string.Join(", ", MyTags)}");
else ChatFail(whyAdd);
break;
case "remove":
case "rm":
case "del":
if (!SetTag(value, on: false, out string whyRemove)) ChatLine(whyRemove);
if (!SetTag(value, on: false, out string whyRemove)) ChatFail(whyRemove);
else ChatLine(MyTags.Count > 0 ? $"{_character}'s tags: {string.Join(", ", MyTags)}" : $"{_character} has no tags now.");
break;
case "clear":
@ -273,7 +274,7 @@ public sealed partial class RynthNetPlugin
if (UpdateSettings(s => s.Character(key).Tags.Clear())) ChatLine($"{_character} has no tags now.");
break;
default:
ChatLine("usage: /rn tag [list | add <tag> | remove <tag> | clear]");
ChatFail("usage: /rn tag [list | add <tag> | remove <tag> | clear]");
break;
}
}
@ -308,7 +309,7 @@ public sealed partial class RynthNetPlugin
{
if (!node.IsRunning)
{
ChatLine("offline: " + (_offlineReason.Length > 0 ? _offlineReason : "stopped"));
ChatFail("offline: " + (_offlineReason.Length > 0 ? _offlineReason : "stopped"));
return;
}
RynthNetPolicy p = MyPolicy;
@ -332,7 +333,7 @@ public sealed partial class RynthNetPlugin
}
else if (a is "on" or "off" or "default")
{
if (!_loggedIn) { ChatLine("log in first: the policy belongs to a character (the file's \"defaults\" cover the rest)."); return; }
if (!_loggedIn) { ChatFail("log in first: the policy belongs to a character (the file's \"defaults\" cover the rest)."); return; }
if (a == "default")
UpdateSettings(s => { if (s.Characters.TryGetValue(key, out RynthNetCharacter? c)) c.Policy = null; });
else
@ -348,7 +349,7 @@ public sealed partial class RynthNetPlugin
}
else if (a.Length > 0)
{
ChatLine("usage: /rn remote on|off|default /rn remote log on|off");
ChatFail("usage: /rn remote on|off|default /rn remote log on|off");
return;
}
ChatLine($"commands from your other clients {(MyPolicy.AcceptRemoteCommands ? "run here" : "are refused here")}" +
@ -368,10 +369,10 @@ public sealed partial class RynthNetPlugin
}
if (verb is not ("add" or "remove" or "rm" or "clear") || (verb != "clear" && value.Length == 0))
{
ChatLine($"usage: /rn {name} [list | add <x> | remove <x> | clear] - {meaning}");
ChatFail($"usage: /rn {name} [list | add <x> | remove <x> | clear] - {meaning}");
return;
}
if (!_loggedIn) { ChatLine("log in first: the policy belongs to a character (the file's \"defaults\" cover the rest)."); return; }
if (!_loggedIn) { ChatFail("log in first: the policy belongs to a character (the file's \"defaults\" cover the rest)."); return; }
bool had = select(MyPolicy).Exists(x => string.Equals(x, value, StringComparison.OrdinalIgnoreCase));
string key = CharacterKey;
bool saved = UpdateSettings(s =>
@ -385,7 +386,7 @@ public sealed partial class RynthNetPlugin
});
if (!saved) return;
List<string> now = select(MyPolicy);
if (verb is "remove" or "rm" && !had) ChatLine($"{name} has no '{value}'.");
if (verb is "remove" or "rm" && !had) ChatFail($"{name} has no '{value}'.");
else ChatLine(now.Count == 0 ? $"{name}: empty." : $"{name}: {string.Join(" | ", now)}");
}
}

View file

@ -17,6 +17,7 @@ using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using RynthCore.Plugin.RynthNet.Transport;
using RynthCore.Plugin.Shared;
using RynthCore.PluginCore;
namespace RynthCore.Plugin.RynthNet;
@ -58,6 +59,7 @@ public sealed partial class RynthNetPlugin : RynthPluginBase
public override int Initialize()
{
_ = Reply;
// The Characters window draws with ImGui.NET bound to the engine's cimgui, in the engine's look.
RynthCore.Plugin.Shared.ImGuiNativeBinding.Ensure(msg => Host.Log("[RynthNet] " + msg));
RynthCore.Plugin.Shared.RynthUi.RynthUi.Init(Host);
@ -153,6 +155,7 @@ public sealed partial class RynthNetPlugin : RynthPluginBase
public override void OnTick()
{
Reply.Flush();
NetNode? node = _node;
if (node == null) return;
long now = NetNode.NowMs;
@ -184,7 +187,7 @@ public sealed partial class RynthNetPlugin : RynthPluginBase
// A typed /ub bc: RynthAi, when loaded, saw the same line and forwards its own copy.
if (queued.TypedUb && RynthAiLoaded()) continue;
try { HandleLocal(node, queued.Line); }
catch (Exception ex) { ChatLine($"'{queued.Line}' failed: {ex.Message}"); }
catch (Exception ex) { ChatFail($"'{queued.Line}' failed: {ex.Message}"); }
}
RunScheduled(now);
@ -250,18 +253,29 @@ public sealed partial class RynthNetPlugin : RynthPluginBase
});
}
private void ChatLine(string text)
// Chat lines wait in the shared reply queue (Plugins/Shared/CommandReply.cs): the host drops a line
// within 100 ms of another plugin's, so /rn help's and /rn list's later lines used to go missing.
private CommandReply? _reply;
private CommandReply Reply => _reply ??= new CommandReply("[RynthNet]",
(t, c) => Host.HasWriteToChat ? Host.WriteToChat(t, c) : LogInstead(t), t => Host.Log(t));
private bool LogInstead(string line)
{
if (Host.HasWriteToChat) Host.WriteToChat("[RynthNet] " + text, 1);
else Host.Log("[RynthNet] " + text);
Host.Log(line);
return true;
}
private void ChatLine(string text) => Reply.Ok(text);
/// <summary>A command that didn't work: why, and the usage (the failure colour).</summary>
private void ChatFail(string text) => Reply.Fail(text);
/// <summary>Applies one change to the shared settings file (merged with the other clients'), then pushes tags.</summary>
private bool UpdateSettings(Action<RynthNetSettings> change)
{
if (!RynthNetSettings.Update(change, out RynthNetSettings current, out string? error))
{
ChatLine("couldn't save settings: " + error);
ChatFail("couldn't save settings: " + error);
return false;
}
_settings = current;
@ -316,7 +330,7 @@ public sealed partial class RynthNetPlugin : RynthPluginBase
if (!e.Ok)
{
string what = _sent.TryGetValue(e.Id, out string? t) ? $"'{t}'" : "the command";
ChatLine($"{e.From} didn't run {what}: {e.Text}");
ChatFail($"{e.From} didn't run {what}: {e.Text}");
}
break;
case NetEventKind.Data:
@ -373,7 +387,7 @@ public sealed partial class RynthNetPlugin : RynthPluginBase
}
if (!Host.HasInvokeChatParser)
{
ChatLine("this engine can't run chat commands for plugins (no InvokeChatParser).");
ChatFail("this engine can't run chat commands for plugins (no InvokeChatParser).");
return;
}
// Same as typing it: plugins (/ra, /ub, /lua...) get it first, then AC.
@ -391,11 +405,11 @@ public sealed partial class RynthNetPlugin : RynthPluginBase
{
NetNode? node = _node;
command = (command ?? "").Trim();
if (command.Length == 0) { if (!quiet) ChatLine("no command given."); return null; }
if (command.Length > Wire.MaxText) { if (!quiet) ChatLine($"command too long (max {Wire.MaxText})."); return null; }
if (command.Length == 0) { if (!quiet) ChatFail("no command given."); return null; }
if (command.Length > Wire.MaxText) { if (!quiet) ChatFail($"command too long (max {Wire.MaxText})."); return null; }
if (CommandPolicy.Rebroadcasts(command))
{
if (!quiet) ChatLine("a broadcast can't contain another broadcast (/rn, /ub bc, /ub bct).");
if (!quiet) ChatFail("a broadcast can't contain another broadcast (/rn, /ub bc, /ub bct).");
return null;
}
delayMs = Math.Clamp(delayMs, 0, 600_000);

View file

@ -0,0 +1,77 @@
using RynthCore.Plugin.RynthOracle.Views;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthOracle;
internal enum OracleVerb { Window, Void, Timers, Quests, Tab, Trackers, Status, About, Help, Unknown }
/// <summary>A parsed "/ro ..." (the words after /ro, lower case): its verb, and the tab or the trackers it shows.</summary>
internal readonly record struct OracleCommand(OracleVerb Verb, string Tab = "", QuestKind? Trackers = null, string Word = "")
{
/// <summary>The verbs that show a window (they need the engine's plugin windows).</summary>
public bool ShowsWindow => Verb is OracleVerb.Window or OracleVerb.Void or OracleVerb.Timers or OracleVerb.Tab
or OracleVerb.Trackers or OracleVerb.About;
public static OracleCommand Parse(string? arg)
{
string a = (arg ?? string.Empty).Trim().ToLowerInvariant();
return a switch
{
"" => new(OracleVerb.Window),
"void" => new(OracleVerb.Void),
"timers" or "timer" => new(OracleVerb.Timers),
"quests" or "refresh" => new(OracleVerb.Quests),
// The main window on its Fellowship tab (RynthCore's Char menu and RynthAi's Mini Remote use this).
"fellowship" or "fellow" or "fship" => new(OracleVerb.Tab, OracleView.TabFellowship),
// The Character tab: the character overview and RynthAi's session. Shows, never toggles off.
"character" or "char" => new(OracleVerb.Tab, OracleView.TabCharacter),
// John's 30 Legendary Key quests: the Quests tab's Legendary rows.
"legendary" or "legend" or "john" => new(OracleVerb.Trackers, OracleView.TabQuests, QuestKind.Legendary),
// The 100 exploration markers: the Quests tab's marker rows (the old Markers tab).
"markers" or "marker" => new(OracleVerb.Trackers, OracleView.TabQuests, QuestKind.Marker),
// Every tracker: the Legendary Key quests and the exploration markers.
"trackers" => new(OracleVerb.Trackers, OracleView.TabQuests),
// The Skills tab: RynthCore's skills panel (raise and train) inside this window.
"skills" or "skill" => new(OracleVerb.Tab, OracleView.TabSkills),
"attributes" or "attrs" or "attribute" or "vitals" => new(OracleVerb.Tab, OracleView.TabAttributes),
"progress" or "progression" => new(OracleVerb.Tab, OracleView.TabProgress),
"status" => new(OracleVerb.Status),
"about" => new(OracleVerb.About, OracleView.TabAbout),
"help" or "?" => new(OracleVerb.Help),
_ => new(OracleVerb.Unknown, Word: a),
};
}
public const string Usage =
"Commands: /ro (window), /ro character (Character tab: status, session), "
+ "/ro skills|attributes|progress (those tabs), /ro void (Void window), "
+ "/ro timers (Quest Timers window), /ro fellowship (Fellowship tab), "
+ "/ro trackers (Quests tab, trackers only), /ro legendary (John's 30 key quests), /ro markers, "
+ "/ro quests (read quest flags), /ro status, "
+ "/ro about (About tab: settings, server, quest list). A server's own pages are its server plugin's (/rserver).";
public const string NoWindows =
"This RynthCore engine can't show plugin windows (it needs script windows, API v71, with ImGui on). /ro status still works.";
// ── What /ro answers (2026-10-28: every command answers, Plugins/Shared/CommandReply.cs) ──
public static string Shown(string window, bool shown) => CommandReply.Shown(window, shown);
public static string OnTab(string tab) => $"Oracle window shown on its {tab} tab.";
public static string OnTrackers(QuestKind? kind) => kind switch
{
QuestKind.Legendary => "Oracle window shown on the Quests tab: the Legendary Key quests.",
QuestKind.Marker => "Oracle window shown on the Quests tab: the exploration markers.",
_ => "Oracle window shown on the Quests tab: every tracker.",
};
/// <summary>"/ro quests": a /myquests sent, or why not (out of the world, the server's one-a-minute limit, one already out).</summary>
public static (bool Ok, string Text) Quests(bool inWorld, bool sent, int waitSeconds) =>
!inWorld ? (false, "Log in first: the quest flags come from the server's /myquests.")
: sent ? (true, "Reading your quest flags (/myquests)...")
: waitSeconds > 0 ? (false, $"The server answers one /myquests a minute; try again in {waitSeconds}s (the flags shown are kept).")
: (false, "/myquests was sent moments ago; waiting for that reply.");
public static string Unknown(string word) => $"Unknown '/ro {word}'. {Usage}";
}

View file

@ -1,6 +1,7 @@
using System;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthOracle.Data;
using RynthCore.Plugin.Shared;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthOracle;
@ -81,11 +82,24 @@ internal sealed class OracleContext
public Func<uint, int> Props => id => Character.Int(Host, id);
/// <summary>
/// The plugin's chat lines, queued and written by the tick (Plugins/Shared/CommandReply.cs: the host
/// drops a line within 100 ms of another plugin's, so a quest's several lines used to go missing).
/// Null before Initialize (and in the offline tests, which use <see cref="PrintSink"/>).
/// </summary>
public CommandReply? Reply;
/// <summary>A line in the player's chat window only (nothing is sent to the server).</summary>
public void Print(string text)
public void Print(string text) => Print(text, ok: true);
/// <summary>A line saying a command didn't work (the failure colour).</summary>
public void PrintFail(string text) => Print(text, ok: false);
private void Print(string text, bool ok)
{
if (PrintSink != null) { PrintSink(text); return; }
if (!Host.WriteToChat("[RynthOracle] " + text, 1))
if (Reply != null) { Reply.Say(ok, text); return; }
if (!Host.WriteToChat("[RynthOracle] " + text, ok ? CommandReply.OkChatType : CommandReply.FailChatType))
Host.Log("[RynthOracle] " + text);
}

View file

@ -64,6 +64,8 @@
<!-- "RynthServer.QuestPack": the active server plugin's quest pack, merged into the Quests list. -->
<Compile Include="..\Shared\RynthServerQuestPackApi.cs" Link="Shared\RynthServerQuestPackApi.cs" />
<Compile Include="..\Shared\ServerQuestPackClient.cs" Link="Shared\ServerQuestPackClient.cs" />
<!-- How a chat command answers (2026-10-28): the shared reply queue and colours. -->
<Compile Include="..\Shared\CommandReply.cs" Link="Shared\CommandReply.cs" />
</ItemGroup>
<ItemGroup>

View file

@ -3,6 +3,7 @@ using System.Collections.Concurrent;
using RynthCore.Plugin.RynthOracle.Data;
using RynthCore.Plugin.RynthOracle.Ui;
using RynthCore.Plugin.RynthOracle.Views;
using RynthCore.Plugin.Shared;
using RynthCore.PluginCore;
namespace RynthCore.Plugin.RynthOracle;
@ -46,7 +47,6 @@ public sealed class RynthOraclePlugin : RynthPluginBase
private int _seenFlagRevision = -1, _seenCatalogRevision = -1, _seenVoidRevision = -1;
// RynthCore's server list (ServerStateClient.Revision) last applied to the server identity.
private int _seenServerStateRevision = -1;
private bool _noUiLogged;
private string? _catalogKey; // what the catalog was loaded for (QuestPackSource.Key; "" = retail only)
private int _seenPackRevision = -1; // the active server plugin's quest pack (ServerQuestPackClient.Revision)
private int _titleCount = -2;
@ -55,6 +55,7 @@ public sealed class RynthOraclePlugin : RynthPluginBase
public override int Initialize()
{
_c.Host = Host;
_c.Reply = new CommandReply("[RynthOracle]", (t, c) => Host.WriteToChat(t, c), t => Host.Log(t));
_c.Settings.Load();
_c.RequestQuests = RequestQuests;
_c.RereadCharacter = RereadCharacter;
@ -306,91 +307,62 @@ public sealed class RynthOraclePlugin : RynthPluginBase
private void RunCommand(string arg)
{
switch (arg)
// Every /ro answers in chat (2026-10-28, OracleCommand.cs; Plugins/Shared/CommandReply.cs). RynthOracle
// can't tell a typed /ro from a meta's or another plugin's menu (they all come through chat), so
// each one does.
OracleCommand c = OracleCommand.Parse(arg);
// A window shown: says so, or (an engine without plugin windows) why nothing shows.
void Shown(string text)
{
case "":
if (_main != null) { _main.Visible = !_main.Visible; _main.NeedsPass = true; }
if (Host.HasUi) _c.Print(text);
else _c.PrintFail(OracleCommand.NoWindows);
}
switch (c.Verb)
{
case OracleVerb.Window:
if (_main != null) { _main.Visible = !_main.Visible; _main.NeedsPass = true; Shown(OracleCommand.Shown("Oracle window", _main.Visible)); }
break;
case "void":
if (_void != null) { _void.Visible = !_void.Visible; _void.NeedsPass = true; }
case OracleVerb.Void:
if (_void != null) { _void.Visible = !_void.Visible; _void.NeedsPass = true; Shown(OracleCommand.Shown("Void window", _void.Visible)); }
break;
case "timers":
case "timer":
if (_timers != null) SetQuestTimers(!_timers.Visible);
case OracleVerb.Timers:
if (_timers != null) { SetQuestTimers(!_timers.Visible); Shown(OracleCommand.Shown("Quest Timers window", _timers.Visible)); }
break;
case "quests":
case "refresh":
RequestQuests();
case OracleVerb.Quests:
{
bool sent = RequestQuests();
var (ok, text) = OracleCommand.Quests(_c.InWorld, sent, _c.Flags.ThrottleSecondsLeft(Environment.TickCount64));
if (ok) _c.Print(text); else _c.PrintFail(text);
break;
case "fellowship":
case "fellow":
case "fship":
// The main window on its Fellowship tab (RynthCore's Char menu and RynthAi's Mini Remote use this).
ShowTab(OracleView.TabFellowship);
}
case OracleVerb.Tab:
// RynthAi, the server plugins and RynthCore's menus link to these; they show, never toggle off.
ShowTab(c.Tab);
Shown(OracleCommand.OnTab(c.Tab));
break;
case "character":
case "char":
// The Character tab: the character overview and RynthAi's session.
// RynthAi, the server plugins and RynthCore's menus link here; it shows, never toggles off.
ShowTab(OracleView.TabCharacter);
case OracleVerb.Trackers:
// A server's own trackers and tabs are its server plugin's pages (since 2026-10-21).
ShowTrackers(c.Trackers);
Shown(OracleCommand.OnTrackers(c.Trackers));
break;
case "legendary":
case "legend":
case "john":
// John's 30 Legendary Key quests: the Quests tab's Legendary rows.
ShowTrackers(QuestKind.Legendary);
break;
case "markers":
case "marker":
// The 100 exploration markers: the Quests tab's marker rows (the old Markers tab).
ShowTrackers(QuestKind.Marker);
break;
case "trackers":
// Every tracker: the Legendary Key quests and the exploration markers. A server's own
// trackers and tabs are its server plugin's pages (since 2026-10-21).
ShowTrackers(null);
break;
case "skills":
case "skill":
// The Skills tab: RynthCore's skills panel (raise and train) inside this window.
ShowTab(OracleView.TabSkills);
break;
case "attributes":
case "attrs":
case "attribute":
case "vitals":
ShowTab(OracleView.TabAttributes);
break;
case "progress":
case "progression":
ShowTab(OracleView.TabProgress);
break;
case "status":
case OracleVerb.Status:
string titles = _c.TitlesKnown ? $", {_c.EarnedTitles.Count} titles held" : "";
_c.Print($"Server: {_c.Server.DisplayName} ({_c.Server.Source}). "
+ $"{_c.Flags.Flags.Count} quest flags read, {_c.Catalog.RetailCount} retail quests{PackText()}, {_c.Void.Dots.Count} Void spells tracked{titles}.");
break;
case "about":
case OracleVerb.About:
// The About tab (settings, the server RynthCore says this is, the quest list).
_c.Print("Based on Oracle of Dereth by Advis Eveldan - thank you! github.com/advis61/OracleOfDereth (MIT)");
ShowTab(OracleView.TabAbout);
ShowTab(c.Tab);
if (!Host.HasUi) _c.PrintFail(OracleCommand.NoWindows);
break;
case OracleVerb.Help:
_c.Print(OracleCommand.Usage);
break;
default:
_c.Print("Commands: /ro (window), /ro character (Character tab: status, session), "
+ "/ro skills|attributes|progress (those tabs), /ro void (Void window), "
+ "/ro timers (Quest Timers window), /ro fellowship (Fellowship tab), "
+ "/ro trackers (Quests tab, trackers only), /ro legendary (John's 30 key quests), /ro markers, "
+ "/ro quests (read quest flags), /ro status, "
+ "/ro about (About tab: settings, server, quest list). A server's own pages are its server plugin's (/rserver).");
_c.PrintFail(OracleCommand.Unknown(c.Word));
break;
}
if (arg is "" or "void" or "timers" or "timer" or "fellowship" or "fellow" or "fship" or "character" or "char"
or "skills" or "skill" or "attributes" or "attrs" or "attribute" or "vitals" or "progress" or "progression"
or "legendary" or "legend" or "john" or "markers" or "marker" or "trackers" or "about" && !Host.HasUi && !_noUiLogged)
{
_noUiLogged = true;
_c.Print("This RynthCore engine can't show plugin windows (it needs script windows, API v71, with ImGui on). /ro status still works.");
}
}
/// <summary>Sends /myquests; false when nothing went out (not in the world, or one was sent moments ago).</summary>
@ -462,6 +434,7 @@ public sealed class RynthOraclePlugin : RynthPluginBase
_c.UtcNow = DateTime.UtcNow;
while (_commands.TryDequeue(out string? cmd)) RunCommand(cmd);
_c.Reply?.Flush();
_ui.Poll(Host);
TickData(now);

View file

@ -60,6 +60,22 @@ public static unsafe class PluginExports
try { return Runtime.Plugin?.AutoState ?? -1; } catch { return -1; }
}
// The same state for RynthAi's own dashboard (2026-10-23): a plugin reads another's exports only
// through the engine's RynthPluginGet*Json broker (GetPluginExportJson). {"auto":-1|0|1}, a
// literal (nothing to free).
[UnmanagedCallersOnly(EntryPoint = "RynthPluginGetAutoSortJson", CallConvs = new[] { typeof(CallConvCdecl) })]
public static IntPtr AutoSortJson()
{
int state;
try { state = Runtime.Plugin?.AutoState ?? -1; } catch { state = -1; }
return state switch
{
1 => LiteralPointer("{\"auto\":1}"u8),
0 => LiteralPointer("{\"auto\":0}"u8),
_ => LiteralPointer("{\"auto\":-1}"u8),
};
}
[UnmanagedCallersOnly(EntryPoint = "RynthSortCommand", CallConvs = new[] { typeof(CallConvCdecl) })]
public static void Command(IntPtr utf8)
{

View file

@ -40,6 +40,8 @@
<Compile Include="..\Shared\RynthAiStatusApi.cs" Link="Shared\RynthAiStatusApi.cs" />
<!-- Install-folder resolver (env, HKCU, HKLM, default C:\Games). Read only; same file as RynthCore src\Shared. -->
<Compile Include="..\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
<!-- How a chat command answers (2026-10-28): the shared reply queue and colours. -->
<Compile Include="..\Shared\CommandReply.cs" Link="Shared\CommandReply.cs" />
</ItemGroup>
<ItemGroup>

View file

@ -6,6 +6,7 @@ using System.Text.Json;
using RynthCore.Plugin.RynthSort.Sorting;
using RynthCore.Plugin.RynthSort.Ui;
using RynthCore.Plugin.RynthSort.Views;
using RynthCore.Plugin.Shared;
using RynthCore.PluginCore;
namespace RynthCore.Plugin.RynthSort;
@ -52,7 +53,6 @@ public sealed class RynthSortPlugin : RynthPluginBase
private string _character = string.Empty;
private long _saveDueMs;
private bool _vendorOpen;
private bool _noUiLogged;
private bool _backupOnSave;
private readonly List<string> _warnings = new();
private volatile int _autoState = -1;
@ -75,6 +75,7 @@ public sealed class RynthSortPlugin : RynthPluginBase
public override int Initialize()
{
_reply = new CommandReply("[RynthSort]", (t, c) => Host.WriteToChat(t, c), t => Host.Log(t));
_ui.Log = msg => Host.Log(msg);
_world = new HostSortWorld(Host, _reader, _loot, () => _vendorOpen);
_sort.SettingsChanged = RequestSave;
@ -144,49 +145,50 @@ public sealed class RynthSortPlugin : RynthPluginBase
private void RunCommand(string arg)
{
string[] words = arg.Split(' ', StringSplitOptions.RemoveEmptyEntries);
string word = words.Length > 0 ? words[0].ToLowerInvariant() : string.Empty;
if (word.Length > 0 && !_identityKnown && word is not ("help" or "?"))
// Every /rsort answers in chat (2026-10-28, SortCommand.cs; Plugins/Shared/CommandReply.cs). RynthSort
// can't tell a typed /rsort from a meta's or RynthAi's /ub packsort, so each one does; only the
// dashboard's "on quiet" / "off quiet" (it shows the state itself) is logged instead.
SortCommand c = SortCommand.Parse(arg);
if (c.NeedsLogin && !_identityKnown)
{
Print("Log in first.");
PrintFail("Log in first.");
return;
}
switch (word)
switch (c.Verb)
{
case "":
if (_window != null) { _window.Visible = !_window.Visible; _window.NeedsPass = true; }
if (_window != null && _window.Visible && !Host.HasUi && !_noUiLogged)
case SortVerb.Window:
if (_window != null)
{
_noUiLogged = true;
Print("This RynthCore engine can't show plugin windows (it needs script windows, API v71, with ImGui on). Sorting still runs: /rsort on|off|now|tidy|clean|unpack.");
_window.Visible = !_window.Visible; _window.NeedsPass = true;
if (Host.HasUi) Print(SortCommand.Window(_window.Visible));
else PrintFail(SortCommand.NoWindows);
}
break;
case "on":
case "off":
_sort.SetAuto(word == "on");
// "quiet": the dashboard's toggle, which shows the state itself.
if (!(words.Length > 1 && words[1].Equals("quiet", StringComparison.OrdinalIgnoreCase)))
Print("Auto-sort " + word);
case SortVerb.On:
case SortVerb.Off:
_sort.SetAuto(c.Verb == SortVerb.On);
_reply.Ok("Auto-sort " + (c.Verb == SortVerb.On ? "on" : "off"), quiet: c.Quiet);
break;
case "now":
case "tidy":
case SortVerb.Now:
_sort.StartJob(SortScope.All);
Print(SortCommand.Started(c.Verb));
break;
case "clean":
case SortVerb.Clean:
_sort.StartJob(SortScope.Clean);
Print(SortCommand.Started(c.Verb));
break;
case "unpack":
{
int? n = words.Length > 1 && int.TryParse(words[1], out int p) && p > 0 ? p : null;
_sort.StartUnpack(n);
Print((n != null ? $"Emptying pack {n}" : "Emptying your side packs") + " into the main pack; auto-sort is off (/rsort on when done).");
case SortVerb.Unpack:
_sort.StartUnpack(c.Pack);
Print(SortCommand.Unpacking(c.Pack));
break;
}
case "status":
case SortVerb.Status:
PrintStatus();
break;
case SortVerb.Help:
Print(SortCommand.Usage);
break;
default:
Print("/rsort [on | off | now | tidy | clean | unpack [pack] | status]");
PrintFail(SortCommand.Unknown(c.Word));
break;
}
if (_window != null) _window.NeedsPass = true;
@ -199,11 +201,13 @@ public sealed class RynthSortPlugin : RynthPluginBase
+ $"{v.Packs.Count} side packs, main pack {v.MainUsed}/{v.MainCapacity}; moved {_sort.Moved}, failed {_sort.Failed} this session.");
}
private void Print(string text)
{
if (!Host.WriteToChat("[RynthSort] " + text, 1))
Host.Log("[RynthSort] " + text);
}
// Chat lines wait in the shared reply queue (the host drops a line within 100 ms of another
// plugin's); the tick writes them.
private CommandReply _reply = null!;
private void Print(string text) => _reply.Ok(text);
private void PrintFail(string text) => _reply.Fail(text);
// ── Tick ────────────────────────────────────────────────────────────────
@ -211,6 +215,7 @@ public sealed class RynthSortPlugin : RynthPluginBase
{
long now = Environment.TickCount64;
while (_commands.TryDequeue(out string? cmd)) RunCommand(cmd);
_reply.Flush();
_ui.Poll(Host);
if (_inWorld)

View file

@ -0,0 +1,54 @@
using System;
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthSort;
internal enum SortVerb { Window, On, Off, Now, Clean, Unpack, Status, Help, Unknown }
/// <summary>
/// A parsed "/rsort ..." and the lines it answers with (2026-10-28: every command answers,
/// Plugins/Shared/CommandReply.cs). <see cref="Quiet"/>: "on quiet" / "off quiet", the engine
/// dashboard's toggle, which shows the state itself (its success is logged only). Pure, so
/// RynthSort.Tests checks every word.
/// </summary>
internal readonly record struct SortCommand(SortVerb Verb, int? Pack = null, bool Quiet = false, string Word = "")
{
public static SortCommand Parse(string? arg)
{
string[] words = (arg ?? string.Empty).Split(' ', StringSplitOptions.RemoveEmptyEntries);
string word = words.Length > 0 ? words[0].ToLowerInvariant() : string.Empty;
bool quiet = words.Length > 1 && words[1].Equals("quiet", StringComparison.OrdinalIgnoreCase);
return word switch
{
"" => new(SortVerb.Window),
"on" => new(SortVerb.On, Quiet: quiet),
"off" => new(SortVerb.Off, Quiet: quiet),
"now" or "tidy" => new(SortVerb.Now),
"clean" => new(SortVerb.Clean),
"unpack" => new(SortVerb.Unpack, words.Length > 1 && int.TryParse(words[1], out int p) && p > 0 ? p : null),
"status" => new(SortVerb.Status),
"help" or "?" => new(SortVerb.Help),
_ => new(SortVerb.Unknown, Word: word),
};
}
/// <summary>The window and help work before the character is known; everything else waits for it.</summary>
public bool NeedsLogin => Verb is not (SortVerb.Window or SortVerb.Help);
public const string Usage = "/rsort [on | off | now | tidy | clean | unpack [pack] | status]";
public const string NoWindows =
"This RynthCore engine can't show plugin windows (it needs script windows, API v71, with ImGui on). Sorting still runs: /rsort on|off|now|tidy|clean|unpack.";
public static string Window(bool shown) => CommandReply.Shown("RynthSort window", shown);
/// <summary>"/rsort now|tidy|clean": the job that starts (it runs as soon as the way is clear).</summary>
public static string Started(SortVerb verb) => verb == SortVerb.Clean
? "Cleaning: every pack sorted, items no rule wants back to the main pack."
: "Sorting every pack now.";
public static string Unpacking(int? pack) =>
(pack != null ? $"Emptying pack {pack}" : "Emptying your side packs") + " into the main pack; auto-sort is off (/rsort on when done).";
public static string Unknown(string word) => $"Unknown '/rsort {word}'. Usage: {Usage}";
}

View file

@ -191,6 +191,11 @@ internal static class DungeonLight
public const string Usage =
"/rv light [on|off] | 0-100 (strength) | dungeons|indoors|everywhere | color RRGGBB|white|torch|moon | show | status";
/// <summary>What /rv light says after a change: the light's settings now (and why it can't light on an old engine).</summary>
public static string Summary(bool on, int strength, LightScope scope, uint colorArgb, bool engineHasApi) =>
$"Dungeon light {(on ? "on" : "off")}: strength {strength}%, {ScopeWord(scope)}, {ColorName(colorArgb)}."
+ (engineHasApi ? "" : " Needs a newer RynthCore (plugin API 91) to light anything.");
/// <summary>One line for chat and the Light tab: what the light is doing here and why.</summary>
public static string StatusLine(in LightStatus s)
{

View file

@ -40,6 +40,8 @@
<Compile Include="..\Shared\SafeImGui.cs" Link="Shared\SafeImGui.cs" />
<Compile Include="..\Shared\RynthUi\RynthUi.cs" Link="Shared\RynthUi\RynthUi.cs" />
<Compile Include="..\Shared\RynthUi\RynthIcons.cs" Link="Shared\RynthUi\RynthIcons.cs" />
<!-- How a chat command answers (2026-10-28): the shared reply queue and colours. -->
<Compile Include="..\Shared\CommandReply.cs" Link="Shared\CommandReply.cs" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="ImGui.NET" Version="1.91.6.1" />

View file

@ -170,9 +170,10 @@ public sealed partial class RynthVisionPlugin
if (_hostsWindow && Host.SetPanelOpen(VisionManifest.Title, RynthPanelOpen.Open) >= 0)
{
RequestTab(VisionTab.Light);
LightChat("Vision window shown, on its Light tab.");
return;
}
LightChat("The Vision window's Light tab needs a newer RynthCore (plugin API 91); " + DungeonLight.Usage);
LightChat("The Vision window's Light tab needs a newer RynthCore (plugin API 91); " + DungeonLight.Usage, ok: false);
return;
case LightCommandKind.Status:
LightChat("Dungeon light: " + DungeonLight.StatusLine(CurrentLightStatus(Host.HasAmbientLight)));
@ -181,21 +182,18 @@ public sealed partial class RynthVisionPlugin
LightChat(DungeonLight.Usage);
return;
default:
LightChat(cmd.Error + " " + DungeonLight.Usage);
LightChat(cmd.Error + " " + DungeonLight.Usage, ok: false);
return;
}
s.Save();
MarkSettingsChanged();
string summary = $"Dungeon light {(s.LightOn ? "on" : "off")}: strength {s.LightStrength}%, " +
$"{DungeonLight.ScopeWord((LightScope)s.LightScope)}, {DungeonLight.ColorName(s.LightColorArgb)}.";
if (!Host.HasAmbientLight)
summary += " Needs a newer RynthCore (plugin API 91) to light anything.";
LightChat(summary);
LightChat(DungeonLight.Summary(s.LightOn, s.LightStrength, (LightScope)s.LightScope, s.LightColorArgb, Host.HasAmbientLight));
}
private void LightChat(string text)
/// <summary>/rv light's answer: the log, and chat through the reply queue (Plugins/Shared/CommandReply.cs).</summary>
private void LightChat(string text, bool ok = true)
{
Host.Log("[RynthVision] " + text);
if (Host.HasWriteToChat) Host.WriteToChat("[RynthVision] " + text, 1);
_reply.Say(ok, text);
}
}

View file

@ -69,7 +69,7 @@ public sealed partial class RynthVisionPlugin
});
/// <summary>"Log terrain types here": on the tick (it may open the terrain data). Any thread.</summary>
internal void QueueInspectTerrain() => _uiActions.Enqueue(InspectTerrain);
internal void QueueInspectTerrain(bool toChat = false) => _uiActions.Enqueue(() => InspectTerrain(toChat));
/// <summary>Asks the window to show <paramref name="tab"/> on its next draw. Any thread.</summary>
private void RequestTab(VisionTab tab) => Volatile.Write(ref _tabRequest, (int)tab);

View file

@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.Diagnostics;
using RynthCore.Plugin.RynthAi.Raycasting;
using RynthCore.Plugin.RynthVision.Overlays;
using RynthCore.Plugin.Shared;
using RynthCore.PluginCore;
using RynthCore.TerrainData;
@ -49,8 +50,12 @@ public sealed partial class RynthVisionPlugin : RynthPluginBase
private bool _debug;
private int _dbgTick;
// What /rv says, queued and written by the tick (Plugins/Shared/CommandReply.cs).
private CommandReply _reply = null!;
public override int Initialize()
{
_reply = new CommandReply("[RynthVision]", (t, c) => Host.WriteToChat(t, c), t => Host.Log(t));
// The Vision window draws with ImGui.NET bound to the engine's cimgui, in its look.
RynthCore.Plugin.Shared.ImGuiNativeBinding.Ensure(msg => Host.Log("[RynthVision] " + msg));
RynthCore.Plugin.Shared.RynthUi.RynthUi.Init(Host);
@ -87,6 +92,7 @@ public sealed partial class RynthVisionPlugin : RynthPluginBase
{
// The window's, /rv's and the light's changes first: this tick draws with them.
TickUi();
_reply.Flush();
// One pose for the light and every overlay this tick.
bool inWorld = Host.TryGetPlayerPose(out uint cellId, out float x, out float y, out float z,
@ -174,26 +180,35 @@ public sealed partial class RynthVisionPlugin : RynthPluginBase
string arg = text.Length > 3 ? text.Substring(3).Trim().ToLowerInvariant() : string.Empty;
// Every /rv answers in chat (2026-10-28, VisionCommands.cs; Plugins/Shared/CommandReply.cs). RynthVision
// can't tell a typed /rv from a meta's, so each one does.
VisionVerb verb = VisionCommands.Parse(arg, out string lightArgs);
// "/rv light ..." (Light/DungeonLight.ParseCommand): applied and answered in chat on the tick.
if (arg == "light" || arg.StartsWith("light ", StringComparison.Ordinal))
if (verb == VisionVerb.Light)
{
QueueLightCommand(arg.Substring(5));
QueueLightCommand(lightArgs);
return;
}
// The settings are the tick's (the Vision window reads the copy it publishes): toggles go through
// its queue, like the window's own changes.
Action<VisionSettings>? toggle;
switch (arg)
switch (verb)
{
case "radar": toggle = static st => st.ShowRadarRing = !st.ShowRadarRing; break;
case "slopes": toggle = static st => st.ShowUnclimbableSlopes = !st.ShowUnclimbableSlopes; break;
case "water": toggle = static st => st.ShowImpassableWater = !st.ShowImpassableWater; break;
case "watertypes": QueueInspectTerrain(); return;
case "debug": _debug = !_debug; Host.Log($"[RynthVision] debug = {_debug}"); return;
case "": toggle = null; break;
case VisionVerb.Radar: toggle = static st => st.ShowRadarRing = !st.ShowRadarRing; break;
case VisionVerb.Slopes: toggle = static st => st.ShowUnclimbableSlopes = !st.ShowUnclimbableSlopes; break;
case VisionVerb.Water: toggle = static st => st.ShowImpassableWater = !st.ShowImpassableWater; break;
case VisionVerb.WaterTypes: QueueInspectTerrain(toChat: true); return;
case VisionVerb.Debug:
_debug = !_debug;
Host.Log($"[RynthVision] debug = {_debug}");
_reply.Ok(VisionCommands.Debug(_debug));
return;
case VisionVerb.Status: toggle = null; break;
default:
Host.Log($"[RynthVision] Unknown option '{arg}'. Use radar | slopes | water | watertypes | debug | light.");
_reply.Fail(VisionCommands.Unknown(arg));
return;
}
@ -203,6 +218,13 @@ public sealed partial class RynthVisionPlugin : RynthPluginBase
_settings.Save();
MarkSettingsChanged();
Host.Log($"[RynthVision] radar={_settings.ShowRadarRing} slopes={_settings.ShowUnclimbableSlopes} water={_settings.ShowImpassableWater}");
_reply.Ok(verb switch
{
VisionVerb.Radar => VisionCommands.Switched(verb, _settings.ShowRadarRing),
VisionVerb.Slopes => VisionCommands.Switched(verb, _settings.ShowUnclimbableSlopes),
VisionVerb.Water => VisionCommands.Switched(verb, _settings.ShowImpassableWater),
_ => VisionCommands.State(_settings.ShowRadarRing, _settings.ShowUnclimbableSlopes, _settings.ShowImpassableWater),
});
});
}
@ -245,20 +267,28 @@ public sealed partial class RynthVisionPlugin : RynthPluginBase
/// which indices belong in VisionSettings.WaterTerrainTypes. An explicit
/// request, so it opens the terrain data if the overlays haven't.
/// </summary>
internal void InspectTerrain()
internal void InspectTerrain() => InspectTerrain(toChat: false);
/// <summary><paramref name="toChat"/>: /rv watertypes, which answers in chat as well as the log.</summary>
internal void InspectTerrain(bool toChat)
{
if (!_terrain.IsReady && !InitTerrain())
{
if (toChat) _reply.Fail($"Terrain data unavailable: {_terrain.Status}.");
return;
}
if (!Host.TryGetPlayerPose(out uint cellId, out float px, out float py, out _, out _, out _, out _, out _) ||
(cellId & 0xFFFF) >= 0x100 || (cellId >> 16) == 0)
{
Host.Log("[RynthVision] Stand outdoors to inspect terrain types.");
if (toChat) _reply.Fail("Stand outdoors to inspect terrain types.");
return;
}
LandblockData? lb = _terrain.LoadLandblock(cellId >> 16);
if (lb == null)
{
Host.Log("[RynthVision] No terrain data for this landblock.");
if (toChat) _reply.Fail("No terrain data for this landblock.");
return;
}
@ -272,5 +302,6 @@ public sealed partial class RynthVisionPlugin : RynthPluginBase
seen.Add(TerrainSampler.GetTerrainType(lb, ix, iy));
Host.Log($"[RynthVision] At cell ({cx},{cy}) terrain type = {hereType}. Landblock types: {string.Join(", ", seen)}");
if (toChat) _reply.Ok($"At cell ({cx},{cy}) terrain type = {hereType}. Landblock types: {string.Join(", ", seen)}");
}
}

View file

@ -0,0 +1,61 @@
// ============================================================================
// RynthVision - VisionCommands.cs
// The /rv chat command's words and what it answers (2026-10-28: every
// command answers in chat, Plugins/Shared/CommandReply.cs). "/rv light ..."
// is Light/DungeonLight.cs's. Pure, so RynthVision.Tests checks every verb.
// ============================================================================
using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthVision;
internal enum VisionVerb { Status, Radar, Slopes, Water, WaterTypes, Debug, Light, Unknown }
internal static class VisionCommands
{
public const string Usage = "/rv [radar | slopes | water] (show or hide) | watertypes | debug | light ... (/rv light help)";
/// <summary>The words after "/rv" (lower case): the verb, and for light what follows it.</summary>
public static VisionVerb Parse(string arg, out string lightArgs)
{
lightArgs = string.Empty;
string a = (arg ?? string.Empty).Trim().ToLowerInvariant();
if (a == "light" || a.StartsWith("light ", System.StringComparison.Ordinal))
{
lightArgs = a.Substring(5);
return VisionVerb.Light;
}
return a switch
{
"" => VisionVerb.Status,
"radar" => VisionVerb.Radar,
"slopes" => VisionVerb.Slopes,
"water" => VisionVerb.Water,
"watertypes" => VisionVerb.WaterTypes,
"debug" => VisionVerb.Debug,
_ => VisionVerb.Unknown,
};
}
/// <summary>The overlay a verb switches: its name in chat.</summary>
public static string OverlayName(VisionVerb verb) => verb switch
{
VisionVerb.Radar => "Radar ring",
VisionVerb.Slopes => "Unclimbable slopes",
VisionVerb.Water => "Impassable water",
_ => verb.ToString(),
};
/// <summary>"/rv radar": the overlay's new state.</summary>
public static string Switched(VisionVerb verb, bool on) => $"{OverlayName(verb)} {CommandReply.OnOff(on)}.";
/// <summary>"/rv" alone: the overlays' state and the usage.</summary>
public static string State(bool radar, bool slopes, bool water) =>
$"Radar ring {CommandReply.OnOff(radar)}, unclimbable slopes {CommandReply.OnOff(slopes)}, impassable water {CommandReply.OnOff(water)}. {Usage}";
/// <summary>"/rv debug": the pose stream's new state.</summary>
public static string Debug(bool on) => $"Debug {CommandReply.OnOff(on)} (the player's pose and the overlays' landblock lines go to the log).";
/// <summary>A word /rv doesn't know.</summary>
public static string Unknown(string arg) => $"Unknown '/rv {(arg ?? string.Empty).Trim()}'. Usage: {Usage}";
}

View file

@ -0,0 +1,154 @@
// ============================================================================
// RynthSuite - Plugins/Shared/CommandReply.cs
// How a plugin answers a chat command (2026-10-28, the owner's rule): every
// command a player types gets one clear line back, what changed and the value
// now, or why not and the usage (more lines only for list, status and help).
// Never silent. Compiled into each plugin that answers commands (linked
// source), RynthServers' server plugins included.
//
// Colours: Ok lines go to chat as type 1 (AC's green, what the plugins always
// used), Fail lines as type 2 (white, RynthAi's colour for warnings). The
// engine's chat window files both under Rynth by their "[Rynth..." prefix and
// draws them in that tab's colour.
//
// Why a queue: off AC's main thread Host.WriteToChat drops a line that comes
// within 100 ms of any plugin's previous one (the engine's guard for AC's chat
// buffer). Commands run on the plugin pump, so a reply right after another
// plugin's line, or the second line of a help text, used to vanish. A line is
// written at once when nothing waits; one the host refuses (and every line
// after it, so they stay in order) waits here, and Flush (once per tick) offers
// the first again until the host takes it. A line that still can't be written
// after MaxTries ticks (about 1.5 s) goes to the log and the next one moves up.
//
// Quiet: a plugin that can tell a command sent by a meta or script from a typed
// one passes quiet: true for the script's successes (logged only); failures
// always show. A plugin that can't tell always replies.
//
// Threads: Ok / Fail from any thread; Flush on the plugin pump (OnTick).
// ============================================================================
using System;
using System.Collections.Concurrent;
using System.Threading;
namespace RynthCore.Plugin.Shared;
public sealed class CommandReply
{
/// <summary>Chat type of a line saying it worked (AC's green).</summary>
public const int OkChatType = 1;
/// <summary>Chat type of a line saying why not (white; RynthAi's warnings use it too).</summary>
public const int FailChatType = 2;
/// <summary>Lines kept waiting at most; more are logged instead (a runaway loop can't fill memory).</summary>
public const int MaxQueued = 128;
/// <summary>Ticks one line is offered to the host before it goes to the log instead.</summary>
public const int MaxTries = 90;
private readonly ConcurrentQueue<(string Line, int Type)> _queue = new();
private readonly Func<string, int, bool> _write;
private readonly Action<string>? _log;
private int _tries;
private int _count;
/// <param name="tag">The plugin's prefix, "[RynthNav]"; put in front of each line that has none.</param>
/// <param name="write">Host.WriteToChat: false when the host didn't take the line.</param>
/// <param name="log">The plugin's log (quiet lines, failures, lines that couldn't be written).</param>
public CommandReply(string tag, Func<string, int, bool> write, Action<string>? log = null)
{
Tag = tag ?? string.Empty;
_write = write ?? throw new ArgumentNullException(nameof(write));
_log = log;
}
/// <summary>The plugin's prefix ("[RynthNav]").</summary>
public string Tag { get; }
/// <summary>Lines waiting to be written.</summary>
public int Pending => _queue.Count;
/// <summary>Every reply given so far, quiet ones included: a caller (or a test) sees whether a command answered.</summary>
public int Count => Volatile.Read(ref _count);
/// <summary>It worked: what changed and the value now. <paramref name="quiet"/>: a script's command, logged only.</summary>
public void Ok(string text, bool quiet = false) => Add(text, OkChatType, quiet);
/// <summary>It didn't: why, and the usage when the words were wrong. Always shown.</summary>
public void Fail(string text) => Add(text, FailChatType, quiet: false);
/// <summary><see cref="Ok"/> or <see cref="Fail"/> by <paramref name="ok"/>.</summary>
public void Say(bool ok, string text, bool quiet = false) => Add(text, ok ? OkChatType : FailChatType, quiet && ok);
/// <summary>The line as it goes to chat: the tag in front unless the text brings its own ("[Mini Remote] ...").</summary>
public string Format(string text)
{
string t = (text ?? string.Empty).Trim();
if (t.Length > 0 && t[0] == '[') return t;
return Tag.Length == 0 ? t : Tag + " " + t;
}
/// <summary>
/// Offers the first waiting line again (one per call, so call it once per tick). True when a line
/// went out. Pump thread.
/// </summary>
public bool Flush()
{
if (!_queue.TryPeek(out var head)) return false;
if (TryWrite(head.Line, head.Type))
{
_queue.TryDequeue(out _);
_tries = 0;
return true;
}
if (++_tries >= MaxTries)
{
_queue.TryDequeue(out _);
_tries = 0;
_log?.Invoke("(not shown in chat) " + head.Line);
}
return false;
}
private bool TryWrite(string line, int type)
{
try { return _write(line, type); }
catch { return false; }
}
/// <summary>Forgets the waiting lines (logout, shutdown).</summary>
public void Clear()
{
while (_queue.TryDequeue(out _)) { }
_tries = 0;
}
private void Add(string text, int type, bool quiet)
{
// Control characters make the engine refuse a line: a text with line breaks goes out as
// several lines (each with the tag), tabs as spaces.
string[] parts = (text ?? string.Empty).Replace("\r", string.Empty).Replace('\t', ' ').Split('\n');
bool any = false;
foreach (string part in parts)
{
if (part.Trim().Length == 0) continue;
string line = Format(part);
any = true;
if (quiet || type == FailChatType) _log?.Invoke(line);
if (quiet) continue;
// Nothing waiting: straight to the host; it may refuse (the 100 ms rule), then the line waits.
if (_queue.IsEmpty && TryWrite(line, type)) continue;
if (_queue.Count >= MaxQueued) { _log?.Invoke("(chat queue full) " + line); continue; }
_queue.Enqueue((line, type));
}
if (any) Interlocked.Increment(ref _count);
}
// ── Wording shared by the plugins ────────────────────────────────────
/// <summary>"Vision window shown." / "Vision window hidden."</summary>
public static string Shown(string what, bool shown) => $"{what} {(shown ? "shown" : "hidden")}.";
/// <summary>"on" / "off".</summary>
public static string OnOff(bool on) => on ? "on" : "off";
}

View file

@ -91,6 +91,8 @@ internal static unsafe class FakeHost
// ── What tested code sent to the engine ───────────────────────────────────
public static readonly List<string> Logs = new();
public static readonly List<string> Chat = new();
/// <summary>The chat type (colour) of each <see cref="Chat"/> line, in the same order.</summary>
public static readonly List<int> ChatTypes = new();
public static readonly List<string> ChatCommands = new();
/// <summary>Every SetAutoRun call, in order; AutoRun is the last value sent.</summary>
public static readonly List<bool> AutoRunCalls = new();
@ -302,7 +304,7 @@ internal static unsafe class FakeHost
ServerTime = 0; Vitae = 1.0f; Portaling = false; PlayerPose = default; HasPose = true;
Vitals = default; BaseVitals = default; WorldName = ""; AccountName = "";
HeadingDeg = 0; Wcids.Clear(); Spellbook.Clear(); PlayerIdValue = 0;
Logs.Clear(); Chat.Clear(); ChatCommands.Clear(); AfterCastSpell = null;
Logs.Clear(); Chat.Clear(); ChatTypes.Clear(); ChatCommands.Clear(); AfterCastSpell = null;
AutoRunCalls.Clear(); AutoRun = false; Jumps = 0; TapJumpCalls = false; TapJumps = 0; TapJumpRefuse = false; Turns = 0; Casts.Clear(); CastRefused = false; CastsRefused = 0; StopCalls = false; Stops = 0; SetMotionCalls = false; MotionCalls.Clear(); AttackSendCalls = false; AttackCalls.Clear(); Sent.Clear(); GiveCalls = false; Gives.Clear(); GiveLands = true; GiveHandler = null;
Uses.Clear(); IdRequests.Clear(); TargetCalls = false; HealthQueries.Clear(); IdTimes.Clear(); Moves.Clear(); Appraised.Clear(); WeaponCalls = false; ContentsCalls = false; CombatModeValue = 1;
RequestIdAccepts = true; RefusedIdRequests = 0; UseObjectAccepts = true;
@ -608,7 +610,7 @@ internal static unsafe class FakeHost
}
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int WriteToChat(IntPtr text, int type) { Chat.Add(Marshal.PtrToStringUni(text) ?? ""); return 1; }
private static int WriteToChat(IntPtr text, int type) { Chat.Add(Marshal.PtrToStringUni(text) ?? ""); ChatTypes.Add(type); return 1; }
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static int SendPluginCommand(IntPtr plugin, IntPtr action, IntPtr value)

View file

@ -165,6 +165,7 @@ internal static class Program
DifficultyTierTests.Register(runner);
TickIsolationTests.Register(runner);
ChoresInFightTests.Register(runner);
CommandReplyTests.Register(runner);
return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null);
}
}

View file

@ -0,0 +1,754 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using RynthCore.Plugin.RynthAi;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.Plugin.RynthAi.Meta;
using RynthCore.PluginCore;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Every chat command answers (2026-10-28, CommandReply.cs). A /ra, /ub, /mt or /vt line the player
// types always says in chat whether it worked: what changed and the value now, or why not and the
// usage, never nothing and never the catch-all "Ran:" line. The same line from a meta is quiet when
// it works (the log has it) and still shows its errors, a repeated one once a minute.
//
// One table: every verb RynthAi's dispatchers take, with a form that works in this rig and a wrong
// one. Verbs whose working form writes under C:\Games (nav / meta / settings saves, dumpspells,
// translateroute, logs prune, trace on) or plays a sound only run their wrong form here.
internal static class CommandReplyTests
{
public static void Register(Runner r)
{
r.Add("command replies: CommandReply - typed always answers, a script's success is quiet, errors once a minute", HelperRules);
r.Add("command replies: every typed command answers in chat, never with the catch-all line", TypedAlwaysAnswers);
r.Add("command replies: a typed command's wrong form answers with a failure line (the failure colour)", TypedWrongFormsFail);
r.Add("command replies: a meta's command is quiet when it works; its error shows, a repeat not within a minute", MetaQuietOnSuccess);
r.Add("command replies: /ub opt set AutoVendor.Enabled true answers 'AutoVendor.Enabled = True' (a meta's: log only)", UbOptSetSaysValue);
r.Add("command replies: deferred answers (LootThisCont, Meta Manager) keep who sent the line", DeferredAnswers);
}
private const uint Lb = 0xA9B40000;
private const uint Player = 0x50000F61, Robe = 0x80282301, Sword = 0x80282302, Cloak = 0x80282303;
private const uint Crier = 0x80000601, Drudge = 0x80000602;
private const BindingFlags Any = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
/// <summary>What a row's working form must do. Act: answer typed, quiet from a meta. Query: output
/// asked for, shown either way. Elsewhere: the server, the engine or another plugin answers (it is
/// handed on). Ignored: an accepted no-equivalent verb (typed: a failure line; a meta: once).</summary>
private enum K { Act, Query, Elsewhere, Ignored }
/// <summary>A verb: a working form, a wrong one, and a line typed first (state the working form needs).</summary>
private sealed record Row(string? Valid, string? Invalid, K Kind, string? Setup = null);
private static readonly Row[] Rows =
{
// ── /ra: settings and actions ──
new("/ra power 80", "/ra power banana", K.Act),
new("/ra offhand shield", "/ra offhand banana", K.Act),
new("/ra offhand dual on", "/ra offhand default", K.Act),
new("/ra follow off", "/ra follow Nobody Here", K.Act),
new("/ra follow Town Crier", null, K.Act),
new("/ra navrec on", null, K.Act),
new("/ra navhud off", null, K.Act),
new("/ra navtrail on", null, K.Act),
new("/ra navtrail clear", null, K.Act),
new("/ra navoverlay off", null, K.Act),
new("/ra debug off", null, K.Act),
new("/ra lootcheck off", "/ra lootcheck", K.Act),
new("/ra groundloot scan", null, K.Act),
new("/ra groundloot on", null, K.Act),
new("/ra vtankyield off", "/ra vtankyield banana", K.Act),
new("/ra stop", null, K.Act),
new("/ra start", null, K.Act),
new("/ra resume", null, K.Act),
new("/ra pause 5", null, K.Act),
new("/ra clearbusy", null, K.Act),
new("/ra panic", null, K.Act),
new("/ra use Faran Robe", "/ra use Nothing Here", K.Act),
new("/ra usep Robe", "/ra usep", K.Act),
new("/ra usei Faran Robe", "/ra usei Nothing Here", K.Act),
new("/ra usel Town Crier", "/ra usel Nothing Here", K.Act),
new("/ra usepi Robe", null, K.Act),
new("/ra uselp Crier", null, K.Act),
new("/ra select Faran Robe", "/ra select Nothing Here", K.Act),
new("/ra selectp Robe", "/ra selectp", K.Act),
new("/ra selecti Faran Robe", null, K.Act),
new("/ra selectl Town Crier", null, K.Act),
new("/ra give Faran Robe to Town Crier", "/ra give Faran Robe", K.Act),
new("/ra givep Robe to Town Crier", "/ra givep Robe to Nobody", K.Act),
new("/ra givexp Faran Robe to Crier", null, K.Act),
new("/ra givepp Robe to Crier", null, K.Act),
new("/ra giver ^Faran to Town Crier", "/ra giver ([ to Town Crier", K.Act),
new("/ra givea Faran Robe to Town Crier", "/ra givea Nothing Here to Town Crier", K.Act),
new("/ra giveap Robe to Town Crier", null, K.Act),
new("/ra giveaxp Faran Robe to Crier", null, K.Act),
new("/ra giveapp Robe to Crier", null, K.Act),
new("/ra gap Robe to Crier", null, K.Act),
new("/ra givear ^Faran to Town Crier", null, K.Act),
new("/ra givea stop", null, K.Act),
new(null, "/ra ig NoSuchProfileHere to Town Crier", K.Act),
new(null, "/ra igp NoSuchProfileHere", K.Act),
new("/ra cast 1234", "/ra cast banana", K.Act),
new("/ra targetlock off", null, K.Act),
new("/ra meleelow", null, K.Act),
new("/ra meleemid", null, K.Act),
new("/ra meleehigh", null, K.Act),
new("/ra navprio on", null, K.Act),
new("/ra lootprio off", null, K.Act),
new("/ra navlootprio on", null, K.Act),
new("/ra setmetastate Hunt", "/ra setmetastate", K.Act),
new("/ra metastate Hunt", null, K.Act),
new("/ra equipfor Drudge Skulker", "/ra equipfor", K.Act),
new("/ra myquests", null, K.Act),
new("/ra refreshquests", null, K.Act),
new("/ra ghosts forget", null, K.Act),
new("/ra jump", "/ra jumpq", K.Act),
new("/ra jumpsw 90 200", "/ra jumpw 90 banana", K.Act),
new("/ra spells hide", null, K.Act),
new("/ra trade decline", "/ra trade banana", K.Act),
new("/ra owncorpse stop", null, K.Act),
new(null, "/ra testitem", K.Act),
new(null, "/ra hazard add", K.Act),
new(null, "/ra hazard texture add banana", K.Act),
new(null, "/ra dunnav 1 2", K.Act),
new(null, "/ra dunnav", K.Act),
new(null, "/ra dunnav-patrol", K.Act),
new(null, "/ra nav restart", K.Act),
new(null, "/ra nav banana", K.Act),
new(null, "/ra meta banana", K.Act),
new(null, "/ra settings", K.Act),
new(null, "/ra settings loadchar", K.Act),
new(null, "/ra loot add banana", K.Act),
new(null, "/ra lootparse", K.Act),
new(null, "/ra lootcheckinv", K.Act),
new(null, "/ra autotrade", K.Act),
new(null, "/ra forcebuff", K.Act),
new(null, "/ra cancelforcebuff", K.Act),
new(null, "/ra buff force", K.Act),
new(null, "/ra buff skipped", K.Act),
new(null, "/ra bufftest", K.Act),
new(null, "/ra swaptest", K.Act),
new(null, "/ra recharge", K.Act),
new(null, "/ra heal", K.Act),
new(null, "/ra stam", K.Act),
new(null, "/ra mana", K.Act),
new(null, "/ra hub", K.Act),
new(null, "/ra quests", K.Act),
new(null, "/ra pets", K.Act),
new(null, "/ra huds show", K.Act),
new(null, "/ra itemhud add Faran Robe", K.Act),
new(null, "/ra remote toggle", K.Act),
new(null, "/ra miniremote hide", K.Act),
new(null, "/ra translate status", K.Act),
new(null, "/ra tr status", K.Act),
new(null, "/ra iteminfo", K.Act),
new(null, "/ra ii", K.Act),
new(null, "/ra corpseopen", K.Act),
new(null, "/ra fellow", K.Act),
new(null, "/ra fellowship leader", K.Act),
new(null, "/ra nosuchverb", K.Act),
// ── /ra: output asked for ──
new("/ra help", null, K.Query),
new("/ra", null, K.Query),
new("/ra version", null, K.Query),
new("/ra server", null, K.Query),
new("/ra buffs", null, K.Query),
new("/ra cache", null, K.Query),
new("/ra cache2", null, K.Query),
new("/ra attackable", null, K.Query),
new("/ra mexec 1+1", "/ra mexec", K.Query),
new("/ra listvars", null, K.Query),
new("/ra listpvars", null, K.Query),
new("/ra listgvars", null, K.Query),
new("/ra dumpprops", null, K.Query),
new("/ra propertydump", null, K.Query),
new("/ra wielded", null, K.Query),
new("/ra scan", null, K.Query),
new("/ra buildinfo", null, K.Query),
new("/ra navdebug", null, K.Query),
new("/ra raycast", null, K.Query),
new("/ra lostest", null, K.Query),
new("/ra landtest", null, K.Query),
new("/ra rayland", null, K.Query),
new("/ra corpseinfo", null, K.Query),
new("/ra corpsecheck", null, K.Query),
new("/ra fellowinfo", null, K.Query),
new("/ra dumpinv", null, K.Query),
new("/ra combat", null, K.Query),
new("/ra why", null, K.Query),
new("/ra ghosts", null, K.Query),
new("/ra ghost", null, K.Query),
new("/ra navstate", null, K.Query),
new("/ra salvstate", null, K.Query),
new("/ra mapdump", null, K.Query),
new("/ra busyinfo", null, K.Query),
new("/ra pace", null, K.Query),
new("/ra owncorpse", null, K.Query),
new("/ra mycorpse", null, K.Query),
new("/ra vtkeys", null, K.Query),
new("/ra discord", null, K.Query),
new("/ra items", null, K.Query),
new("/ra trace list", "/ra trace nosuchcategory", K.Query),
new("/ra logs", null, K.Query),
new("/ra debug", null, K.Query),
new("/ra loot", null, K.Query),
new("/ra hazard", null, K.Query),
new("/ra hazard list", null, K.Query),
new("/ra hazard texture list", null, K.Query),
new("/ra groundloot", null, K.Query),
new("/ra trade state", null, K.Query),
new("/ra vtankyield", null, K.Query),
new("/ra navtrail", null, K.Query),
new("/ra metamgr status", null, K.Elsewhere), // answered on the next tick
// ── /ra: answered by the engine or another plugin ──
new("/ra lua run Hello", null, K.Elsewhere),
new("/ra quit", null, K.Elsewhere),
new("/ra exit", null, K.Elsewhere),
new("/ra videopatch status", null, K.Elsewhere),
new("/ra lootthis", null, K.Elsewhere), // answered on the loot tick (DeferredAnswers)
new("/ra metamgr on", null, K.Elsewhere), // answered on the next tick (DeferredAnswers)
// ── /mt ──
new("/mt opt set AutoVendor.Enabled true", "/mt opt set AutoVendor.Enabled", K.Act),
new("/mt opt set enablecombat 0", "/mt opt", K.Act),
new("/mt opt remember enablecombat", "/mt opt remember", K.Act),
new("/mt opt restore enablecombat", "/mt opt restore NoSuchOption", K.Act, Setup: "/mt opt remember enablecombat"),
new("/mt opt get enablecombat", "/mt opt get NoSuchOption", K.Query),
new("/mt opt list", null, K.Query),
new("/mt config", null, K.Query),
new("/mt combatstate melee", "/mt combatstate banana", K.Act),
new("/mt face 90", "/mt face banana", K.Act),
new("/mt cast 1234", "/mt cast No Such Spell Ever", K.Act),
new("/mt castp 1234", "/mt castp", K.Act),
new("/mt use Faran Robe", "/mt use", K.Act),
new("/mt usep Robe", "/mt usep", K.Act),
new("/mt usei Faran Robe", null, K.Act),
new("/mt useip Robe", null, K.Act),
new("/mt usel Town Crier", null, K.Act),
new("/mt uselp Crier", null, K.Act),
new(null, "/mt use closestvendor", K.Act),
new("/mt select Faran Robe", "/mt select Nothing Here", K.Act),
new("/mt selectp Robe", null, K.Act),
new("/mt give Faran Robe to Town Crier", "/mt give Faran Robe", K.Act),
new("/mt givep Robe to Crier", "/mt givep Nothing to Crier", K.Act),
new("/mt loot Gem", "/mt loot", K.Act),
new("/mt lootp Gem", "/mt lootp", K.Act),
new("/mt drop Faran Robe", "/mt drop Nothing Here", K.Act),
new("/mt dropp Robe", "/mt dropp", K.Act),
new("/mt equip Sharp Sword", "/mt equip Nothing Here", K.Act),
new("/mt equipp Sword", "/mt equipp", K.Act),
new("/mt dequip Worn Cloak", "/mt dequip Nothing Here", K.Query),
new("/mt dequipp Cloak", "/mt dequipp", K.Query),
new("/mt fellow open", "/mt fellow create", K.Elsewhere),
new("/mt fellow close", "/mt fellow recruit", K.Elsewhere),
new("/mt fellow disband", "/mt fellow banana", K.Elsewhere),
new("/mt fellow quit", "/mt fellow", K.Elsewhere),
new("/mt fellow create Hunters", null, K.Elsewhere),
new("/mt fellow recruit Town Crier", null, K.Elsewhere),
new("/mt logout", null, K.Elsewhere),
new("/mt logoff", null, K.Elsewhere),
new("/mt quit", null, K.Elsewhere),
new("/mt exit", null, K.Elsewhere),
new("/mt send /say hi", "/mt send", K.Elsewhere),
new("/mt send enter", "/mt send banana", K.Act),
new("/mt send msg hello", "/mt send msg", K.Act),
new("/mt send cntrl+a", null, K.Act),
new("/mt jump 100", null, K.Act),
new("/mt sjumpw 100", null, K.Act),
new("/mt trade decline", "/mt trade", K.Act),
new("/mt trade reset", "/mt trade add", K.Act),
new("/mt trade end", "/mt trade banana", K.Act),
new("/mt trade add Faran Robe", "/mt trade add Nothing Here", K.Act),
new(null, "/mt trade accept", K.Act),
new("/mt vendor addsell Faran Robe", "/mt vendor", K.Act),
new("/mt vendor clearbuy", "/mt vendor addsell Nothing Here", K.Act),
new("/mt vendor clearsell", "/mt vendor banana", K.Act),
new(null, "/mt vendor sell", K.Act),
new(null, "/mt vendor buy", K.Act),
new("/mt autopack", null, K.Act),
new("/mt click ok", "/mt click", K.Act),
new("/mt click 10 20", "/mt click banana", K.Act),
new("/mt movement w 0", "/mt movement", K.Act),
new("/mt strafe left 0", "/mt strafe up 5", K.Act),
new("/mt client minimize", "/mt client banana", K.Act),
new("/mt client restore", null, K.Act),
new("/mt client frame", null, K.Query),
new("/mt get xy", "/mt get banana", K.Query),
new("/mt cursor", null, K.Query),
new("/mt test", null, K.Query),
new(null, "/mt nosuchverb", K.Act),
new(null, "/mt", K.Act),
// ── /ub ──
new("/ub opt set AutoVendor.Enabled true", "/ub opt set AutoVendor.Enabled", K.Act),
new("/ub opt toggle EnableLooting", "/ub opt toggle NoSuchOption", K.Act),
new("/ub opt get enablecombat", null, K.Query),
new("/ub opt list", null, K.Query),
new("/ub setvar[cr,1]", null, K.Act),
new("/ub jumpw", "/ub jumpq", K.Act),
new("/ub simplejump 100", null, K.Act),
new("/ub give Faran Robe to Town Crier", "/ub give Nothing Here to Town Crier", K.Act),
new("/ub givep Robe to Crier", null, K.Act),
new("/ub give 1 Faran Robe to Crier", null, K.Act),
new("/ub follow off", null, K.Act),
new("/ub followp Crier", null, K.Act),
new("/ub selecti Faran Robe", "/ub selecti Nothing Here", K.Act),
new("/ub selectlp Crier", null, K.Act),
new("/ub myquests", null, K.Act),
new("/ub clearbugged", null, K.Act),
new("/ub mexec 1+1", "/ub mexec", K.Query),
new("/ub listvars", null, K.Query),
new("/ub listpvars", null, K.Query),
new("/ub listgvars", null, K.Query),
new("/ub propertydump", null, K.Query),
new(null, "/ub ig NoSuchProfileHere to Crier", K.Act),
new("/ub delay 1000 /ra stop", "/ub delay banana", K.Act),
new("/ub count item Faran Robe", "/ub count", K.Query),
new("/ub count player 50", "/ub count player banana", K.Query),
new("/ub date", null, K.Query),
new("/ub dateutc yyyy", null, K.Query),
new("/ub id", null, K.Query),
new("/ub pos", null, K.Query),
new("/ub vitae", null, K.Elsewhere),
new(null, "/ub portal Nowhere At All", K.Act),
new(null, "/ub portalp", K.Act),
new(null, "/ub closestportal", K.Act),
new(null, "/ub playsound NoSuchSound.wav", K.Act),
new("/ub setmotion Forward 0", "/ub setmotion", K.Act),
new("/ub getmotion", null, K.Query),
new("/ub clearmotion", null, K.Act),
new("/ub autostack", null, K.Act),
new("/ub autocram", null, K.Act),
new("/ub help", null, K.Query),
new(null, "/ub dumpskills", K.Act),
new("/ub quests check SomeFlag", "/ub quests", K.Elsewhere),
new(null, "/ub translateroute", K.Act),
new("/ub wear Sharp Sword", "/ub wear Nothing Here", K.Act),
new("/ub wearp Sword", "/ub wear", K.Act),
new("/ub getxy", null, K.Query),
new("/ub stfl 0", "/ub stfl", K.Act),
new("/ub stfr 0", null, K.Act),
new("/ub debug off", null, K.Act),
new(null, "/ub close corpse", K.Act),
new("/ub globalframelimit 45", "/ub globalframelimit banana", K.Act),
new("/ub bgframelimit 20", "/ub bgframelimit", K.Act),
new("/ub fellow dismiss Storm", "/ub fellow dismiss", K.Elsewhere),
new("/ub fellow leaderp Storm", null, K.Elsewhere),
new("/ub fellow status", null, K.Query),
new("/ub arrow point 42.1N, 33.6E", null, K.Elsewhere),
new("/ub navgoto -12.5 40.25", "/ub navgoto banana", K.Elsewhere),
new("/ub packsort", null, K.Elsewhere),
new("/ub packsortshow", null, K.Elsewhere),
new("/ub bc /say hi", null, K.Elsewhere),
new("/ub netclients", null, K.Elsewhere),
new("/ub videopatch status", null, K.Elsewhere),
new("/ub bank status", null, K.Elsewhere), // ub-Rythai answers its own verbs
new("/ub combat on", null, K.Act),
new("/ub sloot off", null, K.Act),
new("/ub meta state Hunt", null, K.Act),
new("/ub meta status", null, K.Query),
new("/ub lps", null, K.Query),
new(null, "/ub miniremote show", K.Act),
new(null, "/ub autovendor", K.Act),
new(null, "/ub vendor buyall", K.Act),
new(null, "/ub autotrade", K.Act),
new("/ub soak on", null, K.Ignored),
new("/ub window save", null, K.Ignored),
new("/ub arrow face", null, K.Ignored),
new("/ub packsortreload", null, K.Ignored),
new("/ub qblist", null, K.Ignored),
new("/ub meta banana", null, K.Ignored),
new("/ub usep Robe", "/ub usep", K.Act),
new("/ub face 90", "/ub face", K.Act),
new("/ub combatstate peace", "/ub combatstate", K.Act),
new("/ub cast 1234", "/ub cast", K.Act),
new("/ub equip Sharp Sword", "/ub equip", K.Act),
new("/ub drop Faran Robe", "/ub drop", K.Act),
new("/ub select Faran Robe", "/ub select", K.Act),
new("/ub loot Gem", "/ub loot", K.Act),
new("/ub fellow open", "/ub fellow create", K.Elsewhere),
new("/ub logout", null, K.Elsewhere),
new("/ub quit", null, K.Elsewhere),
new(null, "/ub nosuchverb", K.Act),
// ── /vt ──
new("/vt opt set enablecombat true", "/vt opt set enablecombat", K.Act),
new("/vt opt set NoSuchVtOption 5", "/vt opt", K.Act),
new("/vt opt get enablecombat", null, K.Query),
new("/vt opt list", null, K.Query),
new("/vt stop", null, K.Act),
new("/vt start", null, K.Act),
new("/vt e", null, K.Act),
new("/vt jump", null, K.Act),
new("/vt tapjump", null, K.Act),
new("/vt equipitemsfor Drudge Skulker", "/vt equipitemsfor", K.Act),
new(null, "/vt loot load NoSuchProfileHere", K.Act),
new(null, "/vt meta", K.Act),
new(null, "/vt nav", K.Act),
new("/vt setmetastate Hunt", "/vt setmetastate", K.Act),
new("/vt attackdistance 0.1", null, K.Act),
new("/vt setattackbar 0.5", "/vt setattackbar banana", K.Act),
new("/vt reverseroute", null, K.Act),
new("/vt mexec 1+1", null, K.Query),
new("/vt clearbusy", null, K.Act),
new("/vt propertydump", null, K.Query),
new(null, "/vt testitem", K.Act),
new(null, "/vt forcebuff", K.Act),
new(null, "/vt cancelforcebuff", K.Act),
new(null, "/vt cancelbuff", K.Act),
new("/vt echo hello", null, K.Query),
new("/vt settings banana", null, K.Ignored),
new("/vt deletemonster", null, K.Ignored),
new(null, "/vt nosuchverb", K.Act),
new(null, "/vt", K.Act),
};
// ── The rig: a logged-in RynthAi with a meta manager, combat, a jumper and the fakes ──
private sealed class Rig : IDisposable
{
public readonly RynthAiPlugin P = new();
public readonly LegacyUiSettings S = new();
public readonly MetaManager M;
public readonly List<(uint Msg, uint W, uint L)> Posted = new();
public Rig()
{
FakeHost.Reset();
FakeHost.WeaponCalls = FakeHost.SalvageCalls = FakeHost.GiveCalls = FakeHost.CombatModeCalls = true;
FakeHost.PluginCommandCalls = FakeHost.CloseContainerCalls = FakeHost.TradeVendorCalls = true;
FakeHost.BusyCalls = FakeHost.StopCalls = FakeHost.SetMotionCalls = FakeHost.TapJumpCalls = true;
FakeHost.Names[Player] = "Tester";
FakeHost.PlayerIdValue = Player;
FakeHost.PlayerPose = (Lb | 0x1C, 96f, 96f, 0f);
FakeHost.Positions[Player] = (Lb | 0x1C, 96f, 96f, 0f);
foreach (var (id, name) in new[] { (Robe, "Faran Robe"), (Sword, "Sharp Sword"), (Cloak, "Worn Cloak") })
{
FakeHost.Names[id] = name;
FakeHost.Containers[id] = Player;
FakeHost.ItemTypes[id] = 0x2;
}
FakeHost.Wielded[Cloak] = 0x0400;
foreach (var (id, name, y) in new[] { (Crier, "Town Crier", 98f), (Drudge, "Drudge Skulker", 99f) })
{
FakeHost.Names[id] = name;
FakeHost.Positions[id] = (Lb | 0x1C, 96f, y, 0f);
FakeHost.ItemTypes[id] = 0x10;
}
var host = FakeHost.Create(playerId: Player);
typeof(RynthPluginBase).GetMethod("Attach", Any)!.Invoke(P, new object[] { FakeHost.LastApi });
var dash = (LegacyDashboardRenderer)RuntimeHelpers.GetUninitializedObject(typeof(LegacyDashboardRenderer));
typeof(LegacyDashboardRenderer).GetField("_settings", Any)!.SetValue(dash, S);
Set("_dashboard", dash);
var cache = new WorldObjectCache(host);
cache.SetPlayerId(Player);
foreach (uint id in new[] { Robe, Sword, Cloak }) cache.OnCreateObject(id);
cache.Tick();
foreach (uint id in new[] { Crier, Drudge }) _ = cache[unchecked((int)id)];
Set("_objectCache", cache);
Set("_playerId", Player);
Set("_currentTargetId", Drudge);
M = new MetaManager(S, host, new PlayerVitalsCache());
M.SetPlayerId(Player);
M.SetObjectCache(cache);
M.SetMtCommandHandler(line => (bool)Call("HandleMetaChatCommand", line)!);
M.SetRaCommandHandler(line => Call("HandleRaCommand", line));
M.Reply = P.Reply;
Set("_metaManager", M);
var combat = new CombatManager(host, S, cache);
combat.SetPlayerId(Player);
combat.SetDamageStores(null, new RynthCore.Plugin.RynthAi.CreatureData.MonsterDamageStore());
Set("_combatManager", combat);
Set("_fellowshipTracker", new FellowshipTracker());
Set("_jumper", new Jumper(host, S, text => P.Reply.Fail(text)));
Set("_initialized", true);
Set("_loginComplete", true);
S.AllowMetaKeystrokes = true; // the key verbs act (into the test sink) instead of refusing
S.MonsterRules.Add(new MonsterRule { Name = "Default" });
S.CurrentRoute.Points.Add(new NavPoint { NS = 1.0, EW = 1.0 });
S.CurrentRoute.Points.Add(new NavPoint { NS = 1.1, EW = 1.1 });
GameInput.TestSink = (m, w, l) => Posted.Add((m, w, l));
}
public void Set(string f, object? v) => typeof(RynthAiPlugin).GetField(f, Any)!.SetValue(P, v);
public object? Get(string f) => typeof(RynthAiPlugin).GetField(f, Any)!.GetValue(P);
public object? Call(string method, params object[] args) => typeof(RynthAiPlugin).GetMethod(method, Any)!.Invoke(P, args);
/// <summary>A line typed in the chat bar; the chat lines it wrote.</summary>
public List<(string Text, int Type)> Typed(string line) => Lines(() => { int eat = 0; P.OnChatBarEnter(line, ref eat); });
/// <summary>The same line run by a meta (RunAsMeta, as HandleMetaChatCommand does); the chat lines it wrote.</summary>
public List<(string Text, int Type)> Meta(string line) => Lines(() =>
{
var run = typeof(RynthAiPlugin).GetMethod("RunAsMeta", Any)!.MakeGenericMethod(typeof(bool));
run.Invoke(P, new object[] { (Func<bool>)(() => { int eat = 0; P.OnChatBarEnter(line, ref eat); return true; }) });
});
public static List<(string Text, int Type)> Lines(Action act)
{
int before = FakeHost.Chat.Count;
act();
var lines = new List<(string, int)>();
for (int i = before; i < FakeHost.Chat.Count; i++)
lines.Add((FakeHost.Chat[i], i < FakeHost.ChatTypes.Count ? FakeHost.ChatTypes[i] : -1));
return lines;
}
public void Dispose()
{
GameInput.Shutdown();
GameInput.TestSink = null;
RynthLog.DebugToChat = false;
}
}
/// <summary>Set RYNTH_SHOW_REPLIES=1 to print every typed line's answer (to read them over).</summary>
private static readonly bool ShowReplies = Environment.GetEnvironmentVariable("RYNTH_SHOW_REPLIES") == "1";
private static string Show(List<(string Text, int Type)> lines)
=> lines.Count == 0 ? "(nothing)" : string.Join(" | ", lines.Select(l => $"[{l.Type}] {l.Text}"));
/// <summary>A reply that is the catch-all line or a caught exception: the command has no answer of its own.</summary>
private static string? Bad(List<(string Text, int Type)> lines)
{
foreach (var (t, _) in lines)
{
if (t.StartsWith(CommandReply.RanPrefix, StringComparison.Ordinal)) return "only the catch-all 'Ran:' line";
if (t.Contains(": failed (", StringComparison.Ordinal)) return "threw: " + t;
}
return null;
}
private static void Report(List<string> problems, string what)
{
foreach (string p in problems) Console.WriteLine(" " + p);
Check.Eq(problems.Count, 0, what);
}
// ── The table ─────────────────────────────────────────────────────────────
private static void TypedAlwaysAnswers()
{
var problems = new List<string>();
foreach (var row in Rows)
{
foreach (string? line in new[] { row.Valid, row.Invalid })
{
if (line == null) continue;
using var r = new Rig();
if (row.Setup != null && line == row.Valid) r.Typed(row.Setup);
int handedOn = FakeHost.ChatCommands.Count + FakeHost.PluginCommands.Count;
var lines = r.Typed(line);
if (ShowReplies) Console.WriteLine($" {line} => {Show(lines)}");
bool elsewhere = row.Kind == K.Elsewhere && line == row.Valid;
if (Bad(lines) is string bad) problems.Add($"{line}: {bad}");
else if (elsewhere)
{
bool passedOn = FakeHost.ChatCommands.Count + FakeHost.PluginCommands.Count > handedOn;
bool deferred = line is "/ra lootthis" or "/ub bank status" || line.StartsWith("/ra metamgr", StringComparison.Ordinal);
if (!passedOn && lines.Count == 0 && !deferred) problems.Add($"{line}: nothing said and nothing handed on");
}
else if (lines.Count == 0) problems.Add($"{line}: said nothing");
}
}
Report(problems, "every typed command answers with a line of its own");
}
private static void TypedWrongFormsFail()
{
var problems = new List<string>();
foreach (var row in Rows)
{
if (row.Invalid == null) continue;
using var r = new Rig();
var lines = r.Typed(row.Invalid);
if (!lines.Any(l => l.Type == CommandReply.FailColor))
problems.Add($"{row.Invalid}: no failure line: {Show(lines)}");
}
Report(problems, "a wrong form answers with a failure line");
// Each typed failure answers every time (no once-a-minute for the player).
using var again = new Rig();
int first = again.Typed("/ra power banana").Count;
int second = again.Typed("/ra power banana").Count;
Check.True(first >= 1 && second == first, $"typed twice, answered twice ({first}, {second})");
// A key verb with "Allow metas to send keystrokes" off: typed, refused every time; a meta, once.
using var keys = new Rig();
keys.S.AllowMetaKeystrokes = false;
int t1 = keys.Typed("/mt send enter").Count(l => l.Type == CommandReply.FailColor);
int t2 = keys.Typed("/mt send enter").Count(l => l.Type == CommandReply.FailColor);
int m1 = keys.Meta("/mt send enter").Count;
int m2 = keys.Meta("/mt send enter").Count;
Check.True(t1 == 1 && t2 == 1 && m1 == 1 && m2 == 0, $"keys off: typed {t1}+{t2}, meta {m1}+{m2}");
Check.Eq(keys.Posted.Count, 0, "and no key went out");
}
private static void MetaQuietOnSuccess()
{
var problems = new List<string>();
foreach (var row in Rows)
{
if (row.Valid != null && row.Kind is K.Act or K.Elsewhere)
{
using var r = new Rig();
if (row.Setup != null) r.Typed(row.Setup);
var lines = r.Meta(row.Valid);
if (lines.Count > 0) problems.Add($"{row.Valid} (meta, works): said {Show(lines)}");
if (lines.Any(l => l.Text.StartsWith(CommandReply.RanPrefix, StringComparison.Ordinal)))
problems.Add($"{row.Valid} (meta): the catch-all line");
}
if (row.Valid != null && row.Kind == K.Ignored)
{
using var r = new Rig();
var once = r.Meta(row.Valid);
var twice = r.Meta(row.Valid);
if (once.Count > 1 || twice.Count > 0) problems.Add($"{row.Valid} (meta, ignored): {Show(once)} then {Show(twice)}");
}
if (row.Invalid != null && row.Kind != K.Ignored)
{
using var r = new Rig();
var lines = r.Meta(row.Invalid);
if (!lines.Any(l => l.Type == CommandReply.FailColor))
problems.Add($"{row.Invalid} (meta, wrong): no failure line: {Show(lines)}");
var repeat = r.Meta(row.Invalid);
if (repeat.Any(l => l.Type == CommandReply.FailColor))
problems.Add($"{row.Invalid} (meta, wrong, again within a minute): said again: {Show(repeat)}");
}
}
Report(problems, "a meta's command: quiet when it works, its error once a minute");
// The quiet success is in the log.
using var logged = new Rig();
logged.Meta("/ra power 80");
Check.True(FakeHost.Logs.Any(l => l.Contains("Attack power set to 80%")), "a meta's quiet success is logged");
Check.Eq(logged.S.MeleeAttackPower, 80, "and it worked");
}
private static void UbOptSetSaysValue()
{
using var r = new Rig();
Check.False(r.S.AutoVendorEnabled, "AutoVendor starts off");
var lines = r.Typed("/ub opt set AutoVendor.Enabled true");
Check.True(r.S.AutoVendorEnabled, "the setting changed");
Check.Eq(Show(lines), "[1] [RynthAi] AutoVendor.Enabled = True", "one line: the option and its value now");
lines = r.Meta("/ub opt set AutoVendor.Enabled false");
Check.False(r.S.AutoVendorEnabled, "a meta's set works");
Check.Eq(lines.Count, 0, "and says nothing in chat");
Check.True(FakeHost.Logs.Any(l => l == "[RynthAi] AutoVendor.Enabled = False"), "the log has it");
// The real meta route (MetaManager's chat-command action -> HandleMetaChatCommand) is quiet too.
lines = Rig.Lines(() => r.Call("HandleMetaChatCommand", "/ub opt set AutoVendor.Enabled true"));
Check.True(r.S.AutoVendorEnabled && lines.Count == 0, "HandleMetaChatCommand: set, quiet");
lines = Rig.Lines(() => r.M.TryHandleVtCommand("/vt opt set enablecombat false"));
Check.Eq(lines.Count, 1, "MetaManager's /vt outside a meta (typed): one line");
Check.Eq(lines[0].Text, "[RynthAi] enablecombat = False", "the option and its value now");
// An option RynthAi doesn't map is kept for metas, and says so.
lines = r.Typed("/ub opt set NoSuchOption 5");
Check.True(lines.Count == 1 && lines[0].Text.Contains("NoSuchOption = 5") && lines[0].Text.Contains("kept only for metas"),
"an unmapped option: its value, and that it is only kept for metas: " + Show(lines));
}
private static void DeferredAnswers()
{
// /ra lootthis answers on the loot tick, as the line that asked: typed in chat ...
using (var r = new Rig())
{
r.Typed("/ra lootthis");
var lines = Rig.Lines(() => r.Call("TakeLootThisRequest", r.S));
Check.True(lines.Count == 1 && lines[0].Text.Contains("LootThisCont"), "typed lootthis: the tick answers: " + Show(lines));
}
// /ra metamgr is applied on the next tick; a meta's answer stays quiet there, a typed one shows.
foreach (bool meta in new[] { false, true })
{
using var r = new Rig();
if (meta) r.Meta("/ra metamgr on"); else r.Typed("/ra metamgr on");
var queue = (System.Collections.Concurrent.ConcurrentQueue<(string[] Parts, bool FromScript)>)r.Get("_metaMgrCommands")!;
var lines = Rig.Lines(() =>
{
while (queue.TryDequeue(out var q))
r.P.Reply.RunQueued(q.FromScript, () => r.Call("HandleMetaMgrCommand", new object[] { q.Parts }));
});
Check.Eq(lines.Count, meta ? 0 : 1, meta ? "a meta's metamgr on: quiet on the tick" : "typed metamgr on: answered on the tick");
}
}
// ── The helper itself ───────────────────────────────────────────────────────
private static void HelperRules()
{
var chat = new List<(string Text, int Type)>();
var log = new List<string>();
bool meta = false;
long now = 1_000_000;
var reply = new CommandReply((t, c) => chat.Add((t, c)), log.Add, () => meta) { Clock = () => now };
reply.Run("/ra quiet", () => { });
Check.True(chat.Count == 1 && chat[0].Text == CommandReply.RanPrefix + "/ra quiet", "typed, no answer: the catch-all line");
Check.True(log.Any(l => l.Contains("gave no reply of its own")), "and the log names the command");
chat.Clear();
reply.Run("/ra ok", () => reply.Ok("done"));
Check.True(chat.Count == 1 && chat[0] == ("done", CommandReply.OkColor), "typed Ok: one line, the Ok colour");
chat.Clear();
reply.Run("/ra fail", () => reply.Fail("nope"));
Check.True(chat.Count == 1 && chat[0] == ("nope", CommandReply.FailColor), "typed Fail: one line, the failure colour");
chat.Clear();
reply.Run("/ra throws", () => throw new InvalidOperationException("boom"));
Check.True(chat.Count == 1 && chat[0].Text.Contains("failed (InvalidOperationException: boom)"), "typed, threw: says so, nothing escapes");
chat.Clear();
reply.Run("/ra answered", () => reply.Answered());
Check.Eq(chat.Count, 0, "answered another way: no catch-all line");
reply.Run("/ra ignored", () => reply.Ignored("not here"));
Check.True(chat.Count == 1 && chat[0].Type == CommandReply.FailColor, "typed Ignored: a failure line");
// A meta's lines.
chat.Clear(); log.Clear();
meta = true;
reply.Run("/ra ok", () => reply.Ok("done"));
Check.Eq(chat.Count, 0, "meta Ok: no chat");
Check.True(log.Contains("done"), "meta Ok: the log");
reply.Run("/ra quiet", () => { });
Check.Eq(chat.Count, 0, "meta, no answer: no catch-all line");
reply.Ignored("not here");
Check.Eq(chat.Count, 0, "meta Ignored: log only");
reply.Fail("nope");
reply.Fail("nope");
Check.Eq(chat.Count, 1, "meta Fail: in chat, a repeat within a minute not");
reply.Fail("other");
Check.Eq(chat.Count, 2, "a different error is said");
now += CommandReply.FailRepeatMs;
reply.Fail("nope");
Check.Eq(chat.Count, 3, "after a minute the same error is said again");
Check.Eq(log.Count(l => l == "nope"), 3, "every one is logged");
bool threw = false;
try { reply.Run("/ra throws", () => throw new InvalidOperationException("boom")); }
catch (InvalidOperationException) { threw = true; }
Check.True(threw, "a meta's exception goes on as before");
// A script's line (RynthLua, a route's chat waypoint) is a meta's; a queued command keeps its sender.
chat.Clear();
meta = false;
reply.AsScript(() => { reply.Ok("script done"); return true; });
Check.Eq(chat.Count, 0, "AsScript Ok: quiet");
reply.RunQueued(true, () => reply.Ok("queued by a meta"));
Check.Eq(chat.Count, 0, "RunQueued(meta) Ok: quiet");
reply.RunQueued(false, () => reply.Ok("queued by the player"));
Check.Eq(chat.Count, 1, "RunQueued(typed) Ok: in chat");
meta = true;
reply.RunQueued(false, () => reply.Ok("typed, run while a meta acts"));
Check.Eq(chat.Count, 2, "the queued sender wins over a meta running now");
}
}

View file

@ -105,7 +105,7 @@ internal static class MetaSampleCompatTests
FakeHost.GroundContainer = 0x80F00001;
w.Ub("/ub close corpse");
Check.True(FakeHost.Closes.Contains(0x80F00001), "closes the open container");
Check.False(FakeHost.Chat.Any(c => c.Contains("Unrecognized")), "never 'Unrecognized /ub command'");
Check.False(FakeHost.Chat.Any(c => c.Contains("Unrecognized") || c.Contains("Unknown /ub command")), "never 'Unknown /ub command'");
}
private static void UbExpression()

View file

@ -21,7 +21,7 @@ internal static class UbCompatTests
public static void Register(Runner r)
{
r.Add("ub compat: ub-IT verbs with no RynthAi equivalent are accepted, said once", NoEquivalentAccepted);
r.Add("ub compat: ub-IT verbs with no RynthAi equivalent are accepted, said once to a meta and every time typed", NoEquivalentAccepted);
r.Add("ub compat: ub-Rythai's verbs get no RynthAi reply, and a meta passes them on", UbRythaiVerbsLeftAlone);
r.Add("ub compat: aliases and features map onto RynthAi, RynthNav, RynthSort and the server", AliasesAndFeatures);
r.Add("ub compat: a meta's /ub line uses the /ub meaning, not /mt's", MetaUsesUbMeaning);
@ -70,13 +70,17 @@ internal static class UbCompatTests
private static void NoEquivalentAccepted()
{
var w = new World();
Check.True(w.Ub("/ub soak on"), "/ub soak is handled");
Check.True(w.Ub("/ub soak off"), "again");
Check.Eq(w.ChatWith("/ub soak"), 1, "said once per session, not per meta pulse");
Check.True(w.Meta("/ub soak on"), "/ub soak is handled");
Check.True(w.Meta("/ub soak off"), "again");
Check.Eq(w.ChatWith("/ub soak"), 1, "a meta's: said once per session, not per meta pulse");
// Typed, it answers every time (a typed command always answers, CommandReply.cs).
Check.True(w.Ub("/ub soak on"), "typed /ub soak is handled");
Check.True(w.Ub("/ub soak on"), "typed again");
Check.Eq(w.ChatWith("/ub soak"), 3, "typed: said each time");
// /ub videopatch is not here: RynthAi already forwards it to the engine's /rc videopatch.
foreach (string line in new[] { "/ub chat max", "/ub playeroption AutoRepeatAttack on", "/ub statushud toggle", "/ub professor war 7", "/ub xp level" })
Check.True(w.Ub(line), line + " is handled");
Check.Eq(w.ChatWith("Unrecognized"), 0, "no 'Unrecognized /ub command'");
Check.Eq(w.ChatWith("Unrecognized") + w.ChatWith("Unknown /ub command"), 0, "no 'Unknown /ub command'");
Check.False(w.Ub("/ub notaubitcommand"), "a verb ub-IT doesn't have is still unknown");
}
@ -121,7 +125,7 @@ internal static class UbCompatTests
w.Ub("/ub packsort");
Check.True(FakeHost.PluginCommands.Contains(("RynthSort", "rsort", "now")), "packsort -> /rsort now");
// Server and engine commands go to the chat parser.
// Server commands go to the chat parser.
w.Ub("/ub qblist");
w.Ub("/ub augs");
w.Ub("/ub window save");
@ -129,7 +133,9 @@ internal static class UbCompatTests
// qblist / augs are ACECustom's commands: the server plugin's (RynthILT) since 2026-10-20.
Check.False(FakeHost.ChatCommands.Contains("/qb list") || FakeHost.ChatCommands.Contains("/aug"),
"qblist / augs: no server plugin, so nothing is sent to the server");
Check.True(FakeHost.ChatCommands.Contains("/rc window save"), "window save -> /rc window save");
// The engine has no /rc window save (it never had): RynthAi says where the setting is instead.
Check.False(FakeHost.ChatCommands.Contains("/rc window save"), "window save sends no engine command");
Check.Eq(w.ChatWith("Remember Game Window Position"), 1, "window save says where RynthCore keeps the window");
Check.True(FakeHost.ChatCommands.Contains("/fellowship dismiss Storm"), "fellow dismiss -> /fellowship dismiss");
// With a server plugin they are its verbs ("ub qblist", "ub augs").

View file

@ -285,7 +285,10 @@ internal static class UbMtSafetyTests
w.Meta("/mt trade accept");
Check.Eq(FakeHost.TradeActions.Count, 0, "macro off or Meta off: no trade accept");
Check.Eq(FakeHost.VendorSells.Count, 0, "macro off: no sale");
Check.Eq(w.ChatWith("only runs from a meta that is running"), 6, "all refused with the reason");
// A meta repeating the same refusal says it once a minute (CommandReply.cs): the second
// "/mt trade accept" refusal is in the log, not in chat again.
Check.Eq(w.ChatWith("only runs from a meta that is running"), 5, "all refused with the reason (a meta's repeat once)");
Check.Eq(w.LogWith("/mt trade accept only runs from a meta that is running"), 3, "every refusal is logged (one typed, two from the meta)");
}
finally { w.Dispose(); }
}

View file

@ -0,0 +1,199 @@
using System;
using System.IO;
using RynthCore.Plugin.RynthDefective.Corpses;
namespace RynthDefective.Tests
{
internal static partial class Program
{
private static readonly DateTime T0 = new(2026, 10, 23, 22, 0, 0, DateTimeKind.Utc);
// An outdoor landcell: landblock 0xA9B4 (Holtburg), outdoor cell 0x0016; a dungeon one: 0x6146 cell 0x0258.
private const uint Outdoor = 0xA9B40016u, Dungeon = 0x61460258u;
private static void CorpseLinesParse()
{
Check(CorpseLines.TryLocated("Your corpse is located at (42.1N, 33.6E).", out double ns, out double ew) && ns == 42.1 && ew == 33.6, "N/E");
Check(CorpseLines.TryLocated("Your corpse is located at (0.5S, 12.0W).", out ns, out ew) && ns == -0.5 && ew == -12.0, "S/W");
Check(CorpseLines.IsCorpseLine("Your corpse is located at (42.1N, 33.6E)."), "a corpse line");
Check(CorpseLines.IsNothingDropped("You have retained all your items. You do not need to recover your corpse!"), "nothing dropped");
Check(!CorpseLines.IsCorpseLine("Corpse of Olthoi Slayer"), "a corpse's name isn't a line");
}
private static void CorpseDeaths()
{
var b = new CorpseBook();
b.Died(T0, Outdoor, 100f, 50f, 20f, level: 30);
Eq(b.Corpses.Count, 1, "a death is a corpse");
Eq(b.Corpses[0].RotsUtc, T0.AddSeconds(30 * 300), "rots after level x 5 min");
b.ServerLine(T0.AddSeconds(1), 42.1, 33.6, 30);
Eq(b.Corpses.Count, 1, "the server's line is the same death");
Check(b.Corpses[0].ServerCoords && b.Corpses[0].Ns == 42.1 && b.Corpses[0].Cell == Outdoor, "the server's coordinates added to the place");
// The line first, then the health.
var b2 = new CorpseBook();
b2.ServerLine(T0, 42.1, 33.6, 5);
Check(b2.Corpses.Count == 1 && b2.Corpses[0].Cell == 0, "the line alone: map coordinates only");
Eq(b2.Corpses[0].RotsUtc, T0.AddHours(1), "low level: an hour");
b2.Died(T0.AddSeconds(1), Outdoor, 100f, 50f, 20f, 5);
Check(b2.Corpses.Count == 1 && b2.Corpses[0].Cell == Outdoor, "the death fills in the place");
// Nothing dropped, after and before the death.
var b3 = new CorpseBook();
b3.Died(T0, Dungeon, 10f, 20f, -6f, 100);
b3.NothingDropped(T0.AddSeconds(1));
Eq(b3.Corpses.Count, 0, "nothing dropped: no corpse to note");
b3.NothingDropped(T0.AddMinutes(10));
b3.Died(T0.AddMinutes(10).AddSeconds(1), Dungeon, 10f, 20f, -6f, 100);
Eq(b3.Corpses.Count, 0, "the line before the health: still nothing noted");
b3.Died(T0.AddMinutes(20), Dungeon, 10f, 20f, -6f, 100);
Eq(b3.Corpses.Count, 1, "a later death is noted again");
// Two deaths, minutes apart: two corpses, the newest first.
var b4 = new CorpseBook();
b4.Died(T0, Outdoor, 100f, 50f, 20f, 50);
b4.Died(T0.AddMinutes(5), Dungeon, 10f, 20f, -6f, 50);
b4.ServerLine(T0.AddMinutes(5).AddSeconds(1), 1, 1, 50);
Check(b4.Corpses.Count == 2 && b4.Corpses[0].Cell == Dungeon && !b4.Corpses[1].ServerCoords, "the line goes to the latest death only");
}
private static void CorpseSeen()
{
var b = new CorpseBook();
b.Died(T0, Dungeon, 10f, 20f, -6f, 100);
CorpseRecord r = b.Seen(T0.AddMinutes(3), 0x80001234u, Dungeon, 11f, 21f, -6f);
Check(b.Corpses.Count == 1 && r.ObjectId == 0x80001234u && r.X == 11f, "the corpse seen is the death next to it");
Eq(r.DiedUtc, T0, "it keeps the death's time");
b.Seen(T0.AddMinutes(4), 0x80001234u, Dungeon, 11f, 21f, -6f);
Eq(b.Corpses.Count, 1, "seen again by id");
// Another dungeon, and the same dungeon far away: found corpses of their own.
b.Seen(T0.AddMinutes(5), 0x80005555u, 0x01E90100u, 1f, 1f, 0f);
Eq(b.Corpses.Count, 2, "another dungeon: a corpse found");
Check(b.Corpses[1].DiedUtc == DateTime.MinValue || b.Corpses[0].DiedUtc == DateTime.MinValue, "found: no death time");
var b2 = new CorpseBook();
b2.Died(T0, Dungeon, 10f, 20f, -6f, 100);
b2.Seen(T0.AddMinutes(1), 0x80000001u, Dungeon, 10f + 80f, 20f, -6f);
Eq(b2.Corpses.Count, 2, "80 m off: not that death");
// Two corpses near a death (as on the test client): the one 30 m off is found, the one beside it is the death.
var b2b = new CorpseBook();
b2b.Died(T0, Dungeon, 30f, -202.8f, -24f, 100);
b2b.Seen(T0.AddSeconds(3), 0x8000383Au, Dungeon, 48.2f, -178.9f, -18f);
b2b.Seen(T0.AddSeconds(3), 0x80003841u, Dungeon, 28.3f, -204.8f, -24f);
CorpseRecord death = b2b.Corpses[0].DiedUtc == T0 ? b2b.Corpses[0] : b2b.Corpses[1];
Check(b2b.Corpses.Count == 3 - 1 && death.ObjectId == 0x80003841u, "the death goes to the corpse beside it, not the first seen");
// Outdoors, the server's coordinates only: matched by map distance.
var b3 = new CorpseBook();
CorpseBook.MapCoords(Outdoor, 100f, 50f, out double ns, out double ew);
b3.ServerLine(T0, Math.Round(ns, 1), Math.Round(ew, 1), 100);
b3.Seen(T0.AddMinutes(2), 0x80000002u, Outdoor, 100f, 50f, 20f);
Check(b3.Corpses.Count == 1 && b3.Corpses[0].Cell == Outdoor && b3.Corpses[0].ObjectId == 0x80000002u, "matched to the server's line");
}
private static void CorpseGoneAndExpiry()
{
// Leaving view: gone only when opened, due to rot, or right beside you.
var v = new CorpseRecord { DiedUtc = T0, RotsUtc = T0.AddHours(5), Cell = Dungeon, ObjectId = 1 };
Check(!CorpseBook.VanishMeansGone(v, 30, T0.AddMinutes(20)), "30 m off, not opened: only out of sight");
Check(CorpseBook.VanishMeansGone(v, 8, T0.AddMinutes(20)), "beside you: gone");
var vb = new CorpseBook();
vb.Seen(T0, 0x80000010u, Dungeon, 10f, 20f, -6f);
vb.Opened(0x80000010u, T0.AddMinutes(1));
Check(CorpseBook.VanishMeansGone(vb.Corpses[0], 30, T0.AddMinutes(2)), "opened: its vanishing is the looting");
Check(!CorpseBook.VanishMeansGone(vb.Corpses[0], 30, T0.AddMinutes(30)), "opened long ago: no longer");
Check(CorpseBook.VanishMeansGone(v, 500, T0.AddHours(5).AddMinutes(-2)), "due to rot: gone");
// Standing at its place without it there.
var n = new CorpseRecord { DiedUtc = T0, Cell = Dungeon, ObjectId = 5 };
Check(!CorpseBook.NotThere(n, 3, false, T0.AddSeconds(30)) && !CorpseBook.NotThere(n, 3, false, T0.AddSeconds(50)), "not in the first 2 minutes");
Check(!CorpseBook.NotThere(n, 3, false, T0.AddMinutes(3)), "missing: the timer starts");
Check(!CorpseBook.NotThere(n, 3, false, T0.AddMinutes(3).AddSeconds(5)), "5 s: not yet");
Check(!CorpseBook.NotThere(n, 3, true, T0.AddMinutes(3).AddSeconds(6)), "in view: the timer stops");
Check(!CorpseBook.NotThere(n, 3, false, T0.AddMinutes(3).AddSeconds(7)) && CorpseBook.NotThere(n, 3, false, T0.AddMinutes(3).AddSeconds(17)), "10 s missing: dropped");
var far = new CorpseRecord { DiedUtc = T0, Cell = Dungeon };
Check(!CorpseBook.NotThere(far, 30, false, T0.AddMinutes(3)) && !CorpseBook.NotThere(far, 30, false, T0.AddMinutes(4)), "30 m off: never");
var b = new CorpseBook();
b.Died(T0, Dungeon, 10f, 20f, -6f, 12); // rots after an hour (level 12 x 5 min is less)
b.Seen(T0.AddMinutes(1), 0x80001234u, Dungeon, 10f, 20f, -6f);
Check(!b.Gone(0x80009999u) && b.Gone(0x80001234u) && b.Corpses.Count == 0, "gone by its id");
b.Died(T0, Dungeon, 10f, 20f, -6f, 12);
Check(!b.Expire(T0.AddMinutes(65)), "kept through the grace after its rot time");
Check(b.Expire(T0.AddMinutes(71)) && b.Corpses.Count == 0, "dropped 10 min after it");
b.Seen(T0, 0x80000003u, Dungeon, 10f, 20f, -6f);
Check(!b.Expire(T0.AddHours(47)) && b.Expire(T0.AddHours(49)), "a found corpse: 48 h after it was last seen");
for (int i = 0; i < CorpseBook.MaxCorpses + 5; i++) b.Died(T0.AddMinutes(10 * i), Dungeon, i * 100f, 0f, 0f, 200);
Eq(b.Corpses.Count, CorpseBook.MaxCorpses, "at most 20");
Eq(b.Corpses[0].DiedUtc, T0.AddMinutes(10 * (CorpseBook.MaxCorpses + 4)), "the newest first, the oldest dropped");
Check(b.Forget(b.Corpses[0]) && b.Corpses.Count == CorpseBook.MaxCorpses - 1, "forget");
}
private static void CorpseStoreFiles()
{
var st = new CorpseStore(Path.Combine(_temp, "corpses-store"));
var b = new CorpseBook();
b.Died(T0, Outdoor, 100.25f, 50.5f, 20f, 60);
b.ServerLine(T0.AddSeconds(1), 42.1, -33.6, 60);
b.Seen(T0.AddMinutes(1), 0x80001234u, Outdoor, 100.25f, 50.5f, 20f);
b.Seen(T0.AddMinutes(2), 0x80005678u, Dungeon, 1f, 2f, 3f);
Check(st.Save("Aelrynth", "Drak/kon", b.Corpses) == null, "saved");
Check(File.Exists(Path.Combine(_temp, "corpses-store", "corpses", "Aelrynth_Drak_kon.json")), "the file name is safe");
var back = st.Load("Aelrynth", "Drak/kon", out string? problem);
Check(problem == null && back.Count == 2, "loaded both");
CorpseRecord a = back.Find(c => c.ObjectId == 0x80001234u)!;
Check(a != null && a.DiedUtc == T0 && a.RotsUtc == T0.AddSeconds(60 * 300) && a.Cell == Outdoor && a.X == 100.25f
&& a.ServerCoords && a.Ns == 42.1 && a.Ew == -33.6, "a death's corpse round-trips");
CorpseRecord f = back.Find(c => c.ObjectId == 0x80005678u)!;
Check(f != null && f.DiedUtc == DateTime.MinValue && f.SeenUtc == T0.AddMinutes(2), "a found corpse round-trips");
st.Save("Aelrynth", "Aryze", new[] { new CorpseRecord { DiedUtc = T0, RotsUtc = T0.AddHours(2), Cell = Dungeon } });
st.Save("Aelrynth", "Old", new[] { new CorpseRecord { DiedUtc = T0.AddDays(-3), RotsUtc = T0.AddDays(-2), Cell = Dungeon } });
File.WriteAllText(Path.Combine(_temp, "corpses-store", "corpses", "broken.json"), "{ not json");
var others = st.LoadOthers("Aelrynth", "Drak/kon", T0.AddMinutes(5));
Check(others.Count == 1 && others[0].Character == "Aryze" && others[0].Corpses.Count == 1, "others: rotted and broken files skipped, own left out");
Check(st.Load("Aelrynth", "Nobody", out problem).Count == 0 && problem == null, "no file: no corpses");
}
private static void CorpseRowText()
{
PlaceNames.LoadForTests("{\"locations\":[{\"name\":\"Matron Hive East\",\"type\":\"Dungeon\",\"ns\":-49.78,\"ew\":61.97,\"cell\":\"CC410000\",\"lb\":\"6146\"},"
+ "{\"name\":\"Holtburg\",\"type\":\"Town\",\"ns\":42.1,\"ew\":33.6,\"cell\":\"A9B40016\"}]}");
var dungeon = new CorpseRecord { DiedUtc = T0, RotsUtc = T0.AddHours(3), Cell = Dungeon, X = 10f, Y = 20f, Z = -6f };
Eq(CorpseRows.Place(dungeon), "Matron Hive East", "a dungeon by its name");
Eq(CorpseRows.Place(new CorpseRecord { Cell = 0x01E90100u }), "Dungeon 01E9", "an unnamed dungeon by its landblock");
CorpseBook.MapCoords(Outdoor, 100f, 50f, out double ns, out double ew);
Eq(CorpseRows.Place(new CorpseRecord { Cell = Outdoor, X = 100f, Y = 50f }), CorpseRows.Coords(ns, ew), "outdoors: the map coordinates");
Eq(CorpseRows.Place(new CorpseRecord { Cell = 0xA9B40105u, X = 100f, Y = 50f }), CorpseRows.Coords(ns, ew) + " (indoors)", "a building in town");
Eq(CorpseRows.Coords(-49.78, 61.97), "49.8S, 62.0E", "coordinates");
Eq(CorpseRows.Span(TimeSpan.FromSeconds(40)), "40s", "seconds");
Eq(CorpseRows.Span(TimeSpan.FromMinutes(25.5)), "25m", "minutes");
Eq(CorpseRows.Span(TimeSpan.FromMinutes(190)), "3h 10m", "hours");
Eq(CorpseRows.Span(TimeSpan.FromHours(52)), "2d 4h", "days");
Eq(CorpseRows.Age(dungeon, T0.AddMinutes(25)), "died 25m ago", "age");
Eq(CorpseRows.Rot(dungeon, T0.AddMinutes(25)), "rots in ~2h 35m", "rot estimate");
Eq(CorpseRows.Rot(dungeon, T0.AddHours(4)), "may have rotted", "past its time");
// Standing in the same dungeon 30 m south of it, facing north: ahead, 30 yd N.
var me = new PlayerSpot(Dungeon, 10f, -10f, -6f, 0);
CorpsesView v = CorpseRows.Build(new[] { dungeon }, Array.Empty<OtherCorpses>(), me, T0.AddMinutes(25));
Eq(v.Mine[0].Detail, "died 25m ago · rots in ~2h 35m · 30 yd N", "the detail line");
Check(MathF.Abs(v.Mine[0].Relative) < 0.01f, "the arrow points ahead");
// Facing east: it's to the left.
v = CorpseRows.Build(new[] { dungeon }, Array.Empty<OtherCorpses>(), me with { FacingDeg = 90 }, T0.AddMinutes(25));
Check(MathF.Abs(v.Mine[0].Relative + 90f) < 0.01f, "the arrow points left");
// Another dungeon: no distance, no arrow.
v = CorpseRows.Build(new[] { dungeon }, Array.Empty<OtherCorpses>(), new PlayerSpot(0x01E90100u, 1, 1, 0, 0), T0.AddMinutes(25));
Check(v.Mine[0].Detail == "died 25m ago · rots in ~2h 35m" && float.IsNaN(v.Mine[0].Relative), "elsewhere: no distance");
// Another character's: its name first.
var other = new OtherCorpses("Aelrynth", "Aryze", new[] { dungeon });
v = CorpseRows.Build(Array.Empty<CorpseRecord>(), new[] { other }, me, T0.AddMinutes(25));
Check(v.Mine.Count == 0 && v.Others.Count == 1 && v.Others[0].Detail.StartsWith("Aryze · died 25m ago", StringComparison.Ordinal)
&& v.Others[0].Record == null, "another character's row");
}
}
}

View file

@ -56,6 +56,8 @@ namespace RynthDefective.Tests
Run("picker: favourites and recent weapons first", PickerShortcuts);
Run("pack list: one line per kind of item", PackLists);
Run("commands: /rdef parsing", Commands);
Run("replies: the shared queue (tag, colours, retry, drop, quiet)", ReplyQueue);
Run("replies: every /rdef verb answers, typed right or wrong", ReplyEveryVerb);
Run("store: save and load", StoreRoundTrip);
Run("store: odd files", StoreOddFiles);
Run("hotkeys: the engine's file read for the key under a slot", HotkeyFile);
@ -93,6 +95,12 @@ namespace RynthDefective.Tests
Run("bar: making it independent offers to copy the game's 18 slots", BarIndependentCopy);
Run("store: the independent bar setting; files from before read it off", BarStoreIndependent);
Run("window: the settings window parses and its switches reach their code", BarSettingsWindow);
Run("corpses: the server's lines", CorpseLinesParse);
Run("corpses: a death, the server's line before or after it, nothing dropped", CorpseDeaths);
Run("corpses: a corpse in view is the death beside it, else one found", CorpseSeen);
Run("corpses: gone, rotted, at most 20, forget", CorpseGoneAndExpiry);
Run("corpses: the files, this character's and the others'", CorpseStoreFiles);
Run("corpses: rows: places, times, distance and the arrow", CorpseRowText);
}
finally
{

View file

@ -0,0 +1,133 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthDefective.Model;
using RynthCore.Plugin.Shared;
namespace RynthDefective.Tests
{
// Every /rdef command answers in chat (2026-10-28). The commands themselves need the game (the
// plugin's host), so these check the shared reply queue and, verb by verb, the parse and the line
// the plugin says for it.
internal static partial class Program
{
/// <summary>The shared queue every plugin answers through (Plugins/Shared/CommandReply.cs).</summary>
private static void ReplyQueue()
{
var chat = new List<(string Line, int Type)>();
var log = new List<string>();
bool accept = true;
var r = new CommandReply("[RynthTest]", (t, c) => { if (!accept) return false; chat.Add((t, c)); return true; }, log.Add);
// Nothing waiting: written at once.
r.Ok("Bar shown.");
r.Fail("Which slot? e.g. /rdef clear 3");
r.Ok("[Mini Remote] already tagged");
Eq(r.Pending, 0, "the host took every line at once");
Eq(r.Count, 3, "three replies counted");
Eq(chat.Count, 3, "all three written");
Eq(chat[0], ("[RynthTest] Bar shown.", CommandReply.OkChatType), "ok: the tag in front, green");
Eq(chat[1], ("[RynthTest] Which slot? e.g. /rdef clear 3", CommandReply.FailChatType), "fail: its own colour");
Eq(chat[2].Line, "[Mini Remote] already tagged", "a line with its own tag keeps it");
Check(log.Contains("[RynthTest] Which slot? e.g. /rdef clear 3"), "a failure is logged too");
Check(!r.Flush(), "nothing left");
// The host refuses (another plugin wrote within 100 ms): the line waits, and so does every
// line after it (they stay in order); Flush offers them again, one per tick.
chat.Clear();
accept = false;
r.Ok("Using Stamina Kit (slot 1).");
r.Ok("second");
for (int i = 0; i < 5; i++) r.Flush();
Eq(r.Pending, 2, "refused lines wait");
accept = true;
r.Ok("third");
Eq(chat.Count, 0, "a new line waits behind the refused ones, even when the host would take it");
Check(r.Flush(), "the first goes out when the host takes it");
Eq(r.Pending, 2, "one line per flush (the host drops a second one within 100 ms)");
r.Flush(); r.Flush();
Eq(string.Join("|", chat.ConvertAll(c => c.Line)), "[RynthTest] Using Stamina Kit (slot 1).|[RynthTest] second|[RynthTest] third", "in order");
// A line the host never takes goes to the log after MaxTries, and the next one moves up.
chat.Clear();
accept = false;
log.Clear();
r.Ok("first");
r.Ok("next");
for (int i = 0; i < CommandReply.MaxTries; i++) r.Flush();
Eq(r.Pending, 1, "the stuck line is dropped after MaxTries");
Check(log.Exists(l => l.Contains("[RynthTest] first", StringComparison.Ordinal)), "and logged");
accept = true;
r.Flush();
Eq(chat[^1].Line, "[RynthTest] next", "the next line moves up");
// Line breaks: one chat line each, each tagged. Quiet: logged only. Blank: nothing.
chat.Clear();
log.Clear();
int before = r.Count;
r.Ok("line one\nline two");
r.Ok("a script's success", quiet: true);
r.Fail(" ");
while (r.Flush()) { }
Eq(chat.Count, 2, "two lines for a text with a line break");
Eq(chat[1].Line, "[RynthTest] line two", "the second line tagged too");
Check(log.Contains("[RynthTest] a script's success"), "quiet: in the log");
Check(!chat.Exists(c => c.Line.Contains("script's success", StringComparison.Ordinal)), "quiet: not in chat");
Eq(r.Count - before, 2, "quiet counts as an answer, a blank text doesn't");
accept = false;
r.Ok("x"); r.Clear();
Eq(r.Pending, 0, "Clear forgets the waiting lines");
Eq(CommandReply.Shown("Weapon picker", false), "Weapon picker hidden.", "the shared shown/hidden wording");
}
/// <summary>Each /rdef verb, typed right and typed wrong: what it answers.</summary>
private static void ReplyEveryVerb()
{
// Wrong words: the parser's error is the reply, with an example or the usage.
string[] wrong = { "use", "set", "set x", "set 0", "spell 3", "spell", "clear", "clear x", "bind 3", "bind", "unbind", "unbind x", "slots", "slots 99" };
foreach (string w in wrong)
{
DefCommand c = DefCommandParser.Parse(w);
Check(c.Verb == DefVerb.Error && c.Error.Length > 0, $"'/rdef {w}' answers why");
Check(c.Error.Contains("e.g.", StringComparison.Ordinal) || c.Error.Contains("Usage", StringComparison.Ordinal)
|| c.Error.Contains("How many", StringComparison.Ordinal), $"'/rdef {w}' shows how it's typed: {c.Error}");
}
// Right words: every verb the parser knows maps to an answer.
var right = new (string Typed, DefVerb Verb)[]
{
("", DefVerb.Toggle), ("help", DefVerb.Help), ("list", DefVerb.List), ("status", DefVerb.Status),
("panels", DefVerb.Panels), ("settings", DefVerb.Settings), ("selection", DefVerb.Selection),
("selection 0x80001234", DefVerb.Selection), ("fav", DefVerb.Favourite), ("weapons", DefVerb.Weapons),
("weapons fire", DefVerb.Weapons), ("use 1", DefVerb.Use), ("use Stamina Kit", DefVerb.Use),
("set 2", DefVerb.Set), ("spell 3 Heal Self VI", DefVerb.Spell), ("clear 4", DefVerb.Clear),
("bind 3 F9", DefVerb.Bind), ("unbind 3", DefVerb.Unbind), ("slots 12", DefVerb.Slots),
("Stamina Kit", DefVerb.Use), ("corpses", DefVerb.Corpses), ("corpses clear", DefVerb.Corpses),
};
var seen = new HashSet<DefVerb>();
foreach (var (typed, verb) in right)
{
Eq(DefCommandParser.Parse(typed).Verb, verb, $"'/rdef {typed}'");
seen.Add(verb);
}
foreach (DefVerb v in Enum.GetValues<DefVerb>())
Check(v == DefVerb.Error || seen.Contains(v), $"the table covers /rdef's {v}");
// The lines for the verbs that used to say nothing.
Eq(DefReplies.Window("Shortcuts bar", 1), (true, "Shortcuts bar shown."), "toggle: shown");
Eq(DefReplies.Window("Shortcuts bar", 0), (true, "Shortcuts bar hidden."), "toggle: hidden");
Check(!DefReplies.Window("Selection window", -1).Ok, "a window the engine doesn't have: why not");
var item = new DefSlot { Item = new ItemRef { Name = "Stamina Kit" } };
Eq(DefReplies.UseSlot(item, 1), "Using Stamina Kit (slot 1).", "use: an item slot");
var spell = new DefSlot { SpellId = 1, SpellName = "Strength Other I" };
Check(DefReplies.UseSlot(spell, 2).StartsWith("Casting ", StringComparison.Ordinal), "use: a spell slot casts");
Eq(DefReplies.UseName(" Peerless Healing Kit "), "Using Peerless Healing Kit.", "use by name");
Eq(DefReplies.Weapons(true, "fire"), "Weapon picker shown, searching 'fire'.", "weapons with a search");
Eq(DefReplies.Weapons(false, ""), "Weapon picker hidden.", "weapons: hidden");
Check(DefReplies.TryParseSelection("0x80001234", out uint id, out _) && id == 0x80001234, "selection: a hex id");
Check(!DefReplies.TryParseSelection("bob", out _, out string why) && why.Contains("Usage", StringComparison.Ordinal), "selection: not an id, the usage");
Check(DefReplies.Selected(0x80001234, true, "Pack").Ok, "selection: selected");
Check(!DefReplies.Selected(0x80001234, false, null).Ok, "selection: the game said no");
Check(DefReplies.NoStack.Length > 0, "selection stack: none to select");
}
}
}

View file

@ -37,6 +37,7 @@
<Compile Include="..\..\Plugins\Shared\RynthAiActivityApi.cs" Link="Shared\RynthAiActivityApi.cs" />
<Compile Include="..\..\Plugins\Shared\RynthAiStatusApi.cs" Link="Shared\RynthAiStatusApi.cs" />
<Compile Include="..\..\Plugins\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
<Compile Include="..\..\Plugins\Shared\CommandReply.cs" Link="Shared\CommandReply.cs" />
<!-- The shortcut bar, panel buttons and Selection windows (2026-10-22) draw with the shared ImGui look. -->
<Compile Include="..\..\Plugins\Shared\ImGuiNativeBinding.cs" Link="Shared\ImGuiNativeBinding.cs" />
<Compile Include="..\..\Plugins\Shared\SafeImGui.cs" Link="Shared\SafeImGui.cs" />

View file

@ -66,6 +66,7 @@ namespace RynthInventory.Tests
Run("window events", Events);
Run("banking: no Banking tab (it is RynthILT's own, 2026-10-21)", NoBankingTab);
Run("storage from other plugins (StorageFeed)", StorageFeedTests);
Run("replies: every /ginv word answers", Replies);
}
finally
{

View file

@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthInventory;
namespace RynthInventory.Tests
{
// Every /ginv command answers in chat (2026-10-28). RunCommand needs the plugin's host, so the parse
// of every /ginv word and the lines it says are checked here.
internal static partial class Program
{
private static void Replies()
{
var words = new (string Typed, InventoryVerb Verb, string Text)[]
{
("", InventoryVerb.Window, ""), ("scan", InventoryVerb.Scan, ""), ("RESCAN", InventoryVerb.Scan, ""),
("keep", InventoryVerb.Keep, ""), ("reload", InventoryVerb.Reload, ""), ("status", InventoryVerb.Status, ""),
("help", InventoryVerb.Help, ""), ("?", InventoryVerb.Help, ""),
("Pyreal Mote", InventoryVerb.Search, "Pyreal Mote"), (" scan me ", InventoryVerb.Search, "scan me"),
};
var seen = new HashSet<InventoryVerb>();
foreach (var (typed, verb, text) in words)
{
InventoryCommand c = InventoryCommand.Parse(typed);
Eq(c.Verb, verb, $"'/ginv {typed}'");
Eq(c.Text, text, $"'/ginv {typed}': the search keeps its case");
seen.Add(c.Verb);
}
foreach (InventoryVerb v in Enum.GetValues<InventoryVerb>()) Check(seen.Contains(v), $"the table covers /ginv's {v}");
Eq(InventoryCommand.Window(true), "Global Inventory shown.", "/ginv: shown");
Eq(InventoryCommand.Window(false), "Global Inventory hidden.", "/ginv: hidden");
Eq(InventoryCommand.Searching(" Pyreal Mote "), "Global Inventory: searching for 'Pyreal Mote'.", "/ginv <text>");
Check(InventoryCommand.Usage.Contains("/ginv status"), "help: the usage");
Check(InventoryCommand.NoWindows.Contains("can't show plugin windows"), "no plugin windows: why");
}
}
}

View file

@ -31,6 +31,7 @@
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\UI\ScriptWindows\DisplayListParser.cs" Link="Engine\DisplayListParser.cs" />
<!-- The plugin links this one from Plugins/Shared (the glob above only covers the plugin's folder). -->
<Compile Include="..\..\Plugins\Shared\StorageFeed.cs" Link="Shared\StorageFeed.cs" />
<Compile Include="..\..\Plugins\Shared\CommandReply.cs" Link="Shared\CommandReply.cs" />
</ItemGroup>
<ItemGroup>

View file

@ -261,6 +261,12 @@ internal static class Harness
});
// A second script in the same plugin (another script competing for a handler).
Fn("runScript", a => { Plugin!.RunCode(Str(a, 0), Str(a, 1)); return DynValue.Nil; });
// A script file in the (temp) Scripts folder, for "/lua start <name>" (replies.lua).
Fn("writeScript", a =>
{
System.IO.File.WriteAllText(System.IO.Path.Combine(RynthLuaPaths.Scripts, Str(a, 0) + ".lua"), Str(a, 1));
return DynValue.Nil;
});
Fn("stopScript", a => DynValue.NewBoolean(Plugin!.StopScript(Str(a, 0))));
Fn("scriptLoaded", a => DynValue.NewBoolean(Plugin!.ScriptIsLoaded(Str(a, 0))));
Fn("scriptConsole", a => DynValue.NewString(Plugin!.ScriptConsoleText(Str(a, 0))));

View file

@ -43,6 +43,7 @@
<ItemGroup>
<!-- RynthLuaPaths.cs uses the install-folder resolver. -->
<Compile Include="..\..\Plugins\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
<Compile Include="..\..\Plugins\Shared\CommandReply.cs" Link="Shared\CommandReply.cs" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,64 @@
-- Every /lua command answers in chat (2026-10-28): each built-in verb typed right and typed wrong
-- gives a "[RynthLua]" line, a wrong one saying why (and the usage). The lines go through the shared
-- reply queue (Plugins/Shared/CommandReply.cs), written on the ticks after the command.
local function settle(ms)
local t = 0
while t < ms do sleep(20); t = t + 20 end
end
-- Types the command and returns the RynthLua lines it answered with.
local function answer(cmd)
harness.clearCalls()
check(harness.chatInput(cmd), cmd .. ": eaten")
settle(200)
local lines = {}
for _, l in ipairs(harness.chatLog()) do
if string.find(l, "[RynthLua]", 1, true) == 1 then lines[#lines + 1] = l end
end
return lines
end
local function says(cmd, needle)
local lines = answer(cmd)
check(#lines > 0, cmd .. ": answers")
local found = false
for _, l in ipairs(lines) do
if string.find(l, needle, 1, true) then found = true end
end
check(found, cmd .. ": says '" .. needle .. "' (got: " .. table.concat(lines, " / ") .. ")")
end
harness.writeScript("helper", "while true do sleep(1000) end")
-- right forms
says("/lua list", "Scripts (")
says("/lua start helper", "Running helper.")
says("/lua restart helper", "Restarted helper.")
says("/lua execin helper x = 1", "execin helper: started")
says("/lua autostart helper none", "helper: autostart none.")
says("/lua stop helper", "Stopped helper.")
says("/lua exec y = 2", "exec: started")
says("/lua exec while true do sleep(1000) end", "exec: started")
says("/lua stop exec", "Stopped exec.")
says("/lua hud list", "No huds.")
says("/lua", "/lua list | start")
says("/lua help", "/lua list | start")
-- wrong forms: why, and how it's typed
says("/lua start nosuch", "No script named 'nosuch'")
says("/lua restart", "No script named")
says("/lua stop nosuch", "nosuch isn't running.")
says("/lua exec", "Usage: /lua exec <code>")
says("/lua exec this is not lua", "exec: the code didn't run")
says("/lua execin", "Usage: /lua execin <script> <code>")
says("/lua execin nosuch x = 1", "nosuch isn't running.")
says("/lua autostart", "Usage: /lua autostart")
says("/lua autostart helper sometimes", "Usage: /lua autostart")
says("/lua hud show nosuch/hud", "No hud named")
says("/lua hud bench lots", "Usage: /lua hud bench")
says("/lua hud bench off", "The bench isn't running.")
says("/lua hud wobble", "Unknown '/lua hud wobble'.")
says("/lua wobble", "Unknown '/lua wobble'.")
done()

View file

@ -42,6 +42,7 @@
<ItemGroup>
<!-- RynthLuaPaths.cs uses the install-folder resolver. -->
<Compile Include="..\..\Plugins\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
<Compile Include="..\..\Plugins\Shared\CommandReply.cs" Link="Shared\CommandReply.cs" />
</ItemGroup>
</Project>

View file

@ -48,6 +48,7 @@ internal static partial class Program
Run(nameof(ArrowSingleTarget), ArrowSingleTarget);
Run(nameof(ArrowAlongRoute), ArrowAlongRoute);
Run(nameof(FavoritesAndRecent), FavoritesAndRecent);
Run(nameof(CommandReplies), CommandReplies);
Run(nameof(CoordinateParsing), CoordinateParsing);
Run(nameof(BearingAndDistance), BearingAndDistance);
Run(nameof(RealData), RealData);
@ -512,6 +513,31 @@ internal static partial class Program
Check(back.RemoveFavorite("HOLTBURG") && back.Favorites.Count == 0, "remove by name");
}
/// <summary>
/// The /rnav words that used to answer nothing (2026-10-28: every command answers): "recent" without
/// "clear", "arrive" alone or with a wrong number, an unknown word. The rest of /rnav already
/// answered; RunCommand itself needs the game, so its lines are checked here.
/// </summary>
private static void CommandReplies()
{
var s = new AtlasStore();
Check(NavReplies.Recent(s.Recent).StartsWith("no recent places", StringComparison.Ordinal), "recent: none yet");
s.Touch(new SavedPlace { Name = "Holtburg", Ns = 42.08, Ew = 33.6 });
s.Touch(new SavedPlace { Name = "Yaraq", Ns = -21.5, Ew = -1.8 });
string recent = NavReplies.Recent(s.Recent);
Check(recent.Contains("(2): Yaraq, Holtburg") && recent.Contains("/rnav recent clear"), "recent: newest first, and how to clear: " + recent);
foreach (var (typed, ok) in new[] { ("10", true), ("2", true), ("200", true), ("1", false), ("201", false), ("far", false), ("", false) })
{
Check(NavReplies.TryArrive(typed, out double yd) == ok, $"arrive '{typed}' {(ok ? "taken" : "refused")}");
if (ok) Check(NavReplies.Arrived(yd).Contains($"{yd:F0} yd"), $"arrive {typed}: the new distance");
else Check(NavReplies.ArriveUsage(typed, 10).Contains("/rnav arrive <yards 2-200>"), $"arrive '{typed}': the usage");
}
Check(NavReplies.ArriveUsage("far", 10).StartsWith("'far' isn't 2-200 yd.", StringComparison.Ordinal), "arrive far: says why");
Check(NavReplies.ArriveUsage("", 12).Contains("within 12 yd"), "arrive alone: the distance now");
Check(NavReplies.Unknown("gogo") == "unknown 'gogo' — /rnav help", "an unknown word");
}
// ── Coordinates ──────────────────────────────────────────────────────────
private static void CoordinateParsing()

View file

@ -20,6 +20,7 @@
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\NavCoords.cs" Link="Linked\NavCoords.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\Atlas.cs" Link="Linked\Atlas.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\AtlasStore.cs" Link="Linked\AtlasStore.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\NavReplies.cs" Link="Linked\NavReplies.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\ArrowGuide.cs" Link="Linked\ArrowGuide.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\RecallMemory.cs" Link="Linked\RecallMemory.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNav\RecallPlanner.cs" Link="Linked\RecallPlanner.cs" />

View file

@ -28,6 +28,7 @@ internal static partial class Program
StableOrder();
Vitals();
WindowChecks();
Replies();
Console.WriteLine($"{_checks} checks, {_failed} failed");
return _failed == 0 ? 0 : 1;

View file

@ -0,0 +1,44 @@
using RynthCore.Plugin.RynthNet;
using RynthCore.Plugin.Shared;
namespace RynthNet.Tests;
// Every /rn command answers in chat (2026-10-28). They all did; what was missing is that a several-line
// answer (/rn help, /rn list, /rn status) lost every line but the first to the host's 100 ms limit, and
// that a refusal looked like a success. HandleLocal needs the network node and the host, so the
// argument parsing behind each verb's right and wrong forms, and the shared queue, are checked here.
internal static partial class Program
{
private static void Replies()
{
// bc / bca: "[delay] command".
CommandParser.DelayAndCommand("500 /say hi", out int delay, out string command);
Check(delay == 500 && command == "/say hi", "/rn bc 500 /say hi: the delay, then the command");
CommandParser.DelayAndCommand("/say hi", out delay, out command);
Check(delay == 0 && command == "/say hi", "/rn bc /say hi: no delay");
CommandParser.DelayAndCommand("", out _, out command);
Check(command.Length == 0, "/rn bc alone: no command (it answers 'no command given.')");
// bct: tags first; none is the usage.
Check(CommandParser.TagsAndRest("heal,box 250 /ra start", out var tags, out string after)
&& tags.Count == 2 && after == "250 /ra start", "/rn bct heal,box 250 /ra start");
Check(!CommandParser.TagsAndRest("", out _, out _), "/rn bct alone: the usage");
// tell: a name and a command; a name alone is the usage.
var known = new[] { "Zed Healer", "Alpha" };
Check(CommandParser.NameAndCommand("Zed Healer /ra start", known, out string name, out command)
&& name == "Zed Healer" && command == "/ra start", "/rn tell Zed Healer /ra start: the longest known name");
Check(CommandParser.NameAndCommand("Somebody, /say hi", known, out name, out command) && name == "Somebody",
"/rn tell Somebody, /say hi: the comma splits");
Check(!CommandParser.NameAndCommand("Alpha", known, out _, out _), "/rn tell Alpha alone: the usage");
Check(!CommandParser.NameAndCommand("", known, out _, out _), "/rn tell alone: the usage");
// A several-line answer: every line goes out, one per tick, even when the host refuses some.
var written = new List<string>();
int call = 0;
var reply = new CommandReply("[RynthNet]", (t, c) => { if (++call % 2 == 0) return false; written.Add(t); return true; });
for (int i = 0; i < 11; i++) reply.Ok("help line " + i);
for (int i = 0; i < 40 && reply.Pending > 0; i++) reply.Flush();
Check(written.Count == 11 && written[10] == "[RynthNet] help line 10", "/rn help: all 11 lines written, in order");
}
}

View file

@ -24,6 +24,8 @@
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNet\Characters\CharactersRows.cs" Link="RynthNet\CharactersRows.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNet\Characters\AtlasNames.cs" Link="RynthNet\AtlasNames.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNet\Characters\CharactersManifest.cs" Link="RynthNet\CharactersManifest.cs" />
<Compile Include="..\..\Plugins\RynthCore.Plugin.RynthNet\CommandParser.cs" Link="RynthNet\CommandParser.cs" />
<Compile Include="..\..\Plugins\Shared\CommandReply.cs" Link="Shared\CommandReply.cs" />
<Compile Include="..\..\Plugins\Shared\RynthUi\RynthIcons.cs" Link="Shared\RynthIcons.cs" />
</ItemGroup>

View file

@ -65,6 +65,7 @@ namespace RynthOracle.Tests
Refreshes();
SkillsTabs();
ServerMove();
Replies();
Console.WriteLine($"{_pass} passed, {_fail} failed");
return _fail == 0 ? 0 : 1;
}

View file

@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthOracle;
using RynthCore.Plugin.RynthOracle.Views;
namespace RynthOracle.Tests
{
// Every /ro command answers in chat (2026-10-28). RunCommand needs the plugin's host (its windows),
// so the parse of every /ro word and the line each verb says are checked here.
internal static partial class Program
{
private static void Replies()
{
var words = new (string Typed, OracleVerb Verb, string Tab)[]
{
("", OracleVerb.Window, ""), ("void", OracleVerb.Void, ""), ("timers", OracleVerb.Timers, ""), ("timer", OracleVerb.Timers, ""),
("quests", OracleVerb.Quests, ""), ("refresh", OracleVerb.Quests, ""),
("fellowship", OracleVerb.Tab, OracleView.TabFellowship), ("fellow", OracleVerb.Tab, OracleView.TabFellowship), ("fship", OracleVerb.Tab, OracleView.TabFellowship),
("character", OracleVerb.Tab, OracleView.TabCharacter), ("char", OracleVerb.Tab, OracleView.TabCharacter),
("legendary", OracleVerb.Trackers, OracleView.TabQuests), ("legend", OracleVerb.Trackers, OracleView.TabQuests), ("john", OracleVerb.Trackers, OracleView.TabQuests),
("markers", OracleVerb.Trackers, OracleView.TabQuests), ("marker", OracleVerb.Trackers, OracleView.TabQuests), ("trackers", OracleVerb.Trackers, OracleView.TabQuests),
("skills", OracleVerb.Tab, OracleView.TabSkills), ("skill", OracleVerb.Tab, OracleView.TabSkills),
("attributes", OracleVerb.Tab, OracleView.TabAttributes), ("attrs", OracleVerb.Tab, OracleView.TabAttributes),
("attribute", OracleVerb.Tab, OracleView.TabAttributes), ("vitals", OracleVerb.Tab, OracleView.TabAttributes),
("progress", OracleVerb.Tab, OracleView.TabProgress), ("progression", OracleVerb.Tab, OracleView.TabProgress),
("status", OracleVerb.Status, ""), ("about", OracleVerb.About, OracleView.TabAbout), ("help", OracleVerb.Help, ""), ("?", OracleVerb.Help, ""),
("STATUS", OracleVerb.Status, ""), ("questz", OracleVerb.Unknown, ""), ("dynamic", OracleVerb.Unknown, ""),
};
var seen = new HashSet<OracleVerb>();
foreach (var (typed, verb, tab) in words)
{
OracleCommand c = OracleCommand.Parse(typed);
Check(c.Verb == verb && c.Tab == tab, $"'/ro {typed}': {verb} {tab} (got {c.Verb} {c.Tab})");
seen.Add(c.Verb);
}
foreach (OracleVerb v in Enum.GetValues<OracleVerb>()) Check(seen.Contains(v), $"the table covers /ro's {v}");
Check(OracleCommand.Parse("legendary").Trackers == QuestKind.Legendary && OracleCommand.Parse("markers").Trackers == QuestKind.Marker
&& OracleCommand.Parse("trackers").Trackers == null, "the trackers each word shows");
Check(OracleCommand.Parse("void").ShowsWindow && !OracleCommand.Parse("status").ShowsWindow && !OracleCommand.Parse("quests").ShowsWindow,
"which verbs show a window (they say why not without plugin windows)");
// The lines.
Check(OracleCommand.Shown("Oracle window", true) == "Oracle window shown.", "/ro: shown");
Check(OracleCommand.Shown("Void window", false) == "Void window hidden.", "/ro void: hidden");
Check(OracleCommand.OnTab(OracleView.TabSkills) == "Oracle window shown on its Skills tab.", "a tab");
foreach (QuestKind? k in new QuestKind?[] { QuestKind.Legendary, QuestKind.Marker, null })
Check(OracleCommand.OnTrackers(k).StartsWith("Oracle window shown on the Quests tab", StringComparison.Ordinal), $"trackers {k}");
Check(OracleCommand.Quests(true, true, 0) == (true, "Reading your quest flags (/myquests)..."), "quests: sent");
Check(!OracleCommand.Quests(false, false, 0).Ok, "quests: not in the world");
var wait = OracleCommand.Quests(true, false, 42);
Check(!wait.Ok && wait.Text.Contains("42s"), "quests: the server's minute, with the wait");
Check(!OracleCommand.Quests(true, false, 0).Ok, "quests: one already out");
string unknown = OracleCommand.Unknown("questz");
Check(unknown.StartsWith("Unknown '/ro questz'.", StringComparison.Ordinal) && unknown.Contains("/ro status"), "an unknown word: named, with the usage");
Check(OracleCommand.NoWindows.Contains("can't show plugin windows"), "no plugin windows: why");
}
}
}

View file

@ -38,6 +38,7 @@
<!-- "RynthServer.QuestPack": the active server plugin's quest pack (as in the plugin's csproj). -->
<Compile Include="..\..\Plugins\Shared\RynthServerQuestPackApi.cs" Link="RynthOracle\Shared\RynthServerQuestPackApi.cs" />
<Compile Include="..\..\Plugins\Shared\ServerQuestPackClient.cs" Link="RynthOracle\Shared\ServerQuestPackClient.cs" />
<Compile Include="..\..\Plugins\Shared\CommandReply.cs" Link="RynthOracle\Shared\CommandReply.cs" />
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\UI\ScriptWindows\DisplayListParser.cs" Link="Engine\DisplayListParser.cs" />
</ItemGroup>

View file

@ -84,6 +84,7 @@ namespace RynthSort.Tests
Run("order: slot orders and the pack column", SlotOrders);
Run("plan: stacks and order inside packs", PlanInPack);
Run("moves: answers for moves within a pack", MoveAnswersInPlace);
Run("replies: every /rsort word answers", Replies);
Run("plan: a fixed inventory runs out of moves", Converges);
Run("loop: auto-sort tidies every pack, then stays still", ConvergesInTheLoop);
Run("remote: another plugin's \"rsort\" command reaches /rsort, anything else is not ours", RemoteCommand);

View file

@ -0,0 +1,42 @@
using System;
using System.Collections.Generic;
using RynthCore.Plugin.RynthSort;
namespace RynthSort.Tests
{
// Every /rsort command answers in chat (2026-10-28). RunCommand needs the plugin's host, so the parse
// of every /rsort word, which ones wait for the login, and the lines are checked here.
internal static partial class Program
{
private static void Replies()
{
var words = new (string Typed, SortVerb Verb, bool Quiet, int? Pack)[]
{
("", SortVerb.Window, false, null), ("on", SortVerb.On, false, null), ("off", SortVerb.Off, false, null),
("on quiet", SortVerb.On, true, null), ("OFF Quiet", SortVerb.Off, true, null),
("now", SortVerb.Now, false, null), ("tidy", SortVerb.Now, false, null), ("clean", SortVerb.Clean, false, null),
("unpack", SortVerb.Unpack, false, null), ("unpack 2", SortVerb.Unpack, false, 2), ("unpack x", SortVerb.Unpack, false, null),
("unpack 0", SortVerb.Unpack, false, null), ("status", SortVerb.Status, false, null), ("help", SortVerb.Help, false, null),
("?", SortVerb.Help, false, null), ("sortt", SortVerb.Unknown, false, null),
};
var seen = new HashSet<SortVerb>();
foreach (var (typed, verb, quiet, pack) in words)
{
SortCommand c = SortCommand.Parse(typed);
Check(c.Verb == verb && c.Quiet == quiet && c.Pack == pack, $"'/rsort {typed}': {verb} quiet={quiet} pack={pack} (got {c.Verb} {c.Quiet} {c.Pack})");
seen.Add(c.Verb);
}
foreach (SortVerb v in Enum.GetValues<SortVerb>()) Check(seen.Contains(v), $"the table covers /rsort's {v}");
Check(!SortCommand.Parse("").NeedsLogin && !SortCommand.Parse("help").NeedsLogin, "the window and help work before login");
Check(SortCommand.Parse("now").NeedsLogin && SortCommand.Parse("sortt").NeedsLogin, "the rest says 'Log in first.' before login");
Eq(SortCommand.Window(true), "RynthSort window shown.", "/rsort: shown");
Eq(SortCommand.Started(SortVerb.Now), "Sorting every pack now.", "now / tidy");
Check(SortCommand.Started(SortVerb.Clean).StartsWith("Cleaning", StringComparison.Ordinal), "clean");
Check(SortCommand.Unpacking(3).StartsWith("Emptying pack 3", StringComparison.Ordinal), "unpack 3");
Check(SortCommand.Unpacking(null).StartsWith("Emptying your side packs", StringComparison.Ordinal), "unpack");
string unknown = SortCommand.Unknown("sortt");
Check(unknown.StartsWith("Unknown '/rsort sortt'.", StringComparison.Ordinal) && unknown.Contains(SortCommand.Usage), "an unknown word: named, with the usage");
}
}
}

View file

@ -38,6 +38,7 @@
<Compile Include="..\..\Plugins\Shared\RynthAiActivityApi.cs" Link="Shared\RynthAiActivityApi.cs" />
<Compile Include="..\..\Plugins\Shared\RynthAiStatusApi.cs" Link="Shared\RynthAiStatusApi.cs" />
<Compile Include="..\..\Plugins\Shared\RynthInstallPaths.cs" Link="Shared\RynthInstallPaths.cs" />
<Compile Include="..\..\Plugins\Shared\CommandReply.cs" Link="Shared\CommandReply.cs" />
<Compile Include="..\..\..\RynthCore\src\RynthCore.Engine\UI\ScriptWindows\DisplayListParser.cs" Link="Engine\DisplayListParser.cs" />
</ItemGroup>

Some files were not shown because too many files have changed in this diff Show more