From 3bbfe08ab104148d867ed1eef233085a4af757f7 Mon Sep 17 00:00:00 2001 From: Angel Mankel Date: Mon, 19 Oct 2026 18:19:14 -0700 Subject: [PATCH] feat(arena): BotArena for linux-x64 and win-x64 on the library The shims go; ArenaHost implements BotHost (stderr log, Microsoft.Data.Sqlite read-only, locale, the expansions' .cdb, bot.conf). EngineLibrary finds ygol-engine.dll / libygol-engine.so (env, the root's plugin folder, a built player, next to the exe) for both hosts. Same options and report. --host server is refused off Windows: on Linux the engine's server reads ./expansions and ./script, finds no cards, and every duel ends at turn 0. Co-Authored-By: Claude Opus 5.5 --- src/BotArena/ArenaHost.cs | 48 +++++++++++ src/BotArena/BotArena.csproj | 95 ++++----------------- src/BotArena/EngineLibrary.cs | 52 +++++++++++ src/BotArena/LocalHost.cs | 22 +---- src/BotArena/Program.cs | 9 +- src/BotArena/README.md | 109 +++++++++++------------- src/BotArena/Setup.cs | 16 ++-- src/BotArena/Shims/MDPro3.cs | 63 -------------- src/BotArena/Shims/MonoDataSqlite.cs | 22 ----- src/BotArena/Shims/UnityEngine.Debug.cs | 23 ----- src/BotArena/Worker.cs | 2 +- src/BotArena/YgoServer.cs | 30 ++----- 12 files changed, 187 insertions(+), 304 deletions(-) create mode 100644 src/BotArena/ArenaHost.cs create mode 100644 src/BotArena/EngineLibrary.cs delete mode 100644 src/BotArena/Shims/MDPro3.cs delete mode 100644 src/BotArena/Shims/MonoDataSqlite.cs delete mode 100644 src/BotArena/Shims/UnityEngine.Debug.cs diff --git a/src/BotArena/ArenaHost.cs b/src/BotArena/ArenaHost.cs new file mode 100644 index 0000000..65cbca4 --- /dev/null +++ b/src/BotArena/ArenaHost.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.IO; +using YGOLegacy.Bots; + +namespace YGOLegacy.Tools.BotArena +{ + /// + /// What the game gives the bots (YGOLegacy.Bots.BotHost), done here without Unity: the log, the card + /// databases (Microsoft.Data.Sqlite, read-only), the locale, the .cdb files from Expansions/*.ypk and the + /// locale's bot.conf. The deck limits stay the library's default (60 / 99 / 15): the arena has no + /// rulesets and no config.conf, so every deck gets the shipped Master caps. + /// + internal sealed class ArenaHost : IBotLog, ICardDatabase, IGameFiles, IBotConf + { + public static readonly ArenaHost Instance = new(); + + /// Where log lines go; the worker points this at its log (stderr). + public static Action Sink = s => Console.Error.WriteLine(s); + + public string Locale { get; set; } = "en-US"; + public List ZipCdbPaths = new(); + public readonly List Bots = new(); + + public static void Install() + { + BotHost.Log = Instance; + BotHost.Cards = Instance; + BotHost.Files = Instance; + BotHost.BotConf = Instance; + } + + public void Info(string message) => Sink?.Invoke(message ?? "null"); + public void Warning(string message) => Sink?.Invoke("[warn] " + message); + public void Error(string message) => Sink?.Invoke("[error] " + message); + + /// Read-only and shared: several worker processes open the same .cdb files at once. + public IDbConnection Connect(string path) + => new Microsoft.Data.Sqlite.SqliteConnection("Data Source=" + path + ";Mode=ReadOnly;Cache=Shared"); + + public IReadOnlyList ExpansionCardDatabases() => ZipCdbPaths; + + public IReadOnlyList Entries() => Bots; + + public void Reload() { } + } +} diff --git a/src/BotArena/BotArena.csproj b/src/BotArena/BotArena.csproj index 5d430e8..9cdc9a2 100644 --- a/src/BotArena/BotArena.csproj +++ b/src/BotArena/BotArena.csproj @@ -1,101 +1,38 @@ - + - + Exe net8.0 - win-x64 - false + linux-x64;win-x64 BotArena YGOLegacy.Tools.BotArena YGOLegacy.Tools.BotArena.Program - - disable - disable latest true - true - - $(DefineConstants);YGOL_STANDALONE - - $(NoWarn);CS0108;CS0114;CS0162;CS0164;CS0168;CS0169;CS0219;CS0414;CS0618;CS0649;CS0659;CS0661;CS1522;CS1570;CS1572;CS1573;CS1587;CS1591;CS8981;SYSLIB0011;CA1416 - false - en + $(BotsVersion) + $(NoWarn);CS0618;CA1416 + - - + - ..\..\Assets\Plugins\Managed\YGOLegacy.Engine.dll + $(EngineDir)YGOLegacy.Engine.dll - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + diff --git a/src/BotArena/EngineLibrary.cs b/src/BotArena/EngineLibrary.cs new file mode 100644 index 0000000..cc34b8e --- /dev/null +++ b/src/BotArena/EngineLibrary.cs @@ -0,0 +1,52 @@ +using System; +using System.IO; +using System.Runtime.InteropServices; +using YGOLegacy.Engine; + +namespace YGOLegacy.Tools.BotArena +{ + /// + /// The engine's native library: ygol-engine.dll on Windows, libygol-engine.so on Linux, the + /// release engine.json pins. Found in this order: $YGOL_ENGINE_DLL, the Unity project's plugin + /// folder under --root, a built player's plugin folder, next to this exe (where the release puts it). + /// + internal static class EngineLibrary + { + private static string path; + + public static string FileName => OperatingSystem.IsWindows() ? "ygol-engine.dll" : "libygol-engine.so"; + + public static string Path => path; + + /// Find the library and teach the runtime where it is. Idempotent. + public static string Locate(string root) + { + if (path != null) return path; + var candidates = OperatingSystem.IsWindows() + ? new[] + { + Environment.GetEnvironmentVariable("YGOL_ENGINE_DLL"), + System.IO.Path.Combine(root, "Assets", "Plugins", "Windows", FileName), + System.IO.Path.Combine(root, "YGOLegacy_Data", "Plugins", "x86_64", FileName), + System.IO.Path.Combine(root, "MDPro3_Data", "Plugins", "x86_64", FileName), + System.IO.Path.Combine(AppContext.BaseDirectory, FileName), + } + : new[] + { + Environment.GetEnvironmentVariable("YGOL_ENGINE_DLL"), + System.IO.Path.Combine(root, "Assets", "Plugins", "Linux", FileName), + System.IO.Path.Combine(root, "YGOLegacy_Data", "Plugins", FileName), + System.IO.Path.Combine(AppContext.BaseDirectory, FileName), + }; + foreach (var c in candidates) + if (!string.IsNullOrEmpty(c) && File.Exists(c)) { path = System.IO.Path.GetFullPath(c); break; } + if (path == null) + throw new FileNotFoundException(FileName + " not found (looked in $YGOL_ENGINE_DLL, the plugin folders under --root and next to the exe)"); + + var found = path; + NativeLibrary.SetDllImportResolver(typeof(EngineApi).Assembly, (name, asm, searchPath) => + name == "ygol-engine" ? NativeLibrary.Load(found) : IntPtr.Zero); + return path; + } + } +} diff --git a/src/BotArena/LocalHost.cs b/src/BotArena/LocalHost.cs index 27738f7..7a3683c 100644 --- a/src/BotArena/LocalHost.cs +++ b/src/BotArena/LocalHost.cs @@ -2,7 +2,6 @@ using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; -using System.Runtime.InteropServices; using YGOLegacy.Bot; using YGOLegacy.Engine; using YGOSharp.OCGWrapper; @@ -39,7 +38,7 @@ namespace YGOLegacy.Tools.BotArena private static string root; /// - /// Point the runtime at ygol-engine.dll and install the process-global card + /// Point the runtime at the engine library and install the process-global card /// and script readers. Idempotent; call once per worker. /// public static void Install(string gameRoot) @@ -47,9 +46,7 @@ namespace YGOLegacy.Tools.BotArena if (installed) return; root = gameRoot; - var dll = LocateCore(gameRoot); - NativeLibrary.SetDllImportResolver(typeof(EngineApi).Assembly, (name, asm, path) => - name == "ygol-engine" ? NativeLibrary.Load(dll) : IntPtr.Zero); + var dll = EngineLibrary.Locate(gameRoot); IndexScriptArchives(gameRoot); LocalDuelHost.InstallReaders(ReadCard, ReadScript); @@ -57,21 +54,6 @@ namespace YGOLegacy.Tools.BotArena Worker.Log("local host: engine=" + dll + ", script archives=" + archives.Count); } - private static string LocateCore(string gameRoot) - { - var candidates = new[] - { - Environment.GetEnvironmentVariable("YGOL_ENGINE_DLL"), - Path.Combine(gameRoot, "Assets", "Plugins", "Windows", "ygol-engine.dll"), - Path.Combine(gameRoot, "YGOLegacy_Data", "Plugins", "x86_64", "ygol-engine.dll"), - Path.Combine(gameRoot, "MDPro3_Data", "Plugins", "x86_64", "ygol-engine.dll"), - Path.Combine(AppContext.BaseDirectory, "ygol-engine.dll"), - }; - foreach (var c in candidates) - if (!string.IsNullOrEmpty(c) && File.Exists(c)) return Path.GetFullPath(c); - throw new FileNotFoundException("ygol-engine.dll not found (looked under --root in Assets/Plugins/Windows, a built player's Plugins/x86_64, next to the exe, and $YGOL_ENGINE_DLL)"); - } - // ------------------------------------------------------------------ // Cards // ------------------------------------------------------------------ diff --git a/src/BotArena/Program.cs b/src/BotArena/Program.cs index 96df01c..267a7f1 100644 --- a/src/BotArena/Program.cs +++ b/src/BotArena/Program.cs @@ -15,8 +15,8 @@ namespace YGOLegacy.Tools.BotArena { /// /// Standalone, parallel Bot Arena (TICKET-035). No Unity in the loop: the - /// exe compiles the in-tree WindBot + the fork's brain, loads the engine - /// (ygol-engine.dll) itself and runs N bot-vs-bot duels across `--parallel` worker PROCESSES + /// exe runs the YGOLegacy.Bots library (WindBot + the fork's brain), loads the engine + /// (ygol-engine.dll / libygol-engine.so) itself and runs N bot-vs-bot duels across `--parallel` worker PROCESSES /// (WindBot.Config is process-global, so one duel at a time per process). /// /// Two modes in one exe: @@ -465,7 +465,7 @@ Options: --insightA duel state bus insight for seat A: none | hand | full (TICKET-042). Overrides that deck brain's `insight` knob. Default: the knob (none) --insightB same for seat B - --host local|server in-process core (default) or the engine's server over TCP (TICKET-045) + --host local|server in-process core (default) or the engine's server over TCP (TICKET-045; Windows only) --knobsA per-seat SmartExecutor knob overrides for seat A, applied ON TOP of the deck brain's knobs: ""name=value,name=value"" (e.g. ""lookahead=8,lookaheadTurns=6""). Setting `lookahead` above 0 also installs the arena's perfect-information @@ -604,6 +604,9 @@ Exit codes: 0 = at least one duel played, 1 = none played, 2 = bad arguments."; o.root = Path.GetFullPath(o.root); if (!Directory.Exists(o.root)) throw new ArgumentException("--root does not exist: " + o.root); if (o.hostMode != "local" && o.hostMode != "server") throw new ArgumentException("--host expects local|server, got '" + o.hostMode + "'"); + // The engine's server finds its cards and scripts under names a Windows game root matches only because + // the file system ignores case (./expansions, ./script); on Linux its duels end at turn 0, unplayed. + if (o.hostMode == "server" && !OperatingSystem.IsWindows()) throw new ArgumentException("--host server runs on Windows only; use --host local"); if (o.worker) { o.port = o.portBase; diff --git a/src/BotArena/README.md b/src/BotArena/README.md index 1456fa2..d860555 100644 --- a/src/BotArena/README.md +++ b/src/BotArena/README.md @@ -1,16 +1,18 @@ # BotArena — standalone, parallel bot-vs-bot duels (TICKET-035) Runs hundreds (thousands) of WindBot-vs-WindBot duels from a terminal with **no -Unity in the loop**, using exactly the code the game ships: the in-tree WindBot, -the fork's SmartExecutor brain, the character registry and the game's own -`ocgcore.dll`. Same JSON report as the in-editor Bot Arena (TICKET-030), so -anything that reads `Data/BotArena/*.json` reads either. +Unity in the loop**, using exactly the code the game ships: the `YGOLegacy.Bots` +library (WindBot, the fork's SmartExecutor brain, the character registry) and +the engine release `engine.json` pins. Same JSON report as the in-editor Bot +Arena (TICKET-030), so anything that reads `Data/BotArena/*.json` reads either. +Linux (`linux-x64`) and Windows (`win-x64`). Two duel hosts, `--host local` (the default) and `--host server`: | | `local` (TICKET-045) | `server` (TICKET-035) | |---|---|---| -| what runs the duel | `YGOLegacy.Bot.LocalDuelHost` — ocgcore.dll driven from this process | `ygoserver.dll`, one room per worker | +| what runs the duel | `YGOLegacy.Bot.LocalDuelHost` — the engine library driven from this process | the engine's `start_server`, one room per worker | +| platforms | Linux and Windows | **Windows only** (on Linux the server finds no cards: it reads `./expansions` and `./script`, which a Windows game root matches only because its file system ignores case; the arena refuses it) | | transport | none: a loopback seam into `BinaryClient` | TCP on 127.0.0.1 | | threads per worker | one (host + both bots + both brains) | four (server, two bots, the worker) | | 1000 Weevil duels, 8 workers | **~20 s** (10–40 ms per duel) | ~4 min (~1.6 s per duel) | @@ -25,15 +27,11 @@ their sockets — none of which the in-process host has. ## Build -``` -dotnet build Tools/BotArena # dev machine or the CI runner (dotnet 8 SDK) -``` - -Output: `Tools/BotArena/bin/Debug/net8.0/win-x64/BotArena.exe` (gitignored). -Windows only, like the game (ygoserver.dll is a Windows plugin). - -Sources are **linked**, not copied — see `BotArena.csproj`. There is nothing -to sync: change `SmartExecutor.cs` in the Unity project, rebuild, run. +The repo's `Dockerfile` publishes both builds self-contained (`docker build --target dist -o out .` -> +`out/bot-arena-linux-x64/BotArena`, `out/bot-arena-win-x64/BotArena.exe`), each with the pinned engine's native +library and C# binding next to the exe. With a dotnet 8 SDK: `build/fetch-engine.sh`, then +`dotnet publish src/BotArena -c Release -r win-x64 --self-contained` (or `linux-x64`). The release ships both +(`bot-arena-linux-x64.tar.gz`, `bot-arena-win-x64.zip`). ## Run @@ -44,10 +42,12 @@ BotArena --deckA "Duelist Kingdom/Weevil Underwood DK" ^ --out C:\tmp\arena.json ``` -Run it from the repo root, or pass `--root ` (`Deck/`, `Data/`, -`Expansions/`, `Assets/Plugins/Windows/ygol-engine.dll` are resolved under it; -the working directory of every worker IS the root, because ygoserver reads -`./expansions`, `./script` and writes `./replay`, `./error.log` there). +Run it from a game root (the Unity project or a built game), or pass `--root `: `Deck/`, `Data/` and +`Expansions/` are resolved under it, and the working directory of every worker IS the root (the server reads +`./expansions`, `./script` and writes `./replay`, `./error.log` there). The root must be writable: the report +goes to `Data/BotArena/`. The engine library is the first found of `$YGOL_ENGINE_DLL`, the root's +`Assets/Plugins/Windows/ygol-engine.dll` (Linux: `Assets/Plugins/Linux/libygol-engine.so`), a built player's +plugin folder, and the copy next to the exe. | Option | Meaning | |---|---| @@ -59,11 +59,11 @@ the working directory of every worker IS the root, because ygoserver reads | `--timeout 300` | per-duel timeout in seconds | | `--out file.json` | extra copy of the report (the canonical one always lands in `Data/BotArena/`) | | `--replays dir` | save every duel's `.yrp` as `duel-0001.yrp`, … **`--host server` only** — the in-process host is not a ygoserver and never sends STOC_REPLAY, so a `local` run warns and writes nothing. | -| `--journal dir` | SmartExecutor decision journal (TICKET-036): `duel-0001-A.jsonl` per **Smart** seat (Lucky seats write nothing) + `run.json` (the run's config and seat commands). Feed the dir to `python .claude/skills/bot-brain/blunders.py `. Kinds are listed at the top of the journal region in `SmartExecutor.cs`; 2026-08-18 added `flipHeld` (a Flip Summon the executor chose NOT to take, with its reason — deduped per card + turn) and the `positionWhy: "flip default set"` value on `summon`/`set` lines, plus `positionWhy: "flip from hand beats weak body"` when a weak face-up summon was held so a FLIP monster could be Set instead. | +| `--journal dir` | SmartExecutor decision journal (TICKET-036): `duel-0001-A.jsonl` per **Smart** seat (Lucky seats write nothing) + `run.json` (the run's config and seat commands). Feed the dir to the Unity repo's `python .claude/skills/bot-brain/blunders.py `. Kinds are listed at the top of the journal region in `SmartExecutor.cs`; 2026-08-18 added `flipHeld` (a Flip Summon the executor chose NOT to take, with its reason — deduped per card + turn) and the `positionWhy: "flip default set"` value on `summon`/`set` lines, plus `positionWhy: "flip from hand beats weak body"` when a weak face-up summon was held so a FLIP monster could be Set instead. | | `--port 7920` | first server port; worker *k* starts at `port + 4k` and takes the next free one (`--host server` only) | | `--locale en-US` | `Data/locales//` for `cards.cdb` and `bot.conf` | | `--knobsA/--knobsB "name=value,..."` | per-seat SmartExecutor knob overrides, applied ON TOP of that deck brain's knobs (and the group's) — e.g. `--knobsA "lookahead=8,lookaheadTurns=6"`. Lets one deck be measured at two settings without editing `brain.json`. Setting `lookahead` above 0 also installs the perfect-information rollout oracle for that seat (TICKET-050; `--host local` only). | -| `--host local\|server` | which duel host plays the duels. `local` (default) = ocgcore in-process (TICKET-045); `server` = ygoserver.dll over a TCP loopback, kept for A/B. | +| `--host local\|server` | which duel host plays the duels. `local` (default) = the engine's core in-process (TICKET-045); `server` = the engine's server over a TCP loopback, kept for A/B, Windows only. | | `--insightA/--insightB ` | force that seat's duel-state-bus insight (TICKET-042), overriding the deck brain's `insight` knob. Default: the knob (none). Recorded in the report's `config.insightA/insightB`; at `hand` or above the journal's `turn` lines gain `enemyHandKnown` (the enemy's real hand ids). Both bots of a duel run in this process, so each mirrors the other's stream. | | `--verbose` | `[YGOL bot]` decision logging on for every Smart seat (sets `SmartExecutor.Verbose`; no `verbose: 1` knob needed — the executor is otherwise muted for the run). Lines land in the worker logs. | @@ -85,13 +85,13 @@ schema exactly (`config`, `nameA/B`, `commandA/B`, `winsA/B`, `draws`, `wallClockSeconds`. `totalSeconds` is the run's wall clock too; `durationSeconds` per duel is that duel's own clock (server start → teardown). The model and the helpers that fill it (`Summary`, `SeatCommand`, `Resolve`, -`Tally`) are ONE file shared with the game: -`Assets/YGOLegacy/Scripts/Bot/ArenaReport.cs`. +`Tally`) are ONE file of the library, shared with the game's in-editor arena: +`src/YGOLegacy.Bots/Bot/ArenaReport.cs`. ## How it works ``` -BotArena.exe (parent) +BotArena (parent) ├─ validates decks the way WindBot's Program.ReadFile resolves DeckFile= ├─ CharacterRegistry.LoadFromDisk + Data/locales//bot.conf → BotRoster.ForDeck │ → seat names " A"/" B" + WindBot commands (ArenaReport.SeatCommand) @@ -101,11 +101,11 @@ BotArena.exe (parent) ├─ a dead worker's duel is re-queued once and a replacement worker is started └─ writes the report, prints the summary, kills what is left (try/finally) -BotArena.exe --worker k (one duel at a time) +BotArena --worker k (one duel at a time) ├─ cwd = root - ├─ once: characters, bot.conf, WindBot.Program.InitDatas (cards.cdb + every .cdb - │ inside Expansions/*.ypk, extracted to %TEMP%/YGOLBotArena/cdb/, + Expansions/*.cdb), - │ then per --host: LocalHost.Install (ocgcore.dll + readers) or YgoServer.Locate + ├─ once: ArenaHost.Install (BotHost), characters, bot.conf, WindBot.Program.InitDatas + │ (cards.cdb + every .cdb inside Expansions/*.ypk, extracted to /YGOLBotArena/cdb/, + │ + Expansions/*.cdb), then per --host: LocalHost.Install (engine + readers) or YgoServer.Locate └─ per duel: Worker.RunOneLocal / Worker.RunOneServer (below) → ArenaReport.Resolve → {"type":"duel","record":{…}} on stdout ``` @@ -166,13 +166,12 @@ normal measurement run allocates nothing extra and behaves byte-for-byte as befo ### The in-process host (TICKET-045) -`YGOLegacy.Bot.LocalDuelHost` (`Assets/YGOLegacy/Scripts/Bot/`, Unity-free, also -compiled by the game) is ygoserver's duel loop rewritten in C# for exactly two -seats and one duel, and `LoopbackBotSeat` is the WindBot adapter. Both are -linked, not copied. +`YGOLegacy.Bot.LocalDuelHost` (`src/YGOLegacy.Bots/Bot/`, Unity-free, also +run by the game) is ygoserver's duel loop rewritten in C# for exactly two +seats and one duel, and `LoopbackBotSeat` is the WindBot adapter. * **Where the byte layouts come from.** `Percy.Ygopro.Analyse` - (`Assets/Scripts/MDPro3/Duel/CoreWrapper.cs`) is the fork's own single-seat + (the game's `Assets/Scripts/MDPro3/Duel/CoreWrapper.cs`) is the fork's own single-seat host and already encodes the length of every `MSG_*` and how to blank hidden information; `LocalDuelHost.Scan` is that switch, message for message, plus the ones a single-seat client never sees. An unknown message id throws rather @@ -215,7 +214,7 @@ the executor list's first preference" to "enumerate the executor's top `lookaheadCandidates` (default 4) preferences, play each of them out `N` times, and blend the rollout win rate into the choice". It is **off by default and off in the game**: the knob does nothing without an `ILookaheadOracle`, and the only -implementation of that interface is `Tools/BotArena/ReplayOracle.cs`. +implementation of that interface is `src/BotArena/ReplayOracle.cs`. How a rollout is possible at all: ocgcore cannot clone a live duel, but this arena's per-duel seed drives BOTH `create_duel` and the host's own deck shuffle, @@ -270,30 +269,18 @@ differing**. * Card databases: WindBot's `InitDatas` is run ONCE per worker, not once per bot as `WindBot.Program.Main` would. -## Shims and exclusions (`Shims/`, `BotArena.csproj`) +## What the arena gives the bots (`ArenaHost.cs`) -| Shim | Stands in for | Why | -|---|---|---| -| `Shims/UnityEngine.Debug.cs` | `UnityEngine.Debug.Log/LogWarning/LogError/LogException` | SmartExecutor and CharacterRegistry log through it. Routed to stderr (→ worker log). | -| `Shims/MDPro3.cs` — `MDPro3.Program.PATH_EXPANSIONS`, `MDPro3.IO.ResourceManager.GetAllCdbInZipPaths`, `MDPro3.Utility.Language.GetConfig`, `MDPro3.Servant.SoloSelector.{BotInfo,bots}` | the four MDPro3 statics `WindBot/Program.cs` (InitDatas) and `BotRoster.cs` (Dovphin's bot.conf line) touch | data holders the tool fills in; the game's classes drag in Unity | -| `Shims/MonoDataSqlite.cs` — `Mono.Data.Sqlite.SqliteConnection/SqliteCommand` | Unity's Mono.Data.Sqlite used by `NamedCardsManager`/`CardsManager` | thin subclasses of `Microsoft.Data.Sqlite` (NuGet), opened read-only/shared | -| NuGet `Newtonsoft.Json` | Unity's Newtonsoft package | `Character.cs`, `BrainRules.cs`, the report | -| define `YGOL_STANDALONE` | — | `CharacterRegistry.cs` compiles its UniTask surface (`Loaded`, `Init`) out; the tool uses `LoadFromDisk` | +The library reaches its host only through `YGOLegacy.Bots.BotHost` (the repo README has the contract). +`ArenaHost` is the arena's side of it: -Excluded from the link, each documented in the csproj: `Windbot/BotWrapper.cs` -(unused upstream stub with a second `Main`); YGOSharp `Api.cs`/`Duel.cs`/ -`MtRandom.cs` and the `YGOSharp/` + `Async*`/`NetworkServer` files (ocgcore -P/Invoke and the server side — WindBot only needs the client, the card -managers and the enums); `Bot/BotArena.cs` (the editor runner: UniTask, -OcgCore, TcpHelper). - -Shared-source changes made for this tool (all still compile in Unity): -`ArenaReport.cs` (new, model + helpers extracted from `BotArena.cs`, plus -`ArenaConfig.hostMode` and `DuelRecord.coreMs`), -`CharacterRegistry.LoadFromDisk` + `#if !YGOL_STANDALONE`, the `[YGOL]` -`GameBehavior.YGOL_Replay` event, and (TICKET-045) the loopback seams -`BinaryClient.{YGOL_SendHook,YGOL_Inject,YGOL_MarkConnected}` + -`GameClient.{YGOL_StartLoopback,YGOL_Receive}`. +| `BotHost.` | The arena | +|---|---| +| `Log` | stderr, which the parent writes to the worker log | +| `Cards` | `Microsoft.Data.Sqlite`, read-only and shared (several workers open the same `.cdb`) | +| `Files` | `--locale`; the `.cdb` files of `Expansions/*.ypk`, extracted by `Setup.ExtractZipCdbs` | +| `BotConf` | `Data/locales//bot.conf`, parsed by `Setup.ReadBots` (the game's reader, minus the deck covers) | +| `DeckLimits` | the library default, 60 / 99 / 15: the arena has no rulesets and no `config.conf` | ## Caveats @@ -312,7 +299,7 @@ Shared-source changes made for this tool (all still compile in Unity): **One known exception, and it is not the seeding.** `Zexal/Kite Tenjo Zxl` diverges in 3–5 duels per 500 (~0.8 %), at `--parallel 1` as much as at `--parallel 4`, so it is not scheduling and not cross-duel leakage: it is - address-space dependent behaviour below us (ocgcore.dll iterates some + address-space dependent behaviour below us (the engine's core iterates some containers of pointers, and heap addresses move with ASLR). The same deck is the only one of the seven that also throws a `NullReferenceException` mid-duel (4 duels per 500) — the errored duel indices ARE stable across runs, so the @@ -327,7 +314,7 @@ Shared-source changes made for this tool (all still compile in Unity): quote the pooled figure (sum `winsA` and `completed` across the reports); before the fix the same command line gave **63.0 % and 68.0 %** on Weevil DK. `--seed 0` pins nothing and is not repeatable, as before. `--host server` is - never repeatable: `ygoserver.dll` shuffles the decks itself with a seed this + never repeatable: the engine's server shuffles the decks itself with a seed this process cannot reach (the per-duel `Program.Rand` reseed still happens there, so at least no state leaks from the previous duel). * **A duel that ends in `error` is not measured — check `errors` before trusting a @@ -348,10 +335,10 @@ Shared-source changes made for this tool (all still compile in Unity): **`Orichalcos/Valon ORI` hits this in 171 of 200 duels** (measured 2026-08-16), so that deck cannot currently be measured at all. Not diagnosed; the first step is a `--verbose` run of one failing duel index. -* `Deck/`, `Expansions/`, `Puzzle/` are junctions into the Syncthing share — - the tool only READS them. Reports go to `Data/BotArena/`, replays wherever - `--replays` says, the cdb cache to `%TEMP%`. -* ygoserver.dll writes `error.log` and `replay/` in the root, as the game does +* The tool only READS `Deck/`, `Expansions/`, `Puzzle/` (on a designer's machine, + junctions into the Syncthing share). Reports go to `Data/BotArena/`, replays + wherever `--replays` says, the cdb cache to the temp folder. +* The engine's server writes `error.log` and `replay/` in the root, as the game does (`--host server` only; the in-process host writes nothing outside `Data/BotArena/`). * Both hosts use the same process-global statics, so it is still ONE duel per diff --git a/src/BotArena/Setup.cs b/src/BotArena/Setup.cs index 577e7c0..5eff35f 100644 --- a/src/BotArena/Setup.cs +++ b/src/BotArena/Setup.cs @@ -2,7 +2,7 @@ using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; -using MDPro3.Servant; +using YGOLegacy.Bots; using YGOLegacy.Characters; namespace YGOLegacy.Tools.BotArena @@ -18,7 +18,8 @@ namespace YGOLegacy.Tools.BotArena /// Dovphin line. Everything relative to the current directory (= root). public static void LoadGameData(Options o) { - MDPro3.Utility.Language.Current = o.locale; + ArenaHost.Install(); + ArenaHost.Instance.Locale = o.locale; CharacterRegistry.LoadFromDisk(); ReadBots(Path.Combine("Data", "locales", o.locale, "bot.conf")); } @@ -26,7 +27,8 @@ namespace YGOLegacy.Tools.BotArena /// The game's SoloSelector.ReadBots, minus the deck-cover lookup. private static void ReadBots(string confPath) { - SoloSelector.bots.Clear(); + var bots = ArenaHost.Instance.Bots; + bots.Clear(); if (!File.Exists(confPath)) { Program.Log("no " + confPath + " — using the built-in Dovphin command"); @@ -37,14 +39,14 @@ namespace YGOLegacy.Tools.BotArena { var line = (reader.ReadLine() ?? string.Empty).Trim(); if (line.Length == 0 || line[0] != '!') continue; - var bot = new SoloSelector.BotInfo + var bot = new BotConfEntry { name = line.TrimStart('!'), command = (reader.ReadLine() ?? string.Empty).Trim(), desc = (reader.ReadLine() ?? string.Empty).Trim(), }; bot.flags = (reader.ReadLine() ?? string.Empty).Trim().Split(' '); - SoloSelector.bots.Add(bot); + bots.Add(bot); } } @@ -59,12 +61,12 @@ namespace YGOLegacy.Tools.BotArena var localeCdb = Path.Combine("Data", "locales", o.locale, "cards.cdb"); if (!File.Exists(localeCdb)) throw new FileNotFoundException("card database not found: " + Path.GetFullPath(localeCdb) + " (wrong --root or --locale?)"); - MDPro3.IO.ResourceManager.ZipCdbPaths = ExtractZipCdbs(MDPro3.Program.PATH_EXPANSIONS); + ArenaHost.Instance.ZipCdbPaths = ExtractZipCdbs("Expansions/"); WindBot.Program.InitDatas("cards.cdb"); } /// .cdb entries of Expansions/*.ypk|*.zip, extracted once per archive - /// version into %TEMP%/YGOLBotArena/cdb/. Concurrent workers race for + /// version into /YGOLBotArena/cdb/. Concurrent workers race for /// the same file: write to a temp name and move into place, first wins. private static List ExtractZipCdbs(string expansions) { diff --git a/src/BotArena/Shims/MDPro3.cs b/src/BotArena/Shims/MDPro3.cs deleted file mode 100644 index 4489ca4..0000000 --- a/src/BotArena/Shims/MDPro3.cs +++ /dev/null @@ -1,63 +0,0 @@ -using System.Collections.Generic; - -// Shims: the handful of MDPro3 statics that WindBot's Program.cs and the fork's -// BotRoster.cs touch. Each is a data holder the arena fills in before use; the -// game's own classes are NOT compiled here (they drag in Unity). -namespace MDPro3 -{ - /// WindBot.Program.InitDatas scans MDPro3.Program.PATH_EXPANSIONS for *.cdb. - public static class Program - { - public const string PATH_EXPANSIONS = "Expansions/"; - } - - /// Data/config.conf. The arena never writes one, so every key falls back to - /// its default -- which is what DeckLimits wants: the shipped cap, not a - /// local override. - public static class Config - { - public const string EMPTY_STRING = ""; - public static string Get(string key, string fallback) => fallback; - } -} - -namespace MDPro3.IO -{ - /// WindBot.Program.InitDatas adds every .cdb the game extracted out of the - /// Expansions/*.ypk archives. The arena worker extracts them itself - /// (Worker.ExtractZipCdbs) and parks the paths here. - public static class ResourceManager - { - public static List ZipCdbPaths = new(); - public static List GetAllCdbInZipPaths() => ZipCdbPaths; - } -} - -namespace MDPro3.Utility -{ - /// The active locale: picks Data/locales//cards.cdb and bot.conf. - public static class Language - { - public static string Current = "en-US"; - public static string GetConfig() => Current; - } -} - -namespace MDPro3.Servant -{ - /// BotRoster reads the "use your deck" (Dovphin) bot.conf line from here. - /// The arena parses Data/locales//bot.conf into it (Program.ReadBots) - /// — same shape as the game's SoloSelector.BotInfo/bots. - public static class SoloSelector - { - public class BotInfo - { - public string name; - public string command; - public string desc; - public string[] flags; - } - - public static readonly List bots = new(); - } -} diff --git a/src/BotArena/Shims/MonoDataSqlite.cs b/src/BotArena/Shims/MonoDataSqlite.cs deleted file mode 100644 index 86d21c8..0000000 --- a/src/BotArena/Shims/MonoDataSqlite.cs +++ /dev/null @@ -1,22 +0,0 @@ -// Shim: YGOSharp's NamedCardsManager is written against Mono.Data.Sqlite -// (Unity ships it). Outside Unity we sit the same two type names on top of -// Microsoft.Data.Sqlite, whose connection/command surface is identical for the -// SELECT it runs. Read-only, shared: several worker processes open the same -// .cdb files (some through the Expansions/ junction) at once. -namespace Mono.Data.Sqlite -{ - public class SqliteConnection : Microsoft.Data.Sqlite.SqliteConnection - { - public SqliteConnection(string connectionString) - : base(ReadOnly(connectionString)) { } - - private static string ReadOnly(string cs) - => cs.Contains("Mode=") ? cs : cs.TrimEnd(';') + ";Mode=ReadOnly;Cache=Shared"; - } - - public class SqliteCommand : Microsoft.Data.Sqlite.SqliteCommand - { - public SqliteCommand(string commandText, SqliteConnection connection) - : base(commandText, connection) { } - } -} diff --git a/src/BotArena/Shims/UnityEngine.Debug.cs b/src/BotArena/Shims/UnityEngine.Debug.cs deleted file mode 100644 index e425faf..0000000 --- a/src/BotArena/Shims/UnityEngine.Debug.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; - -// Shim: UnityEngine.Debug for code linked from the game (SmartExecutor, -// CharacterRegistry log via UnityEngine.Debug.Log*). Routes to the sink the -// arena installs (stderr in a worker, or a per-worker log file); nothing else -// of UnityEngine exists here on purpose — if a linked file needs more, that -// file is the wrong thing to link. -namespace UnityEngine -{ - public static class Debug - { - /// Where log lines go; the worker points this at its log writer. - public static Action Sink = s => Console.Error.WriteLine(s); - - public static void Log(object message) => Sink?.Invoke(Text(message)); - public static void LogWarning(object message) => Sink?.Invoke("[warn] " + Text(message)); - public static void LogError(object message) => Sink?.Invoke("[error] " + Text(message)); - public static void LogException(Exception e) => Sink?.Invoke("[exception] " + e); - public static void LogFormat(string format, params object[] args) => Log(string.Format(format, args)); - - private static string Text(object message) => message?.ToString() ?? "null"; - } -} diff --git a/src/BotArena/Worker.cs b/src/BotArena/Worker.cs index df5cb59..0805d08 100644 --- a/src/BotArena/Worker.cs +++ b/src/BotArena/Worker.cs @@ -50,7 +50,7 @@ namespace YGOLegacy.Tools.BotArena // stdout is the protocol channel; everything chatty goes to stderr. proto = Console.Out; Console.SetOut(Console.Error); - UnityEngine.Debug.Sink = s => Console.Error.WriteLine(s); + ArenaHost.Sink = s => Console.Error.WriteLine(s); try { diff --git a/src/BotArena/YgoServer.cs b/src/BotArena/YgoServer.cs index 165df3b..d1f2e8d 100644 --- a/src/BotArena/YgoServer.cs +++ b/src/BotArena/YgoServer.cs @@ -10,8 +10,8 @@ using YGOLegacy.Engine; namespace YGOLegacy.Tools.BotArena { /// - /// The game's server is not an exe: it is ygol-engine.dll - /// (Assets/Plugins/Windows/), driven exactly as MDPro3.Net.YgoServer drives + /// The game's server is not an exe: it is the engine library + /// (ygol-engine.dll / libygol-engine.so), driven exactly as MDPro3.Net.YgoServer drives /// it — start_server(args) blocks on a thread until the duel ends /// (the server-mode build stops itself after DuelEnd) or stop_server() /// is called. It reads ./expansions (Expansions/ on the Windows FS), @@ -27,32 +27,12 @@ namespace YGOLegacy.Tools.BotArena { public const int DefaultTime = 180; // OnlineServant.DEFAULT_TIME private static Thread serverThread; - private static string dllPath; public static bool Running => serverThread != null && serverThread.IsAlive; - public static string DllPath => dllPath; + public static string DllPath => EngineLibrary.Path; - /// Find ygol-engine.dll and teach the runtime where it is. Order: env - /// YGOL_ENGINE_DLL, the project's plugin folder, a built player's - /// plugin folder, next to this exe. - public static void Locate(string root) - { - var candidates = new[] - { - Environment.GetEnvironmentVariable("YGOL_ENGINE_DLL"), - Path.Combine(root, "Assets", "Plugins", "Windows", "ygol-engine.dll"), - Path.Combine(root, "YGOLegacy_Data", "Plugins", "x86_64", "ygol-engine.dll"), - Path.Combine(root, "MDPro3_Data", "Plugins", "x86_64", "ygol-engine.dll"), - Path.Combine(AppContext.BaseDirectory, "ygol-engine.dll"), - }; - foreach (var c in candidates) - if (!string.IsNullOrEmpty(c) && File.Exists(c)) { dllPath = Path.GetFullPath(c); break; } - if (dllPath == null) - throw new FileNotFoundException("ygol-engine.dll not found (looked in Assets/Plugins/Windows under --root, a built player's Plugins/x86_64, next to the exe, and $YGOL_ENGINE_DLL)"); - - NativeLibrary.SetDllImportResolver(typeof(EngineApi).Assembly, (name, asm, path) => - name == "ygol-engine" ? NativeLibrary.Load(dllPath) : IntPtr.Zero); - } + /// Find the engine library (EngineLibrary.Locate) and teach the runtime where it is. + public static void Locate(string root) => EngineLibrary.Locate(root); /// A port nothing is listening on, from `from` upward. public static int FreePort(int from)