diff --git a/src/RynthCore.Engine/Compatibility/AcCharacterOptions.cs b/src/RynthCore.Engine/Compatibility/AcCharacterOptions.cs
index 3604af8..1c4600e 100644
--- a/src/RynthCore.Engine/Compatibility/AcCharacterOptions.cs
+++ b/src/RynthCore.Engine/Compatibility/AcCharacterOptions.cs
@@ -115,13 +115,17 @@ internal static unsafe class AcCharacterOptions
_status = "acclient.exe not available";
return;
}
- // Pattern only: a fallback-VA result is never called. Written out per call so
- // tools/pe_pattern.py CHECK parses and verifies each pattern against the client.
- static IntPtr PatternOnly(HookResolver.ResolveResult r) =>
- r.Success && r.Source == HookResolver.ResolveSource.PatternScan ? r.Address : IntPtr.Zero;
- IntPtr set = PatternOnly(HookResolver.Resolve(text, "AcCharacterOptions.PlayerModule::SetOption", SetOptionPattern, SetOptionVa));
- IntPtr get = PatternOnly(HookResolver.Resolve(text, "AcCharacterOptions.PlayerModule::GetOption", GetOptionPattern, GetOptionVa));
- IntPtr changed = PatternOnly(HookResolver.Resolve(text, "AcCharacterOptions.PlayerModule::OptionChanged", OptionChangedPattern, OptionChangedVa));
+ // Pattern only, and one match only: a fallback-VA result is never called, nor one of several
+ // matches (HookResolver picks the one nearest the fallback and says "pattern-multimatch").
+ // HookResolver also reports "pattern-unique" without looking further when its first match
+ // sits exactly at the fallback VA, so the count is checked here as well (IsUnique).
+ // Written out per call so tools/pe_pattern.py CHECK parses and verifies each pattern.
+ IntPtr PatternOnly(HookResolver.ResolveResult r, byte?[] pattern) =>
+ r.Success && r.Source == HookResolver.ResolveSource.PatternScan && r.Detail == "pattern-unique"
+ && IsUnique(text.Bytes, pattern) ? r.Address : IntPtr.Zero;
+ IntPtr set = PatternOnly(HookResolver.Resolve(text, "AcCharacterOptions.PlayerModule::SetOption", SetOptionPattern, SetOptionVa), SetOptionPattern);
+ IntPtr get = PatternOnly(HookResolver.Resolve(text, "AcCharacterOptions.PlayerModule::GetOption", GetOptionPattern, GetOptionVa), GetOptionPattern);
+ IntPtr changed = PatternOnly(HookResolver.Resolve(text, "AcCharacterOptions.PlayerModule::OptionChanged", OptionChangedPattern, OptionChangedVa), OptionChangedPattern);
if (set == IntPtr.Zero || get == IntPtr.Zero || changed == IntPtr.Zero)
{
_status = $"not found in this client (set {Ok(set)}, get {Ok(get)}, changed {Ok(changed)})";
@@ -156,6 +160,13 @@ internal static unsafe class AcCharacterOptions
static string Ok(IntPtr p) => p != IntPtr.Zero ? "ok" : "missing";
}
+ /// Does match exactly once in ?
+ private static bool IsUnique(byte[] bytes, byte?[] pattern)
+ {
+ int first = PatternScanner.FindPattern(bytes, pattern);
+ return first >= 0 && PatternScanner.FindPatternInRegion(bytes, pattern, first + 1, bytes.Length) < 0;
+ }
+
/// The PlayerModule, checked to be the class whose option handler was read; or why not.
private static IntPtr Module(out string why)
{
diff --git a/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs b/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs
index a454307..f8b1adc 100644
--- a/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs
+++ b/src/RynthCore.Engine/ImGui/Panels/ChatFace.cs
@@ -284,9 +284,11 @@ internal sealed class ChatFace : IImGuiPanel
}
else
{
- const string join = "Join the Dereth Network";
+ // While a Join waits for the mod's answer (ChatNetwork.PendingJoin, 15 s at most) it is not offered again.
+ bool waiting = ChatNetwork.PendingJoin.IsPending(Environment.TickCount64);
+ string join = waiting ? "Joining the Dereth Network..." : "Join the Dereth Network";
float joinW = ImGuiNET.ImGui.CalcTextSize(join).X + 16;
- if (Button("##chat_net_join", join, new Vector2(x, y), new Vector2(joinW, h), Text, TabActive))
+ if (Button("##chat_net_join", join, new Vector2(x, y), new Vector2(joinW, h), Text, TabActive, enabled: !waiting))
ChatModel.RequestNetworkJoin();
ImGuiNET.ImGui.SetItemTooltip("Put this character on the Dereth Network and listen to its Global room");
}
diff --git a/src/RynthCore.Engine/ImGui/Win32Backend.cs b/src/RynthCore.Engine/ImGui/Win32Backend.cs
index 03d00f2..fe3b95f 100644
--- a/src/RynthCore.Engine/ImGui/Win32Backend.cs
+++ b/src/RynthCore.Engine/ImGui/Win32Backend.cs
@@ -293,12 +293,9 @@ internal static unsafe class Win32Backend
/// Fired on the game thread to run the chat network bar's queued work (ChatModel).
public static Action? OnChatNetwork;
- /// Callable from any thread: runs on AC's main thread.
- public static void RequestChatNetwork()
- {
- if (_gameHwnd != IntPtr.Zero)
- PostMessage(_gameHwnd, WM_RYNTHCORE_NETWORK, IntPtr.Zero, IntPtr.Zero);
- }
+ /// Callable from any thread: runs on AC's main thread. False when nothing was posted.
+ public static bool RequestChatNetwork() =>
+ _gameHwnd != IntPtr.Zero && PostMessage(_gameHwnd, WM_RYNTHCORE_NETWORK, IntPtr.Zero, IntPtr.Zero);
/// The game's main window handle.
public static IntPtr GameHwnd => _gameHwnd;
diff --git a/src/RynthCore.Engine/UI/Data/ChatData.cs b/src/RynthCore.Engine/UI/Data/ChatData.cs
index f8d32a6..852ddad 100644
--- a/src/RynthCore.Engine/UI/Data/ChatData.cs
+++ b/src/RynthCore.Engine/UI/Data/ChatData.cs
@@ -97,6 +97,7 @@ internal sealed unsafe class ChatSource : UiSource
{
// Another client saved the shared settings: pick up its rules / filters (every 2 s at most).
ChatModel.PollSettingsFile();
+ ChatModel.KickNetworkOps(); // the network bar's next queued op, once its gap has passed
try { PollLines(); }
finally
{
@@ -1375,6 +1376,7 @@ internal static class ChatModel
};
Win32Backend.OnChatSend = OnSend;
Win32Backend.OnChatNetwork = RunNetworkOps; // the network bar's Join / Leave and the status question
+ HookNetworkSession();
// Escape leaves the line, as retail's chat does: the half-typed text stays in the box
// (it used to be erased), and Enter or a click on the box carries on typing it.
Win32Backend.OnChatCancel = () =>
@@ -1533,102 +1535,150 @@ internal static class ChatModel
{
if (added.Count == 0 || !AnyNetworkActive()) return;
long now = Environment.TickCount64;
- int eaten = added.RemoveAll(l => ChatNetwork.Observe(l.Text, l.ChatType, now));
+ bool applyJoin = false;
+ int eaten = added.RemoveAll(l =>
+ {
+ bool eat = ChatNetwork.Observe(l.Text, l.ChatType, now, out bool apply);
+ applyJoin |= apply;
+ return eat;
+ });
if (eaten > 0) RynthLog.UI($"ChatModel: the network status answer ({eaten} line{(eaten == 1 ? "" : "s")}) kept out of the scrollback.");
+ // The mod put the character on after a Join: now its room option (RunNetworkOp, ApplyJoinRoom).
+ if (applyJoin && Volatile.Read(ref _pendingJoinEntry) is { } entry) RequestNetwork(NetworkOp.ApplyJoinRoom, entry);
}
- private enum NetworkOp { Query, Join, Leave }
- private static readonly System.Collections.Concurrent.ConcurrentQueue _networkOps = new();
- private static bool _networkSessionHooked;
+ // The network bar's work, on AC's main thread: one op per WM_RYNTHCORE_NETWORK message, at
+ // least NetworkOpPacer.GapMs apart (each op sends at most one line through AC's window proc).
+ // The message is posted only while the gap has passed (KickNetworkOps: the click, and the pump
+ // every poll), never slept for on AC's thread. Each op carries the entry it was asked for.
+ private enum NetworkOp { Query, Join, Leave, ApplyJoinRoom }
+ private readonly record struct NetworkWork(NetworkOp Op, SectionChatTabDecl Entry, long QueuedMs);
+ private static readonly System.Collections.Concurrent.ConcurrentQueue _networkOps = new();
+ private static readonly NetworkOpPacer _networkPacer = new();
+ private static int _networkPosted;
+ private static SectionChatTabDecl? _pendingJoinEntry;
// Settings: JoinKey(server, character) -> the room Join turned on (absent while none).
private static Dictionary _networkJoinRooms = NewMap();
///
/// The main window shows a network tab (its face, every frame): the first time per character
- /// session, once in the world, ask the server whether this character is on the network.
+ /// session, once in the world, ask the server whether this character is on the network. The
+ /// question counts as asked only once it was sent (ChatNetwork.Query).
///
public static void NoteNetworkTabViewed()
{
- HookNetworkSession();
if (!LoginLifecycleHooks.HasObservedLoginComplete || SendLinePtr == IntPtr.Zero) return;
- if (!ChatNetwork.TryBeginQuery()) return;
- RequestNetwork(NetworkOp.Query);
+ if (CurrentNetworkEntry() is not { } entry || !ChatNetwork.Query.TryQueue()) return;
+ if (!RequestNetwork(NetworkOp.Query, entry)) ChatNetwork.Query.Dropped();
}
/// The Join button. Any thread: the work runs on AC's main thread.
- public static void RequestNetworkJoin() => RequestNetwork(NetworkOp.Join);
-
- /// The Leave button. Any thread: the work runs on AC's main thread.
- public static void RequestNetworkLeave() => RequestNetwork(NetworkOp.Leave);
-
- private static void RequestNetwork(NetworkOp op)
+ public static void RequestNetworkJoin()
{
- if (_networkOps.Count >= 8) return; // clicks while the game thread is busy: a few is plenty
- _networkOps.Enqueue(op);
- Win32Backend.RequestChatNetwork();
+ if (CurrentNetworkEntry() is { } entry) RequestNetwork(NetworkOp.Join, entry);
}
- /// A new character session asks again and knows nothing (login and logout). Once.
+ /// The Leave button. Any thread: the work runs on AC's main thread.
+ public static void RequestNetworkLeave()
+ {
+ if (CurrentNetworkEntry() is { } entry) RequestNetwork(NetworkOp.Leave, entry);
+ }
+
+ private static bool RequestNetwork(NetworkOp op, SectionChatTabDecl entry)
+ {
+ if (_networkOps.Count >= 8) return false; // clicks while the game thread is busy: a few is plenty
+ _networkOps.Enqueue(new NetworkWork(op, entry, Environment.TickCount64));
+ KickNetworkOps();
+ return true;
+ }
+
+ ///
+ /// Posts the message that runs the next op, when one is queued, none is posted, and the gap since
+ /// the last op has passed. Any thread (PostMessage); the pump calls it every poll.
+ ///
+ internal static void KickNetworkOps()
+ {
+ if (_networkOps.IsEmpty || !_networkPacer.IsDue(Environment.TickCount64)) return;
+ if (Interlocked.CompareExchange(ref _networkPosted, 1, 0) != 0) return;
+ if (!Win32Backend.RequestChatNetwork()) Volatile.Write(ref _networkPosted, 0); // no window yet: the next kick tries
+ }
+
+ /// A new character session asks again and knows nothing (login and logout). Once, at init.
private static void HookNetworkSession()
{
- if (_networkSessionHooked) return;
- _networkSessionHooked = true;
LoginLifecycleHooks.LoginComplete += ChatNetwork.ResetSession;
LogoutLifecycleHooks.LogoutComplete += ChatNetwork.ResetSession;
}
///
/// AC's main thread, on a fresh window message (Win32Backend, WM_RYNTHCORE_NETWORK), as a typed
- /// line is sent: the queued status question, Join and Leave.
+ /// line is sent: at most one queued op (the status question, Join, Leave, a Join's room).
///
private static void RunNetworkOps()
{
- while (_networkOps.TryDequeue(out NetworkOp op))
+ Volatile.Write(ref _networkPosted, 0);
+ long now = Environment.TickCount64;
+ if (!_networkPacer.IsDue(now)) return; // the next kick posts again once the gap has passed
+ while (_networkOps.TryDequeue(out NetworkWork work))
{
- try { RunNetworkOp(op); }
- catch (Exception ex) { RynthLog.UI($"ChatModel: network {op} failed ({ex.GetType().Name}: {ex.Message})."); }
+ if (NetworkOpPacer.IsStale(work.QueuedMs, now))
+ {
+ if (work.Op == NetworkOp.Query) ChatNetwork.Query.Dropped();
+ RynthLog.UI($"ChatModel: network {work.Op} dropped (queued {now - work.QueuedMs} ms ago).");
+ continue; // nothing sent: the next one may run in this message
+ }
+ _networkPacer.TryTake(now);
+ try { RunNetworkOp(work.Op, work.Entry); }
+ catch (Exception ex)
+ {
+ if (work.Op == NetworkOp.Query) ChatNetwork.Query.Dropped();
+ RynthLog.UI($"ChatModel: network {work.Op} failed ({ex.GetType().Name}: {ex.Message}).");
+ }
+ break; // one op per message
}
+ KickNetworkOps();
}
- private static void RunNetworkOp(NetworkOp op)
+ private static void RunNetworkOp(NetworkOp op, SectionChatTabDecl entry)
{
- SectionChatTabDecl? entry = CurrentNetworkEntry();
- if (entry?.Network is not { } network) return; // the tab or its server went away meanwhile
+ // The entry's server stopped being active meanwhile: nothing of its network applies.
+ if (entry.Network is not { } network || !ChatRouter.ServerIn(_activeServers, entry.Server))
+ {
+ if (op == NetworkOp.Query) ChatNetwork.Query.Dropped();
+ return;
+ }
string command = network.Command;
string key = ChatNetwork.JoinKey(entry.Server, PumpCharacterName());
switch (op)
{
case NetworkOp.Query:
ChatNetwork.Eater.Query(Environment.TickCount64);
- SendChatLine("/" + command);
+ if (SendChatLine("/" + command)) ChatNetwork.Query.MarkSent();
+ else
+ {
+ ChatNetwork.Eater.Clear();
+ ChatNetwork.Query.Dropped();
+ }
break;
case NetworkOp.Join:
- {
+ // The room option waits for the mod's "on" (ChatNetwork.PendingJoin): a refused
+ // join (a name that cannot be an address, a world off the network) sets nothing.
ChatNetwork.JoinProblem = null;
- SendChatLine("/" + command + " on");
- string roomName = Volatile.Read(ref _globalRooms).TryGetValue(entry.Server, out string? found) ? found : entry.GlobalRoomFallback;
- if (!AcCharacterOptions.TryParseRoom(roomName, out AcCharacterOptions.Room room))
- {
- ChatNetwork.JoinProblem = $"no room \"{roomName}\" to listen to";
- break;
- }
- // Already on: Join did not turn it on, so Leave leaves it alone.
- if (!AcCharacterOptions.TryGet(room, out bool wasOn, out string why)
- || (!wasOn && !AcCharacterOptions.TrySet(room, true, out why)))
- {
- ChatNetwork.JoinProblem = $"Hear {AcCharacterOptions.Name(room)} Chat not set: {why}";
- RynthLog.UI("ChatModel: " + ChatNetwork.JoinProblem);
- break;
- }
- if (!wasOn) SetJoinRoom(key, AcCharacterOptions.Name(room));
+ Volatile.Write(ref _pendingJoinEntry, entry);
+ ChatNetwork.PendingJoin.Begin(Environment.TickCount64);
+ if (!SendChatLine("/" + command + " on")) ChatNetwork.PendingJoin.Clear();
+ break;
+
+ case NetworkOp.ApplyJoinRoom:
+ ApplyJoinRoom(entry, key);
break;
- }
case NetworkOp.Leave:
{
ChatNetwork.JoinProblem = null;
+ ChatNetwork.PendingJoin.Clear();
SendChatLine("/" + command + " off");
if (!Volatile.Read(ref _networkJoinRooms).TryGetValue(key, out string? joined)) break;
if (AcCharacterOptions.TryParseRoom(joined, out AcCharacterOptions.Room room)
@@ -1644,11 +1694,55 @@ internal static class ChatModel
}
}
- /// Records (or with null forgets) the room Join turned on for . Saved.
+ ///
+ /// A Join was answered "on": the Global room's Hear option, by ChatNetwork.JoinPlan (an earlier
+ /// Join's room that is no longer the Global one goes off first; the current one goes on only
+ /// when it is off, and is recorded only then). AC's main thread.
+ ///
+ private static void ApplyJoinRoom(SectionChatTabDecl entry, string key)
+ {
+ string roomName = Volatile.Read(ref _globalRooms).TryGetValue(entry.Server, out string? found) ? found : entry.GlobalRoomFallback;
+ if (!AcCharacterOptions.TryParseRoom(roomName, out AcCharacterOptions.Room room))
+ {
+ ChatNetwork.JoinProblem = $"no room \"{roomName}\" to listen to";
+ return;
+ }
+ string current = AcCharacterOptions.Name(room);
+ if (!AcCharacterOptions.TryGet(room, out bool isOn, out string why))
+ {
+ ChatNetwork.JoinProblem = $"Hear {current} Chat not read: {why}";
+ RynthLog.UI("ChatModel: " + ChatNetwork.JoinProblem);
+ return;
+ }
+ string? recorded = Volatile.Read(ref _networkJoinRooms).TryGetValue(key, out string? r) ? r : null;
+ JoinPlanResult plan = ChatNetwork.JoinPlan(recorded, current, isOn);
+ if (plan.TurnOff != null)
+ {
+ if (AcCharacterOptions.TryParseRoom(plan.TurnOff, out AcCharacterOptions.Room old)
+ && !AcCharacterOptions.TrySet(old, false, out why))
+ {
+ ChatNetwork.JoinProblem = $"Hear {AcCharacterOptions.Name(old)} Chat not turned off: {why}";
+ RynthLog.UI("ChatModel: " + ChatNetwork.JoinProblem);
+ return; // the record stays: the next Join tries again
+ }
+ SetJoinRoom(key, null);
+ }
+ if (plan.TurnOn != null && !AcCharacterOptions.TrySet(room, true, out why))
+ {
+ ChatNetwork.JoinProblem = $"Hear {current} Chat not set: {why}";
+ RynthLog.UI("ChatModel: " + ChatNetwork.JoinProblem);
+ return;
+ }
+ SetJoinRoom(key, plan.Record);
+ }
+
+ /// Records (or with null forgets) the room Join turned on for . Saved when it changed.
private static void SetJoinRoom(string key, string? room)
{
lock (EditLock)
{
+ bool have = _networkJoinRooms.TryGetValue(key, out string? was);
+ if (room == null ? !have : have && string.Equals(was, room, StringComparison.Ordinal)) return;
Dictionary map = NewMap(_networkJoinRooms);
if (room == null) map.Remove(key); else map[key] = room;
Volatile.Write(ref _networkJoinRooms, map);
@@ -1656,14 +1750,15 @@ internal static class ChatModel
SaveSettings();
}
- /// A line through the chat parser, as a typed one goes. AC's main thread, on a fresh message.
- private static unsafe void SendChatLine(string text)
+ /// A line through the chat parser, as a typed one goes; false when RynthChat isn't bound. AC's main thread, on a fresh message.
+ private static unsafe bool SendChatLine(string text)
{
IntPtr send = SendLinePtr;
- if (send == IntPtr.Zero) return;
+ if (send == IntPtr.Zero) return false;
IntPtr ptr = Marshal.StringToHGlobalAnsi(text);
try { ((delegate* unmanaged[Cdecl])send)(ptr); }
finally { Marshal.FreeHGlobal(ptr); }
+ return true;
}
/// The creature selected in the game (an NPC or another player), for /tell.
diff --git a/src/RynthCore.Engine/UI/Data/ChatNetwork.cs b/src/RynthCore.Engine/UI/Data/ChatNetwork.cs
index ac241e7..69076ec 100644
--- a/src/RynthCore.Engine/UI/Data/ChatNetwork.cs
+++ b/src/RynthCore.Engine/UI/Data/ChatNetwork.cs
@@ -27,7 +27,6 @@ internal static class ChatNetwork
{
// -1 unknown, 0 off the network, 1 on it. An int so any thread can read and write it whole.
private static int _on = -1;
- private static int _queried;
private static volatile string? _address;
private static volatile string? _joinProblem;
@@ -57,8 +56,11 @@ internal static class ChatNetwork
/// The status question's reply lines to keep out of the scrollback.
public static readonly NetworkReplyEater Eater = new();
- /// True once per character session: the caller asks the server now. Any thread.
- public static bool TryBeginQuery() => Interlocked.Exchange(ref _queried, 1) == 0;
+ /// The once-per-session status question: asked only once it was actually sent.
+ public static readonly NetworkQueryState Query = new();
+
+ /// A Join waiting for the mod to say this character is on (then the room option is set).
+ public static readonly NetworkPendingJoin PendingJoin = new();
/// A new character session (login, logout): nothing known, ask again. Any thread.
public static void ResetSession()
@@ -66,25 +68,51 @@ internal static class ChatNetwork
On = null;
_address = null;
_joinProblem = null;
- Volatile.Write(ref _queried, 0);
+ Query.Reset();
Eater.Clear();
+ PendingJoin.Clear();
}
///
/// One incoming line (the pump): a status line moves On and the address; true when the line is
/// part of the status question's answer and is to be left out of the scrollback.
+ /// : an "on" line answered a pending Join, so its room option is due.
+ /// "This world is not on the Dereth Network." ends any wait (no answer is coming) and is shown.
///
- internal static bool Observe(string text, int chatType, long nowMs)
+ internal static bool Observe(string text, int chatType, long nowMs, out bool applyJoin)
{
+ applyJoin = false;
+ if (IsWorldNotOnLine(text, chatType))
+ {
+ Eater.Clear();
+ PendingJoin.Clear();
+ return false;
+ }
NetworkStatus? status = Classify(text, chatType);
if (status is { } s)
{
On = s.On;
_address = s.On ? s.Address : null;
+ applyJoin = PendingJoin.OnStatus(s, nowMs);
}
return Eater.Take(status, text, chatType, nowMs);
}
+ ///
+ /// What Join does with the room options, given the room an earlier Join turned on and recorded
+ /// (, null when none), the room the Global rule tracks now and whether
+ /// that one is on already. A recorded room that is no longer the current one is turned off (Join
+ /// turned it on: that is what the record means); the current one is turned on only when it is
+ /// off, and recorded only then (or kept, when it was ours already).
+ ///
+ internal static JoinPlanResult JoinPlan(string? recorded, string current, bool currentIsOn)
+ {
+ bool same = recorded != null && string.Equals(recorded, current, StringComparison.OrdinalIgnoreCase);
+ string? turnOff = recorded != null && !same ? recorded : null;
+ if (currentIsOn) return new JoinPlanResult(turnOff, null, same ? recorded : null);
+ return new JoinPlanResult(turnOff, current, current);
+ }
+
// -- The mod's lines --
// ACE ChatMessageType: Broadcast 0x00 (the mod's ShowSystem), System 0x05. A player's speech,
@@ -96,6 +124,11 @@ internal static class ChatNetwork
internal const string NotOnPrefix = "You are not on the Dereth Network";
internal const string OffPrefix = "You are off the Dereth Network";
internal const string DirectoryPrefix = "Your directory page:";
+ internal const string WorldNotOnLine = "This world is not on the Dereth Network."; // NetworkWorld.NotOnNetworkLine
+
+ /// The mod's answer on a world that is not on the network (nothing else follows it).
+ internal static bool IsWorldNotOnLine(string text, int chatType) =>
+ !string.IsNullOrEmpty(text) && IsSystemType(chatType) && string.Equals(text.Trim(), WorldNotOnLine, StringComparison.Ordinal);
///
/// What a line says about this character and the network, or null when it says nothing (or is not
@@ -144,6 +177,107 @@ internal static class ChatNetwork
}
}
+/// What Join does: the room to turn off first (or null), the room to turn on (or null), and the room to record after (null: none).
+internal readonly record struct JoinPlanResult(string? TurnOff, string? TurnOn, string? Record);
+
+///
+/// The once-per-session status question: None (ask when a network tab is viewed), Queued (asked
+/// for, not sent yet: not asked again meanwhile), Sent (answered or not, never again this session).
+/// A queued question that could not be sent (the tab changed first) goes back to None. Any thread.
+///
+internal sealed class NetworkQueryState
+{
+ private const int None = 0, Queued = 1, Sent = 2;
+ private int _state;
+
+ /// True when the question is still to be asked; the caller queues it now.
+ public bool TryQueue() => Interlocked.CompareExchange(ref _state, Queued, None) == None;
+
+ /// The question went out: never again this session.
+ public void MarkSent() => Volatile.Write(ref _state, Sent);
+
+ /// The queued question was dropped unsent: the next view asks again.
+ public void Dropped() => Interlocked.CompareExchange(ref _state, None, Queued);
+
+ public bool WasSent => Volatile.Read(ref _state) == Sent;
+
+ public void Reset() => Volatile.Write(ref _state, None);
+}
+
+///
+/// A Join waiting for the mod's answer: the room option is set only when an "on" status line
+/// arrives within of the Join. Anything else (an "off" line, silence, a
+/// refusal such as a name that cannot be an address) sets nothing, and the wait just lapses.
+/// Any thread.
+///
+internal sealed class NetworkPendingJoin
+{
+ public const long TimeoutMs = 15_000;
+
+ private readonly object _lock = new();
+ private long _since = -1;
+
+ /// Join was just sent.
+ public void Begin(long nowMs)
+ {
+ lock (_lock) _since = nowMs;
+ }
+
+ public void Clear()
+ {
+ lock (_lock) _since = -1;
+ }
+
+ /// Is a Join waiting (and not lapsed) at ?
+ public bool IsPending(long nowMs)
+ {
+ lock (_lock)
+ {
+ if (_since >= 0 && nowMs - _since > TimeoutMs) _since = -1;
+ return _since >= 0;
+ }
+ }
+
+ /// A status line arrived: true (once) when it is the "on" that a waiting Join was waiting for.
+ public bool OnStatus(NetworkStatus status, long nowMs)
+ {
+ lock (_lock)
+ {
+ if (_since < 0) return false;
+ if (nowMs - _since > TimeoutMs) { _since = -1; return false; }
+ if (!status.On) return false; // an earlier answer still in flight; keep waiting
+ _since = -1;
+ return true;
+ }
+ }
+}
+
+///
+/// Paces the network bar's work: one chat line through AC's window proc per window message, and
+/// at least between two (OnLoginCommandRunner.InterCommandGapMs is 250 ms too).
+/// Work older than is dropped. Pure; ChatModel holds one.
+///
+internal sealed class NetworkOpPacer
+{
+ public const long GapMs = 250;
+ public const long MaxAgeMs = 10_000;
+ private long _lastMs = long.MinValue / 2; // read whole on any thread (Interlocked: a 32-bit process)
+
+ /// Has the gap since the last op passed at ? Any thread.
+ public bool IsDue(long nowMs) => nowMs - Interlocked.Read(ref _lastMs) >= GapMs;
+
+ /// May one op run at ? If so it is counted as run then. One thread.
+ public bool TryTake(long nowMs)
+ {
+ if (!IsDue(nowMs)) return false;
+ Interlocked.Exchange(ref _lastMs, nowMs);
+ return true;
+ }
+
+ /// Is an op queued at too old to run at ?
+ public static bool IsStale(long queuedMs, long nowMs) => nowMs - queuedMs > MaxAgeMs;
+}
+
///
/// The answer to the one status question a session asks: the first status line within
/// of the question, and a "Your directory page:" line within
diff --git a/tools/ChatFilterTests/Program.cs b/tools/ChatFilterTests/Program.cs
index 12779d6..ba736a4 100644
--- a/tools/ChatFilterTests/Program.cs
+++ b/tools/ChatFilterTests/Program.cs
@@ -60,6 +60,7 @@ internal static class Program
PinBookkeeping();
NetworkRewrite();
NetworkStatusLines();
+ NetworkSourcePins();
SharedFileReload();
LineColorTags();
LineColorKinds();
@@ -1607,7 +1608,7 @@ internal static class Program
Check(ChatFilterPresets.All.Length >= 10, "a useful set");
}
- // 2026-11-15: pinned tab bookkeeping (ChatPins), pure.
+ // 2026-11-15: network tab sends (ChatNetwork.Rewrite), pure.
private static void NetworkRewrite()
{
Case("Rewrite_PlainText");
@@ -1706,13 +1707,14 @@ internal static class Program
Case("Observe_MovesOnAndAddress");
ChatNetwork.ResetSession();
Check(ChatNetwork.On == null && ChatNetwork.Address == null, "a new session knows nothing");
- Check(ChatNetwork.TryBeginQuery() && !ChatNetwork.TryBeginQuery(), "one question per session");
+ Check(ChatNetwork.Query.TryQueue() && !ChatNetwork.Query.TryQueue(), "one question queued per session");
+ ChatNetwork.Query.MarkSent();
ChatNetwork.Eater.Query(100);
- Check(ChatNetwork.Observe(status, Broadcast, 200), "the session's answer is eaten");
+ Check(ChatNetwork.Observe(status, Broadcast, 200, out bool apply0) && !apply0, "the session's answer is eaten (no Join pending)");
Check(ChatNetwork.On == true && ChatNetwork.Address == "Ann@alpha", "and puts the character on, as Ann@alpha");
Check(ChatNetwork.OnOrUnknown && ChatNetwork.Rewrite("hi", "dn", ChatNetwork.OnOrUnknown) == "/dn global hi", "on: Global lines are sent");
- Check(!ChatNetwork.Observe(said, Speech, 300) && ChatNetwork.On == true, "a player's look-alike changes nothing");
- Check(!ChatNetwork.Observe("You are off the Dereth Network. Nobody on another world can see you or tell you, and your profile is out of its directory.", Broadcast, 400),
+ Check(!ChatNetwork.Observe(said, Speech, 300, out _) && ChatNetwork.On == true, "a player's look-alike changes nothing");
+ Check(!ChatNetwork.Observe("You are off the Dereth Network. Nobody on another world can see you or tell you, and your profile is out of its directory.", Broadcast, 400, out _),
"a later leave line is shown");
Check(ChatNetwork.On == false && ChatNetwork.Address == null, "and puts the character off");
Check(ChatNetwork.Rewrite("hi", "dn", ChatNetwork.OnOrUnknown) == null, "off: Global lines are blocked");
@@ -1720,9 +1722,80 @@ internal static class Program
ChatNetwork.ResetSession();
Check(ChatNetwork.On == null && ChatNetwork.OnOrUnknown && ChatNetwork.JoinProblem == null, "logout/login: unknown again (sent as on), no problem shown");
Check(ChatNetwork.Rewrite("hi", "dn", ChatNetwork.OnOrUnknown) == "/dn global hi", "unknown: Global lines are sent");
- Check(ChatNetwork.TryBeginQuery(), "and the next view asks again");
+ Check(ChatNetwork.Query.TryQueue(), "and the next view asks again");
ChatNetwork.ResetSession();
+ // F3: the question counts as asked only once it was sent.
+ Case("Query_ArmedOnlyWhenSent");
+ var q = new NetworkQueryState();
+ Check(q.TryQueue(), "a new session queues the question");
+ Check(!q.TryQueue(), "not twice while queued (every frame views the tab)");
+ q.Dropped();
+ Check(!q.WasSent && q.TryQueue(), "dropped unsent (the tab changed, RynthChat not bound): the next view asks again");
+ q.MarkSent();
+ Check(q.WasSent && !q.TryQueue(), "sent: never again this session");
+ q.Dropped();
+ Check(q.WasSent && !q.TryQueue(), "a late drop does not undo a sent question");
+ q.Reset();
+ Check(!q.WasSent && q.TryQueue(), "a new session asks again");
+
+ // F7: a world off the network answers with one line and nothing more.
+ Case("WorldNotOn_ClearsTheWait");
+ ChatNetwork.ResetSession();
+ ChatNetwork.On = true;
+ ChatNetwork.Eater.Query(1000);
+ ChatNetwork.PendingJoin.Begin(1000);
+ Check(!ChatNetwork.Observe("This world is not on the Dereth Network.", Broadcast, 1100, out bool applyW) && !applyW, "the world's line is shown, applies nothing");
+ Check(ChatNetwork.On == true, "and does not move On");
+ Check(!ChatNetwork.PendingJoin.IsPending(1100), "it ends a waiting Join");
+ Check(!ChatNetwork.Observe(status, Broadcast, 1200, out _), "and the eater: a later status line is shown");
+ Check(!ChatNetwork.IsWorldNotOnLine("This world is not on the Dereth Network.", Speech), "said in Local it is nothing");
+ ChatNetwork.ResetSession();
+
+ // F5: the room option waits for the mod's "on" after a Join.
+ Case("PendingJoin_StateMachine");
+ var pj = new NetworkPendingJoin();
+ var onS = new NetworkStatus(true, "Ann@alpha");
+ var offS = new NetworkStatus(false, null);
+ Check(!pj.OnStatus(onS, 0), "no Join: an on line applies nothing");
+ pj.Begin(1000);
+ Check(pj.IsPending(1000) && pj.IsPending(1000 + NetworkPendingJoin.TimeoutMs), "waiting up to the timeout");
+ Check(!pj.OnStatus(offS, 1500) && pj.IsPending(1500), "an off line (an earlier answer still in flight) keeps waiting");
+ Check(pj.OnStatus(onS, 2000), "the on line applies the room");
+ Check(!pj.IsPending(2000) && !pj.OnStatus(onS, 2100), "once only");
+ pj.Begin(10_000);
+ Check(!pj.OnStatus(onS, 10_000 + NetworkPendingJoin.TimeoutMs + 1), "an on line after the timeout applies nothing");
+ Check(!pj.IsPending(10_000 + NetworkPendingJoin.TimeoutMs + 1), "and the wait is over");
+ pj.Begin(40_000);
+ Check(!pj.IsPending(40_000 + NetworkPendingJoin.TimeoutMs + 1), "silence: the wait lapses by itself");
+ Check(!pj.OnStatus(onS, 40_000 + NetworkPendingJoin.TimeoutMs + 2), "and nothing is applied later");
+ pj.Begin(60_000);
+ pj.Clear();
+ Check(!pj.OnStatus(onS, 60_100), "Leave (Clear) cancels a waiting Join");
+ ChatNetwork.ResetSession();
+ ChatNetwork.PendingJoin.Begin(5000);
+ Check(!ChatNetwork.Observe("This character's name cannot be a network address, so it cannot join the Dereth Network.", Broadcast, 5100, out bool applyR) && !applyR,
+ "a refused join applies nothing");
+ Check(ChatNetwork.Observe(status, Broadcast, 5200, out bool applyOn) == false && applyOn, "an on line after a Join applies the room (and, unasked, is shown)");
+ ChatNetwork.ResetSession();
+
+ // F4: which rooms Join turns off and on, and what it records.
+ Case("JoinPlan");
+ Check(ChatNetwork.JoinPlan(null, "Roleplay", false) == new JoinPlanResult(null, "Roleplay", "Roleplay"), "nothing recorded, room off: turn on, record");
+ Check(ChatNetwork.JoinPlan(null, "Roleplay", true) == new JoinPlanResult(null, null, null), "nothing recorded, room on already: touch nothing, record nothing");
+ Check(ChatNetwork.JoinPlan("Roleplay", "Roleplay", true) == new JoinPlanResult(null, null, "Roleplay"), "ours and still on: keep the record");
+ Check(ChatNetwork.JoinPlan("Roleplay", "roleplay", false) == new JoinPlanResult(null, "roleplay", "roleplay"), "ours but turned off since (any case): on again, recorded");
+ Check(ChatNetwork.JoinPlan("Roleplay", "General", false) == new JoinPlanResult("Roleplay", "General", "General"), "Global moved: the old room off, the new on, recorded");
+ Check(ChatNetwork.JoinPlan("Roleplay", "General", true) == new JoinPlanResult("Roleplay", null, null), "Global moved to a room on already: old off, new untouched, no record");
+
+ Case("OpPacer");
+ var pacer = new NetworkOpPacer();
+ Check(pacer.IsDue(0) && pacer.TryTake(0), "the first op runs at once");
+ Check(!pacer.IsDue(NetworkOpPacer.GapMs - 1) && !pacer.TryTake(NetworkOpPacer.GapMs - 1), "the next waits the gap");
+ Check(pacer.TryTake(NetworkOpPacer.GapMs), "and runs once it has passed");
+ Check(NetworkOpPacer.GapMs >= 250, "the gap is at least OnLoginCommandRunner's 250 ms");
+ Check(!NetworkOpPacer.IsStale(0, NetworkOpPacer.MaxAgeMs) && NetworkOpPacer.IsStale(0, NetworkOpPacer.MaxAgeMs + 1), "old work is dropped");
+
Case("JoinKey");
Check(ChatNetwork.JoinKey(" DreamWeave ", " Ann ") == "dreamweave/Ann", "server lower-cased, both trimmed, the name kept");
@@ -1738,6 +1811,155 @@ internal static class Program
Check(JsonSerializer.Deserialize(OldFile, opts)!.NetworkJoinRooms == null, "an older file has none");
}
+ // 2026-11-15 (Task 11 review, F1 and F8): source scans for what the engine-side code must keep
+ // doing (it is not compiled into this tool). Each pin is a predicate over the source, matched on
+ // whole trimmed lines so a commented-out line does not count, and each is shown to fail on a
+ // mutated copy of the same source (the mutation proof), so a pin that passes vacuously is caught.
+ private static void NetworkSourcePins()
+ {
+ string? chatData = RepoFile("src", "RynthCore.Engine", "UI", "Data", "ChatData.cs");
+ string? options = RepoFile("src", "RynthCore.Engine", "Compatibility", "AcCharacterOptions.cs");
+ string? resolver = RepoFile("src", "RynthCore.Engine", "Compatibility", "HookResolver.cs");
+ Case("NetworkPins_FilesFound");
+ Check(chatData != null && options != null && resolver != null, "found ChatData.cs, AcCharacterOptions.cs and HookResolver.cs by walking up from " + AppContext.BaseDirectory);
+ if (chatData == null || options == null || resolver == null) return;
+ string data = File.ReadAllText(chatData).Replace("\r\n", "\n");
+ string opt = File.ReadAllText(options).Replace("\r\n", "\n");
+ string res = File.ReadAllText(resolver).Replace("\r\n", "\n");
+
+ // F1: a resolved address is used only when HookResolver says pattern-unique AND the pattern is unique.
+ Case("Pin_UniquePatternOnly");
+ const string uniqueLine = "r.Success && r.Source == HookResolver.ResolveSource.PatternScan && r.Detail == \"pattern-unique\"";
+ const string countLine = "&& IsUnique(text.Bytes, pattern) ? r.Address : IntPtr.Zero;";
+ static bool UniquePin(string s, string u, string c) => HasLine(s, u) && HasLine(s, c);
+ Check(HasLine(res, "detail = \"pattern-unique\";"), "HookResolver's own word for a single match is pattern-unique");
+ Check(!HasLine(res.Replace("detail = \"pattern-unique\";", "detail = \"unique\";"), "detail = \"pattern-unique\";"), "mutation: another word fails that pin");
+ Check(UniquePin(opt, uniqueLine, countLine), "AcCharacterOptions takes pattern-unique only, and counts the matches itself");
+ Check(!UniquePin(opt.Replace(" && r.Detail == \"pattern-unique\"", ""), uniqueLine, countLine), "mutation: without the Detail check the pin fails");
+ Check(!UniquePin(opt.Replace("&& IsUnique(text.Bytes, pattern) ", ""), uniqueLine, countLine), "mutation: without the count the pin fails");
+
+ // F8: OnSend keeps the typed line in history and rewrites after it.
+ Case("Pin_OnSendRewritesAfterHistory");
+ const string rewriteLine = "string? rewritten = ChatNetwork.Rewrite(text, network.Command, ChatNetwork.OnOrUnknown);";
+ static bool RewritePin(string body, string rw) => LineAt(body, rw) > LastLineAt(body, "AddHistory(text);") && LastLineAt(body, "AddHistory(text);") >= 0;
+ string? onSend = MethodBody(data, "private static unsafe void OnSend()");
+ Check(onSend != null && RewritePin(onSend, rewriteLine), "OnSend: Rewrite comes after the last AddHistory(text)");
+ if (onSend != null)
+ {
+ Check(!RewritePin(onSend.Replace(rewriteLine, "// " + rewriteLine), rewriteLine), "mutation: Rewrite commented out fails");
+ Check(!RewritePin(onSend + "\n AddHistory(text);\n", rewriteLine), "mutation: an AddHistory after the Rewrite fails");
+ }
+
+ // F8: the poll path runs the network status check, before the lines are published.
+ Case("Pin_PollRunsNetworkLines");
+ const string pumpLine = "try { ChatModel.PumpNetworkLines(added); }";
+ static bool PollPin(string body, string p) => LineAt(body, p) >= 0 && LineAt(body, p) < body.IndexOf("Publish(ChatHistory.Merge(", StringComparison.Ordinal);
+ string? poll = MethodBody(data, "private void PollLines()");
+ Check(poll != null && PollPin(poll, pumpLine), "PollLines calls PumpNetworkLines before publishing");
+ if (poll != null)
+ {
+ Check(!PollPin(poll.Replace(pumpLine, "// " + pumpLine), pumpLine), "mutation: commented out fails");
+ const string publishLine = "Publish(ChatHistory.Merge(old, added, maxLines));";
+ Check(LineAt(poll, publishLine) >= 0, "the publish line the mutation moves it after is there");
+ Check(!PollPin(poll.Replace(pumpLine, "").Replace(publishLine, publishLine + "\n " + pumpLine), pumpLine),
+ "mutation: moved after the publish fails");
+ }
+
+ // F8: login and logout reset the network session, hooked at init.
+ Case("Pin_SessionResets");
+ const string loginLine = "LoginLifecycleHooks.LoginComplete += ChatNetwork.ResetSession;";
+ const string logoutLine = "LogoutLifecycleHooks.LogoutComplete += ChatNetwork.ResetSession;";
+ string? hook = MethodBody(data, "private static void HookNetworkSession()");
+ string? install = MethodBody(data, "public static void InstallInput()");
+ static bool SessionPin(string? h, string? i, string a, string b) => h != null && i != null && HasLine(h, a) && HasLine(h, b) && HasLine(i, "HookNetworkSession();");
+ Check(SessionPin(hook, install, loginLine, logoutLine), "HookNetworkSession adds both resets, and InstallInput calls it");
+ Check(!SessionPin(hook?.Replace(loginLine, "// " + loginLine), install, loginLine, logoutLine), "mutation: no login reset fails");
+ Check(!SessionPin(hook?.Replace(logoutLine, "// " + logoutLine), install, loginLine, logoutLine), "mutation: no logout reset fails");
+ Check(!SessionPin(hook, install?.Replace("HookNetworkSession();", "// HookNetworkSession();"), loginLine, logoutLine), "mutation: never hooked fails");
+
+ // F8: TryGet and TrySet check the module (thread, login, vtable) before any call into AC.
+ Case("Pin_ModuleBeforeEveryCall");
+ const string moduleLine = "IntPtr module = Module(out why);";
+ const string guardLine = "if (module == IntPtr.Zero) return false;";
+ static bool ModulePin(string? body)
+ {
+ if (body == null) return false;
+ int m = LineAt(body, "IntPtr module = Module(out why);"), g = LineAt(body, "if (module == IntPtr.Zero) return false;");
+ if (m < 0 || g < m) return false;
+ // Any use of a delegate field (a call, or taking it into a local that is called) is after the guard.
+ foreach (string field in new[] { "_getOption", "_setOption" })
+ for (int at = body.IndexOf(field, StringComparison.Ordinal); at >= 0; at = body.IndexOf(field, at + 1, StringComparison.Ordinal))
+ if (at < g) return false;
+ return body.Contains("_getOption", StringComparison.Ordinal);
+ }
+ string? tryGet = MethodBody(opt, "public static bool TryGet(");
+ string? trySet = MethodBody(opt, "public static bool TrySet(");
+ Check(ModulePin(tryGet) && ModulePin(trySet), "TryGet and TrySet: Module() and its guard before every delegate call");
+ Check(trySet != null && trySet.Contains("_setOption)(", StringComparison.Ordinal) && trySet.Contains("_getOption;", StringComparison.Ordinal),
+ "TrySet does use both delegates (the pin covers them)");
+ Check(!ModulePin(tryGet?.Replace(moduleLine, "// " + moduleLine)), "mutation: TryGet without Module() fails");
+ Check(!ModulePin(trySet?.Replace(guardLine, "// " + guardLine)), "mutation: TrySet without the guard fails");
+ Check(!ModulePin(trySet?.Replace(moduleLine, "((delegate* unmanaged[Thiscall])_setOption)(IntPtr.Zero, 0, 0);\n " + moduleLine)),
+ "mutation: a call before Module() fails");
+ }
+
+ private static string? RepoFile(params string[] parts)
+ {
+ for (string? dir = AppContext.BaseDirectory; dir != null; dir = Path.GetDirectoryName(dir))
+ {
+ string candidate = Path.Combine(new[] { dir }.Concat(parts).ToArray());
+ if (File.Exists(candidate)) return candidate;
+ }
+ return null;
+ }
+
+ /// The body (from its opening brace to the matching close) of the member whose declaration starts with .
+ private static string? MethodBody(string src, string head)
+ {
+ int at = src.IndexOf(head, StringComparison.Ordinal);
+ if (at < 0) return null;
+ int open = src.IndexOf('{', at);
+ if (open < 0) return null;
+ int depth = 0;
+ for (int i = open; i < src.Length; i++)
+ {
+ if (src[i] == '{') depth++;
+ else if (src[i] == '}' && --depth == 0) return src[open..(i + 1)];
+ }
+ return null;
+ }
+
+ /// The offset of the first line whose trimmed text is exactly (a commented-out line is not it), or -1.
+ private static int LineAt(string text, string line)
+ {
+ int offset = 0;
+ foreach (string l in text.Split('\n'))
+ {
+ if (l.Trim() == line) return offset;
+ offset += l.Length + 1;
+ }
+ return -1;
+ }
+
+ private static int LastLineAt(string text, string line)
+ {
+ int offset = 0, last = -1;
+ foreach (string l in text.Split('\n'))
+ {
+ if (l.Trim() == line) last = offset;
+ offset += l.Length + 1;
+ }
+ return last;
+ }
+
+ private static bool HasLine(string text, string line)
+ {
+ foreach (string l in text.Split('\n'))
+ if (l.Trim() == line) return true;
+ return false;
+ }
+
+ // 2026-11-15: pinned tab bookkeeping (ChatPins), pure.
private static void PinBookkeeping()
{
Case("Toggle_AddsAtEndAndRemoves");