using System.Diagnostics;
using System.Numerics;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.RegularExpressions;
using ImGuiNET;
using RynthCore.Engine.UI.Data;
namespace ChatHistoryBench;
///
/// What a longer chat history costs, and whether ImGui scrolls the way ChatFace's
/// follow fix needs (see the csproj header). Prints tables; exit 1 if a scroll check fails.
///
internal static unsafe class Program
{
private static readonly int[] Sizes = { 500, 2000, 5000, 10000 };
private static int _checks, _failed;
private static int Main(string[] args)
{
Console.WriteLine($"ChatHistoryBench: {(Environment.Is64BitProcess ? "x64" : "x86")} process, .NET {Environment.Version}, {Environment.ProcessorCount} cores");
#if !HAVE_RYNTHCHAT
Console.WriteLine("RynthSuite checkout not found: plugin-side numbers skipped.");
#endif
InitImGui();
ScrollChecks();
HistoryChecks();
AutomatedChecks();
Memory();
Cpu();
Console.WriteLine();
Console.WriteLine($"Checks: {_checks - _failed}/{_checks} passed.");
return _failed == 0 ? 0 : 1;
}
// ── Realistic lines ──────────────────────────────────────────────────
private static readonly string[] Names = { "Drakkon", "Aja", "Bob Smith", "Lucy", "Malar Zhavik", "Tusker Slayer", "Kel of the Vale" };
private static readonly string[] Monsters = { "Tusker Guard", "Olthoi Swarm Nymph", "Mattekar", "Banderling Raider", "Shadow Child", "Drudge Ravener" };
private static readonly string[] Spells = { "Incantation of Strength Self", "Aura of Defender", "Focus Self VII", "Incantation of Blade Protection Self" };
private static readonly string[] Words = (
"anyone selling mana stones need buffs at the portal north of town lfg for the olthoi dungeon " +
"key drop rate is terrible tonight wts pyreal motes lol thanks for the fellow invite where is " +
"the lifestone heading to the hub in a minute who has a legendary key ok see you there").Split(' ');
/// One AC chat line: (text as AC prints it, ChatMessageType), 60-150 characters.
private static (string Text, int Type) MakeLine(Random r)
{
int target = r.Next(60, 151);
string name = Names[r.Next(Names.Length)], mob = Monsters[r.Next(Monsters.Length)];
int k = r.Next(100);
(string head, int type, bool speech) = k switch
{
< 20 => ($"You hit {mob} for {r.Next(5, 400)} points of slashing damage!", 0x16, false),
< 35 => ($"{mob} grazes your foot for {r.Next(1, 90)} points of bludgeoning damage!", 0x15, false),
< 45 => ($"You cast {Spells[r.Next(Spells.Length)]} on yourself, refreshing {Spells[r.Next(Spells.Length)]}", 0x07, false),
< 50 => ("The spell consumed the following components: Prismatic Taper", 0x07, false),
< 62 => ($"[{(r.Next(2) == 0 ? "General" : "Trade")}] {name} says, \"", 0x08, true),
< 72 => ($"{name} says, \"", 0x02, true),
< 77 => ($"{name} tells you, \"", 0x03, true),
< 82 => ($"[Fellowship] {name} says, \"", 0x13, true),
< 88 => ($"[RynthAi] Meta state Combat -> Loot ({r.Next(1, 30)} corpses)", 0x00, false),
< 92 => ("You're too busy!", 0x1A, false),
_ => ($"You've earned {r.Next(1000, 900000)} experience.", 0x0D, false),
};
var sb = new System.Text.StringBuilder(head, 160);
if (speech)
{
if (r.Next(12) == 0) sb.Append("Drakkon "); // someone mentions you now and then
while (sb.Length < target - 1) sb.Append(Words[r.Next(Words.Length)]).Append(' ');
sb.Length = Math.Min(sb.Length, target - 1);
sb.Append('"');
}
else
{
while (sb.Length < target) sb.Append(sb.Length == head.Length ? " (" : " ").Append(Words[r.Next(Words.Length)]);
if (sb.Length > target) sb.Length = target;
}
return (sb.ToString(), type);
}
// ── The engine side, as ChatSource does it ───────────────────────────
private static ChatRouter MakeRouter()
{
ChatFilterRule Rule(ChatMatchMode mode, string pattern, ChatRuleAction action, string tab = "", string when = "",
ChatColorMode color = ChatColorMode.None)
{
var r = new ChatFilterRule { Mode = mode, Pattern = pattern, Action = action, Tab = tab, When = when, ColorMode = color };
r.Recompile();
return r;
}
// A rule set like a player's: hide spam, sort, copy tells, colour.
ChatFilterRule[] rules =
{
Rule(ChatMatchMode.Contains, "You're too busy!", ChatRuleAction.Hide),
Rule(ChatMatchMode.StartsWith, "The spell consumed the following components", ChatRuleAction.Hide),
Rule(ChatMatchMode.Regex, @"^\[RynthAi\]", ChatRuleAction.Move, "Bot"),
Rule(ChatMatchMode.Regex, @"tells you, """, ChatRuleAction.Copy, "Tells", color: ChatColorMode.Line),
Rule(ChatMatchMode.Regex, @"^\[(Trade|LFG)\]", ChatRuleAction.Move, "Trade"),
Rule(ChatMatchMode.Regex, @"^You cast .* on yourself", ChatRuleAction.Move, "Buffs", "type:7"),
Rule(ChatMatchMode.Regex, @"\b(Olthoi|Tusker)\b", ChatRuleAction.Color, color: ChatColorMode.Match),
Rule(ChatMatchMode.Contains, "Critical hit", ChatRuleAction.Color, color: ChatColorMode.Line),
};
var mention = new Regex(@"(?ChatSource.PollLines' parse + construct + route for one read (no AC-link stripping: no links here).
private static List ReadLines(string json, ChatRouter router)
{
RynthChatLineDto[]? dtos = JsonSerializer.Deserialize(json, RynthChatJsonContext.Default.RynthChatLineDtoArray);
var added = new List(dtos?.Length ?? 0);
foreach (RynthChatLineDto dto in dtos ?? Array.Empty())
{
var line = new ChatLine(_nextId++, dto.Ts ?? "", dto.Chan ?? "Other", dto.Type, dto.Sender, dto.Text ?? "") { Seq = dto.Seq };
line.Route = router.Evaluate(line, null);
added.Add(line);
}
return added;
}
#if HAVE_RYNTHCHAT
private static RynthCore.Plugin.RynthChat.ChatBuffer FilledPlugin(int n, Random r)
{
var b = new RynthCore.Plugin.RynthChat.ChatBuffer(n);
for (int i = 0; i < n; i++) { var (t, ty) = MakeLine(r); b.Add(t, ty); }
return b;
}
#endif
/// N engine lines, routed, built the way ChatSource builds them (from the plugin's JSON when it's here).
private static ChatLine[] EngineLines(int n, Random r, ChatRouter router)
{
#if HAVE_RYNTHCHAT
string json = FilledPlugin(n, r).BuildJson(0);
#else
var dtos = new RynthChatLineDto[n];
for (int i = 0; i < n; i++) { var (t, ty) = MakeLine(r); dtos[i] = new RynthChatLineDto { Seq = (ulong)i + 1, Ts = "12:34:56", Chan = "Combat", Type = ty, Text = t }; }
string json = JsonSerializer.Serialize(dtos, RynthChatJsonContext.Default.RynthChatLineDtoArray);
#endif
return ReadLines(json, router).ToArray();
}
// ── Memory ───────────────────────────────────────────────────────────
private static long Heap()
{
for (int i = 0; i < 3; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); }
return GC.GetTotalMemory(true);
}
/// Bytes held by what returns.
private static long Held(Func