Files
Triforce-Source/launcher/LogicTests/Tests.Randomizer.cs
ruckus7382sfgsgdf b527e29adb Triforce v0.8.5
A Randomizer page in the launcher, a new title screen with Mods and Save Select tabs, scaling changes applied in game, the Jabu-Jabu bars fixed, renderer frame-time work and the brightness-flash fix, and fixes from the 0.8.4 reports.
2026-11-28 10:54:41 -06:00

518 lines
40 KiB
C#

using System.Formats.Tar;
using System.IO.Compression;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json.Nodes;
using Triforce.Logic;
using static Triforce.LogicTests.T;
namespace Triforce.LogicTests;
/// <summary>((Triforce, 11-25) A stand-in for OOTRR's program (this test program, copied in as ootrr.exe): settings-dump, its
/// --decode, generate and build, as OOTRR 0.8.2 answers them, with what it was asked written to ootrr-calls.txt beside it.
/// A seed text "fail" makes generate fail; "slow" makes build wait (to be stopped), a file of its build held open.</summary>
static class FakeOotrr
{
public const string Schema = """
{"schema_version":1,"string_prefix":"OOTRR1-",
"groups":[{"id":"world","label":"World","tip":"How the world starts."},{"id":"goal","label":"Goals","tip":""},{"id":"starting","label":"Starting items","tip":""}],
"settings":[
{"id":"open_forest","num":3,"label":"Kokiri Forest","group":"world","kind":"choice","tag":"common","tip":"t","default":"closed","choices":[{"id":"open","label":"Open"},{"id":"closed","label":"Closed"}],"deps":[]},
{"id":"open_kakariko","num":4,"label":"Kakariko Gate","group":"world","kind":"choice","tag":"common","tip":"t","default":"closed","choices":[{"id":"open","label":"Open"},{"id":"closed","label":"Closed"}],"deps":[{"on":"open_forest","is":"open"}],"disabled":"closed"},
{"id":"open_door_of_time","num":5,"label":"Door of Time (old)","group":"world","kind":"toggle","tag":"common","tip":"t","default":false,"deps":[],"legacy":true},
{"id":"starting_age","num":2,"label":"Starting Age","group":"world","kind":"choice","tag":"core","tip":"t","default":"child","choices":[{"id":"child","label":"Child"},{"id":"adult","label":"Adult"}],"deps":[],"unsupported":true},
{"id":"bridge","num":24,"label":"Rainbow Bridge","group":"goal","kind":"choice","tag":"core","tip":"t","default":"vanilla","choices":[{"id":"open","label":"Open"},{"id":"vanilla","label":"Vanilla"},{"id":"dungeons","label":"Rewards"},{"id":"tokens","label":"Tokens"}],"deps":[]},
{"id":"bridge_rewards","num":27,"label":"Rewards for the bridge","group":"goal","kind":"number","tag":"common","tip":"t","default":9,"min":0,"max":9,"deps":[{"on":"bridge","is":"dungeons"}]},
{"id":"skip_ganon_trials","num":30,"label":"Skip trials","group":"goal","kind":"toggle","tag":"common","tip":"t","default":false,"deps":[]},
{"id":"trials","num":31,"label":"Trials","group":"goal","kind":"number","tag":"common","tip":"t","default":6,"min":0,"max":6,"deps":[{"on":"skip_ganon_trials","is":false}]},
{"id":"triforce_count","num":33,"label":"Pieces","group":"goal","kind":"number","tag":"common","tip":"t","default":30,"min":1,"max":999,"deps":[]},
{"id":"triforce_goal","num":34,"label":"Pieces needed","group":"goal","kind":"number","tag":"common","tip":"t","default":20,"min":1,"max":999,"max_by":"triforce_count","deps":[]},
{"id":"door_song","num":134,"label":"Door song","group":"world","kind":"toggle","tag":"common","tip":"t","default":true,"deps":[{"on":"bridge","not":"open"},{"on":"bridge","not":"tokens"}]},
{"id":"early_beds","num":77,"label":"Beds","group":"world","kind":"toggle","tag":"common","tip":"t","default":false,"deps":[{"on":"bridge","in":["vanilla","dungeons"]}]},
{"id":"enemy_health","num":110,"label":"Enemy health","group":"goal","kind":"number","tag":"common","tip":"t","default":100,"min":50,"max":500,"step":10,"times":100,"deps":[]},
{"id":"starting_items","num":36,"label":"Starting items","group":"starting","kind":"multi","tag":"common","tip":"t","default":[],"choices":[{"id":"ocarina","label":"Ocarina"},{"id":"bow","label":"Bow"},{"id":"hookshot","label":"Hookshot"},{"id":"hover_boots","label":"Hover Boots"}],"deps":[]},
{"id":"disabled_locations","num":13,"label":"Excluded","group":"starting","kind":"list","tag":"core","tip":"t","default":[],"max_items":2,"deps":[]}
],
"menu":[{"id":"win","label":"Logic","sections":[{"label":"Goal","items":[{"id":"bridge","view":{"label":"Bridge","opts":[{"label":"Open","ours":"open","live":false},{"label":"Vanilla","ours":"vanilla","live":true},{"label":"Trigger-Dungeons","ours":"","live":false}],"kind":"pick"}},{"stub":"Win Condition","kind":"choice"}]}]}],
"presets":[{"id":"default","name":"Default","tip":"d","order":0,"settings":{}},{"id":"easy","name":"Easy","tip":"e","order":10,"settings":{"open_forest":"open","open_kakariko":"open","bridge":"dungeons","bridge_rewards":3,"skip_ganon_trials":true}},
{"id":"open_world","name":"Open world","tip":"o","order":20,"settings":{"open_forest":"open","bridge":"open"}}]}
""";
public static int Run(string[] a)
{
var dir = AppContext.BaseDirectory;
File.AppendAllText(Path.Combine(dir, "ootrr-calls.txt"), string.Join("\u001f", a) + "\n");
string Arg(int i) => i < a.Length ? a[i] : "";
switch (Arg(0))
{
case "settings-dump" when Arg(1) == "--decode":
if (!Arg(2).StartsWith("OOTRR1-", StringComparison.Ordinal)) { Console.Error.WriteLine("error: not a settings string"); return 1; }
Console.WriteLine("{\"settings\":{\"open_forest\":\"open\",\"bridge\":\"tokens\",\"made_up\":1,\"trials\":99},\"warnings\":[\"one setting was dropped\"]}");
return 0;
case "settings-dump":
Console.WriteLine(Schema.Replace("\n", " "));
return 0;
case "generate":
{
var seed = Arg(2);
if (seed == "fail") { Console.Error.WriteLine("warning: something"); Console.Error.WriteLine("error: no placement could be found"); return 1; }
var settings = File.ReadAllText(Arg(1));
if (System.Text.Json.Nodes.JsonNode.Parse(settings)?["bridge"]?.ToString() == "tokens")
{
Console.Error.WriteLine("error: bridge is tokens, which this build cannot apply yet (only vanilla and dungeons work)");
return 1;
}
File.WriteAllText(Arg(3), "{\"format\":\"ootrr-seed\",\"version\":1,\"generator\":\"ootrr-core fake\",\"seed\":" + System.Text.Json.JsonSerializer.Serialize(seed) +
",\"settings\":\"OOTRR1-FAKE" + settings.Length + "\",\"placements\":{}}");
if (Arg(4) == "--spoiler") File.WriteAllText(Arg(5), "Spoiler of " + seed + "\n");
Console.WriteLine("Chest shuffle slice, seed \"" + seed + "\"");
Console.WriteLine("seed file: " + Arg(3));
return 0;
}
case "build":
{
var seed = System.Text.Json.Nodes.JsonNode.Parse(File.ReadAllText(Arg(1)))?["seed"]?.ToString() ?? "";
var root = Path.Combine(Arg(3), Arg(4));
Directory.CreateDirectory(Path.Combine(root, "romfs", "Event", "EventFlow"));
Directory.CreateDirectory(Path.Combine(root, "exefs"));
if (seed == "slow")
{
// (a file it writes, held open as a real build's would be, while it waits to be stopped)
using var held = new FileStream(Path.Combine(root, "romfs", "held.bin"), FileMode.Create, FileAccess.Write, FileShare.None);
Console.WriteLine("Writing flows");
Thread.Sleep(30000);
}
Console.WriteLine("Writing flows");
File.WriteAllText(Path.Combine(root, "romfs", "Event", "EventFlow", "Dm_Kokiri_0000.bfevfl.zs"), "flow of " + seed);
File.WriteAllText(Path.Combine(root, "romfs", "Event", "x.txt"), "x");
Console.WriteLine("changed 3 of 4 placed chests");
return 0;
}
}
Console.Error.WriteLine("error: unknown command " + Arg(0));
return 2;
}
}
static partial class Tests
{
static RandoSchema TestSchema() => RandoSchema.Parse(FakeOotrr.Schema);
// ---------------- the settings ----------------
static void RandoSchemaRules()
{
var s = TestSchema();
Equal(3, s.Groups.Count, "groups");
Equal("OOTRR1-", s.StringPrefix, "the settings strings' prefix");
Equal(3, s.Presets.Count, "presets");
var d = s.Defaults();
Equal("closed", d["open_forest"]!.ToString(), "a choice's default");
Equal(0, s.ForOotrr(d).Count, "the defaults: nothing to tell OOTRR");
// (dependencies: is, not, in; a held value; hidden)
var kak = s.Find("open_kakariko")!;
Equal(RandoState.Held, s.StateOf(kak, d), "the gate is held while the forest is closed");
d["open_kakariko"] = "open";
Equal("closed", s.Effective(d)["open_kakariko"]!.ToString(), "a held setting takes its held value");
Equal(0, s.ForOotrr(d).Count, "a held value that is the default is not told");
d["open_forest"] = "open";
Equal(RandoState.Open, s.StateOf(kak, d), "open forest: the gate opens up");
Equal("open", s.ForOotrr(d)["open_kakariko"]!.ToString(), "and its value goes to OOTRR");
Equal(RandoState.Hidden, s.StateOf(s.Find("bridge_rewards")!, d), "a setting whose dependency fails, with no held value, is left out");
d["bridge"] = "tokens";
Equal(RandoState.Hidden, s.StateOf(s.Find("door_song")!, d), "not: tokens is one of the values it must not have");
Equal(RandoState.Hidden, s.StateOf(s.Find("early_beds")!, d), "in: tokens is not one of its values");
d["bridge"] = "dungeons";
Equal(RandoState.Open, s.StateOf(s.Find("door_song")!, d), "not, met");
Equal(RandoState.Open, s.StateOf(s.Find("early_beds")!, d), "in, met");
// (values as each kind takes them)
var fo = s.Find("open_forest")!;
Check(RandoSchema.Clean(fo, JsonValue.Create("nope")) == null, "a choice that is not one is refused");
Check(RandoSchema.Clean(s.Find("skip_ganon_trials")!, JsonValue.Create("true")) == null, "a toggle takes true or false only");
var hp = s.Find("enemy_health")!;
Equal("120", RandoSchema.Clean(hp, JsonNode.Parse("120"))!.ToJsonString(), "a number in range and step");
Equal("120", RandoSchema.Clean(hp, JsonNode.Parse("120.0"))!.ToJsonString(), "a whole number written as 120.0");
Check(RandoSchema.Clean(hp, JsonNode.Parse("125")) == null, "off its step");
Check(RandoSchema.Clean(hp, JsonNode.Parse("510")) == null, "above its range");
var multi = s.Find("starting_items")!;
Equal("[\"ocarina\",\"bow\"]", RandoSchema.Clean(multi, JsonNode.Parse("[\"bow\",\"ocarina\",\"bow\"]"))!.ToJsonString(), "multi: in OOTRR's order, each once");
Check(RandoSchema.Clean(multi, JsonNode.Parse("[\"bow\",\"sword\"]")) == null, "multi: an item it does not have is refused");
var list = s.Find("disabled_locations")!;
Check(RandoSchema.Clean(list, JsonNode.Parse("[\"a\",\"b\",\"c\"]")) == null, "a list longer than its most");
Equal("Ocarina, Bow", RandoSchema.Show(multi, JsonNode.Parse("[\"ocarina\",\"bow\"]")), "multi shown by its labels");
Equal("None", RandoSchema.Show(multi, new JsonArray()), "an empty multi");
Equal("Ocarina, Bow and 2 more", RandoSchema.Show(multi, JsonNode.Parse("[\"ocarina\",\"bow\",\"hookshot\",\"hover_boots\"]")), "a long multi");
Equal(100L, hp.Times, "a multiple's times");
Equal("1.5\u00d7", RandoSchema.Show(hp, JsonNode.Parse("150")), "a multiple shown as one");
Equal("1\u00d7", RandoSchema.Show(hp, JsonNode.Parse("100")), "a whole multiple");
Equal("6", RandoSchema.Show(s.Find("trials")!, JsonNode.Parse("6")), "a plain number");
// (max_by: no higher than another setting; a value above it comes down to it, and goes back up with it)
var goal = s.Find("triforce_goal")!;
d["triforce_count"] = 12;
Equal(12L, s.MaxOf(goal, d), "max_by caps the most");
Equal("12", s.Effective(d)["triforce_goal"]!.ToJsonString(), "the default 20, above 12: 12");
Equal("12", s.ForOotrr(d)["triforce_goal"]!.ToJsonString(), "and that is what OOTRR is told");
d["triforce_count"] = 40;
Equal("20", s.Effective(d)["triforce_goal"]!.ToJsonString(), "the value kept, once the other is higher again");
Equal(120L, RandoSchema.Snap(hp, 125), "a number brought onto its step, down");
Equal(50L, RandoSchema.Snap(hp, 40), "never below its least");
// (presets and a saved map read back)
var easy = s.WithPreset("easy");
Equal("easy", s.PresetOf(easy), "a preset's values are that preset");
Equal("default", s.PresetOf(s.Defaults()), "the defaults are Default");
easy["trials"] = 3; // (a setting that is hidden under easy: held values decide, so it is still Easy)
Equal("easy", s.PresetOf(easy), "a change that the preset hides does not leave it");
easy["open_forest"] = "closed";
Equal(null, s.PresetOf(easy), "a change it shows: Custom");
var adopted = s.Adopt(JsonNode.Parse("{\"open_forest\":\"open\",\"not_there\":1,\"trials\":99,\"open_door_of_time\":true}") as JsonObject);
Equal("open", adopted["open_forest"]!.ToString(), "a saved value kept");
Equal("6", adopted["trials"]!.ToJsonString(), "a saved value it would refuse: the default");
Check(!adopted.ContainsKey("not_there"), "a setting it does not know is dropped");
Check(!s.ForOotrr(adopted).ContainsKey("open_door_of_time"), "a legacy setting is never told");
Throws<FormatException>(() => RandoSchema.Parse("{\"groups\":[]}"), "a dump without settings");
// (an option OOTRR's menu marks as not live: refused, and a preset that asks for it gets the default there, said)
var bridge = s.Find("bridge")!;
Check(!bridge.IsLive("open") && bridge.IsLive("vanilla") && bridge.IsLive("dungeons"), "the menu's live flags (an option with no value of OOTRR's is no choice)");
Check(RandoSchema.Clean(bridge, JsonValue.Create("open")) == null, "a value the build cannot apply yet is refused");
var ow = s.WithPreset("open_world");
Equal("vanilla", ow["bridge"]!.ToString(), "the preset's not-live value: the default");
Equal("open", ow["open_forest"]!.ToString(), "its other values kept");
var gaps = s.Gaps(s.Preset("open_world")!.Settings);
Check(gaps.Count == 1 && gaps[0] == ("Rainbow Bridge", "Open", "Vanilla"), "said: " + string.Join(";", gaps));
// (OOTRR's refusals in the settings' own words)
Equal("Rainbow Bridge is Open, which this build cannot apply yet (only Vanilla, Rewards and Tokens work)",
Randomizer.Friendly(s, "bridge is open, which this build cannot apply yet (only vanilla, dungeons and tokens work)"), "a list of choices");
Equal("Rainbow Bridge is Open, which this build cannot apply yet (only Vanilla works)",
Randomizer.Friendly(s, "bridge is open, which this build cannot apply yet (only vanilla works)"), "one choice");
Equal("something else entirely", Randomizer.Friendly(s, "something else entirely"), "a message it does not know stays");
}
static void RandoNames()
{
Equal("Randomizer K7QW2MPA", Randomizer.FolderName("K7QW2MPA"), "a plain seed");
Equal("Randomizer my seed for Saturday", Randomizer.FolderName(" my_seed.for Saturday "), "space, _ and . become spaces");
Equal("Randomizer a-b-c", Randomizer.FolderName("a/b\\c"), "path characters cannot leave the folder");
Equal("Randomizer seed", Randomizer.FolderName("::"), "nothing left: seed");
Check(Randomizer.FolderName(new string('x', 300)).Length <= 60, "a long seed is cut");
Check(Randomizer.FolderName("../../x").IndexOf("..", StringComparison.Ordinal) < 0, "no .. in a name");
var root = NewRoot("rando-names");
Directory.CreateDirectory(Path.Combine(root, "-Randomizer x"));
Equal("Randomizer x 2", Randomizer.FreeName(root, "Randomizer x"), "a name an off folder has is taken");
var r = Randomizer.RandomSeed();
Check(r.Length == 8 && r.All(c => char.IsAsciiLetterUpper(c) || char.IsAsciiDigit(c)), "a random seed: eight letters and digits");
var o = new Ootrr(Ctx(root));
Equal("ootrr.exe", o.KeptName("OOTRR-0.8.2-windows-x64-portable/ootrr.exe"), "the program, one folder down");
Equal("LICENSE", o.KeptName("OOTRR-0.8.2-windows-x64-portable/LICENSE"), "its licence");
Equal(null, o.KeptName("OOTRR/../ootrr.exe"), "a name that climbs out");
Equal(null, o.KeptName("a/b/c/ootrr.exe"), "too deep");
Equal(null, o.KeptName("OOTRR/evil.dll"), "anything else");
Equal("The randomizer stopped: no placement could be found", Ootrr.ErrorOf(new OotrrRun(1, "", "warning: x\nerror: no placement could be found\n")), "an error line, warnings skipped");
}
// ---------------- installing ----------------
static byte[] TarGz(params (string Name, string Text)[] files)
{
using var m = new MemoryStream();
using (var gz = new GZipStream(m, CompressionLevel.Fastest, true))
using (var tar = new TarWriter(gz, TarEntryFormat.Pax, true))
foreach (var (name, text) in files)
tar.WriteEntry(new PaxTarEntry(TarEntryType.RegularFile, name) { DataStream = new MemoryStream(Encoding.UTF8.GetBytes(text)) });
return m.ToArray();
}
static async Task RandoInstall()
{
using var server = new FakeServer();
var root = NewRoot("rando-install");
var ctx = Ctx(root, env: new() { ["TRIFORCE_OOTRR_URL"] = server.Url + "/rel" });
using var http = Downloader.CreateHttp();
// (a zip as the Windows release is: one folder, the program and its papers; plus names that must not come out)
var exe = ctx.IsWindows ? "ootrr.exe" : "ootrr";
var zip = Zip(("OOTRR-0.8.2-windows-x64-portable/" + exe, "PROGRAM"), ("OOTRR-0.8.2-windows-x64-portable/LICENSE", "GPL"),
("OOTRR-0.8.2-windows-x64-portable/README.md", "readme"), ("../outside.txt", "no"), ("../" + exe, "CLIMBED"), ("x/../../" + exe, "CLIMBED"),
("OOTRR-0.8.2-windows-x64-portable/data/cache.bin", "no"));
var f = new OotrrFile("OOTRR-test.zip", zip.Length, Convert.ToHexStringLower(SHA256.HashData(zip)));
server.Add("/rel/OOTRR-test.zip", zip);
var o = new Ootrr(ctx, null, f);
{
Check(!o.Have, "nothing yet");
await o.InstallAsync(http, null, CancellationToken.None);
Check(o.Have, "installed");
Equal("PROGRAM", File.ReadAllText(Path.Combine(o.Folder, exe)), "the program");
Check(File.Exists(Path.Combine(o.Folder, "LICENSE")) && File.Exists(Path.Combine(o.Folder, "portable.txt")), "its licence, and portable.txt written");
Check(!File.Exists(Path.Combine(root, "outside.txt")) && !File.Exists(Path.Combine(o.Folder, "cache.bin")), "nothing else came out");
Check(!File.Exists(Path.Combine(Path.GetDirectoryName(o.Folder)!, exe)) && !File.Exists(Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(o.Folder)!)!, exe)),
"a program named with .. lands nowhere: not above the folder");
Check(!File.Exists(Path.Combine(ctx.DownloadsFolder, "ootrr", "OOTRR-test.zip")), "the download is deleted once unpacked");
var seen = server.Requests;
await o.InstallAsync(http, null, CancellationToken.None);
Equal(seen, server.Requests, "installed: no second download");
// (a program in the folder that is not the pinned release's is not run)
Check(!new Ootrr(ctx, null, f with { Sha256 = new string('0', 64) }).Have, "another pin: not the program it expects");
o.Remove();
Check(!o.Have && !Directory.Exists(o.Folder), "removed");
}
// (a file whose hash is wrong: deleted, nothing unpacked)
var bad = new OotrrFile("OOTRR-bad.zip", zip.Length, new string('a', 64));
server.Add("/rel/OOTRR-bad.zip", zip);
var ob = new Ootrr(ctx, null, bad);
var e = await ThrowsAsync<OotrrException>(() => ob.InstallAsync(http, null, CancellationToken.None), "a wrong hash");
Check(e.Message.Contains("SHA-256"), "it says why");
Check(!File.Exists(Path.Combine(ctx.DownloadsFolder, "ootrr", "OOTRR-bad.zip")) && !ob.Have && !Directory.Exists(ob.Folder), "nothing kept");
// (the Linux release, a .tar.gz: the program by its name on this system)
var tgz = TarGz(("OOTRR-0.8.2-linux-x86_64/" + exe, "PROGRAM2"), ("OOTRR-0.8.2-linux-x86_64/NOTICE", "n"), ("OOTRR-0.8.2-linux-x86_64/install.sh", "no"));
var ft = new OotrrFile("OOTRR-test.tar.gz", tgz.Length, Convert.ToHexStringLower(SHA256.HashData(tgz)));
server.Add("/rel/OOTRR-test.tar.gz", tgz);
var ot = new Ootrr(ctx, null, ft);
await ot.InstallAsync(http, null, CancellationToken.None);
Equal("PROGRAM2", File.ReadAllText(Path.Combine(ot.Folder, exe)), "the program out of the tar");
Check(File.Exists(Path.Combine(ot.Folder, "NOTICE")) && !File.Exists(Path.Combine(ot.Folder, "install.sh")), "only the kept files");
}
// ---------------- seeds ----------------
/// <summary>A test root with a built game folder (its romfs folders) and the stand-in OOTRR; the randomizer for it.</summary>
static (TriforceContext Ctx, string Game, Randomizer R, string Calls) RandoSetup(string name)
{
var root = NewRoot(name);
var tool = Path.Combine(root, "fake-ootrr");
CopySelf(tool, "ootrr.exe");
var game = Path.Combine(root, "game");
foreach (var d in new[] { "Pack", "Banc", "Event", "System" }) Directory.CreateDirectory(Path.Combine(game, "romfs", d));
var ctx = Ctx(root, env: new() { ["TRIFORCE_OOTRR_EXE"] = Path.Combine(tool, "ootrr.exe") });
var mm = new ModManager(ctx) { GameRuns = _ => false };
return (ctx, game, new Randomizer(ctx, null, mm), Path.Combine(tool, "ootrr-calls.txt"));
}
static async Task RandoSeeds()
{
var (ctx, game, r, calls) = RandoSetup("rando-seeds");
var s = await r.SchemaAsync(CancellationToken.None);
Equal(15, s.Settings.Count, "the settings, from the program's settings-dump");
var values = s.WithPreset("easy");
values["starting_items"] = JsonNode.Parse("[\"hookshot\"]");
var lines = new List<string>();
// (what a stopped build left: taken away by the next seed; never read by the game or listed)
var left = Path.Combine(game, "mods", Randomizer.Making + "old1", "romfs", "Event");
Directory.CreateDirectory(left);
File.WriteAllText(Path.Combine(left, "half.txt"), "half");
Check(r.Manager.ListGame(game).All(m => !m.Path.Contains(Randomizer.Making)), "a build folder is no mod");
var made = await r.MakeAsync(game, s, values, "Saturday race!", new RandoCosmetics("grouped", "off", "random", false), lines.Add, CancellationToken.None, "Easy");
Check(!Directory.EnumerateDirectories(Path.Combine(game, "mods"), Randomizer.Making + "*").Any(), "no build folder left, the old one taken away");
Equal("Easy", made.Seed.Preset, "the preset it went by, kept");
var folder = Path.Combine(game, "mods", "Randomizer Saturday race!");
Equal(folder, made.Seed.Mod.Path, "the seed's folder");
Check(made.Seed.Mod.On, "on");
Equal("flow of Saturday race!", File.ReadAllText(Path.Combine(folder, "romfs", "Event", "EventFlow", "Dm_Kokiri_0000.bfevfl.zs")), "the seed's game files");
Check(!Directory.Exists(Path.Combine(folder, "exefs")), "the build's empty exefs is not kept");
Check(File.Exists(made.Seed.SeedFile) && File.ReadAllText(made.Seed.Spoiler) == "Spoiler of Saturday race!\n", "the seed file and spoiler beside it");
Equal("OOTRR1-FAKE", made.Seed.Settings.Substring(0, 11), "the settings string, from the seed file");
var sent = JsonNode.Parse(File.ReadAllText(Path.Combine(made.Seed.Files, "settings.json")))!.AsObject();
Equal("open", sent["open_forest"]!.ToString(), "the preset's values went to generate");
Equal("[\"hookshot\"]", sent["starting_items"]!.ToJsonString(), "and the changed one");
Check(!sent.ContainsKey("trials") && !sent.ContainsKey("triforce_count"), "only what differs from the defaults");
Check(lines.Contains("Placing the items") && lines.Contains("changed 3 of 4 placed chests"), "progress lines, the program's own among them");
var build = File.ReadAllLines(calls).Select(l => l.Split('\u001f')).Last(a => a[0] == "build");
Equal(Path.Combine(game, "romfs"), build[2], "built from the game folder's romfs");
Equal(Path.Combine(game, "mods"), build[3], "into its mods folder");
Check(build[4].StartsWith(Randomizer.Making, StringComparison.Ordinal), "under a hidden name first: " + build[4]);
var opt = string.Join(" ", build.Skip(5));
Check(opt.Contains("--host nx2navi") && opt.Contains("--music grouped") && opt.Contains("--colors random") && opt.Contains("--no-title-logo"), "host and cosmetics: " + opt);
Equal("Randomizer · Saturday race!", ModManager.ReadInfo(folder)!.Name, "its name on the Mods page");
Check(!Directory.Exists(Path.Combine(ctx.Home, "randomizer", "work")) || !Directory.EnumerateFileSystemEntries(Path.Combine(ctx.Home, "randomizer", "work")).Any(), "the work folder is cleaned");
// (a second seed: on, the first off; the same seed again gets a folder of its own)
var second = await r.MakeAsync(game, s, s.Defaults(), "Saturday race!", new RandoCosmetics(), null, CancellationToken.None);
Equal("Randomizer Saturday race! 2", second.Seed.Mod.Name, "the same seed's second folder");
var seeds = r.Seeds(game);
Equal(2, seeds.Count, "two seeds");
Equal(1, seeds.Count(x => x.Mod.On), "one on");
Check(seeds.Single(x => x.Mod.On).Mod.Name == "Randomizer Saturday race! 2", "the new one");
Check(Directory.Exists(Path.Combine(game, "mods", "-Randomizer Saturday race!")), "the first switched off by its folder's name");
r.Use(game, seeds.Single(x => !x.Mod.On));
Equal("Randomizer Saturday race!", r.Seeds(game).Single(x => x.Mod.On).Mod.Name, "Use: that one on, the other off");
r.Off(game);
Check(r.Seeds(game).All(x => !x.Mod.On), "Off: every seed off");
r.Remove(game, r.Seeds(game).First(x => x.Mod.Name == "Randomizer Saturday race! 2"));
Equal(1, r.Seeds(game).Count, "removed");
Check(Directory.EnumerateDirectories(Path.Combine(game, "mods", Mods.Removed)).Any(), "into mods\\.removed");
// (another mod that is on and carries one of the seed's files, sorting after it, wins it: said)
r.Use(game, r.Seeds(game).Single());
var other = Path.Combine(game, "mods", "Tall grass", "romfs", "Event", "EventFlow");
Directory.CreateDirectory(other);
File.WriteAllText(Path.Combine(other, "Dm_Kokiri_0000.bfevfl.zs"), "other");
var shared = r.Shared(game, r.Seeds(game).Single().Mod.Rel);
Check(shared.Count == 1 && shared[0].Name == "Tall grass" && shared[0].Wins, "the other mod that wins a file");
// (a seed whose other seed cannot be switched off: it is made, and stays off; never two seeds on)
var onNow = r.Seeds(game).Single(x => x.Mod.On);
Directory.CreateDirectory(Path.Combine(game, "mods", "-" + onNow.Mod.Folder)); // (where switching it off would rename it to)
var stuck = await ThrowsAsync<OotrrException>(() => r.MakeAsync(game, s, s.Defaults(), "Sunday", new RandoCosmetics(), null, CancellationToken.None), "the other seed cannot be switched off");
Check(stuck.Message.StartsWith("Seed Sunday is made, but it stays off: ", StringComparison.Ordinal), "said: " + stuck.Message);
Equal(1, r.Seeds(game).Count(x => x.Mod.On), "still one seed on");
Check(r.Seeds(game).Single(x => x.Seed == "Sunday") is { Mod.On: false } sunday && sunday.Mod.Folder == "-Randomizer Sunday", "the new one is there, off");
Directory.Delete(Path.Combine(game, "mods", "-" + onNow.Mod.Folder));
r.Use(game, r.Seeds(game).Single(x => x.Seed == "Sunday"));
Check(r.Seeds(game).Single(x => x.Mod.On).Seed == "Sunday", "and can be switched on once that is fixed");
// (a seed's file is anyone's to write: its cosmetics are only ever the known ones, its texts kept short)
var marker = Path.Combine(r.Seeds(game).Single(x => x.Seed == "Sunday").Mod.Path, Randomizer.Marker);
File.WriteAllText(marker, "{\"seed\":\"Sunday\",\"music\":\"<img src=x onerror=alert(1)>\",\"colors\":\"random\",\"preset\":\"" + new string('p', 500) + "\"}");
var junk = r.Seeds(game).Single(x => x.Seed == "Sunday");
Equal("off", junk.Cosmetics.Music, "an unknown music value: off");
Equal("random", junk.Cosmetics.Colors, "a known one kept");
Check(junk.Preset.Length <= 80, "a long preset name cut");
File.WriteAllText(marker, "[\"not an object\"]");
Check(r.Seeds(game).All(x => x.Seed != "Sunday"), "a seed file that is no object: not listed as a seed");
// (the kept choices)
r.SaveChoices(new RandoChoices { Values = s.ForOotrr(values), Seed = "abc", Cosmetics = new RandoCosmetics("anywhere", "grouped", "random", false) });
var back = r.LoadChoices();
Equal("abc", back.Seed, "the seed text kept");
Equal(new RandoCosmetics("anywhere", "grouped", "random", false), back.Cosmetics, "the cosmetics kept");
Equal("open", s.Adopt(back.Values)["open_forest"]!.ToString(), "the values kept");
var choices = Path.Combine(ctx.Home, Randomizer.WorkFolder, "choices.json");
Check(File.Exists(choices), "kept in the launcher's randomizer folder (which the uninstall takes away)");
foreach (var bad in new[] { "[1,2]", "\"text\"", "5", "{\"cosmetics\":[1],\"seed\":5,\"values\":\"x\"}", "{\"seed\":\"two\\nlines\"}", "{broken" })
{
File.WriteAllText(choices, bad);
var b = r.LoadChoices();
Check(b.Seed == "" && b.Values == null && b.Cosmetics == new RandoCosmetics(), "a choices file that is not one: the defaults (" + bad + ")");
}
Check(Uninstaller.OwnFolders.Contains(Randomizer.WorkFolder), "the uninstall takes the randomizer's folder away");
}
static async Task RandoFailures()
{
var (_, game, r, _) = RandoSetup("rando-fail");
var s = await r.SchemaAsync(CancellationToken.None);
var e = await ThrowsAsync<OotrrException>(() => r.MakeAsync(game, s, s.Defaults(), "fail", new RandoCosmetics(), null, CancellationToken.None), "generate fails");
Equal("The randomizer stopped: no placement could be found", e.Message, "OOTRR's own error");
Check(!Directory.Exists(Path.Combine(game, "mods", "Randomizer fail")), "no folder left");
// (stopped while the build writes, a file of its own held open: the program is gone before its folder is taken away)
using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(60)))
await ThrowsAsync<OperationCanceledException>(() => r.MakeAsync(game, s, s.Defaults(), "slow", new RandoCosmetics(), l => { if (l == "Writing flows") cts.Cancel(); }, cts.Token), "stopped part way");
Check(!Directory.Exists(Path.Combine(game, "mods", "Randomizer slow")) && !Directory.Exists(Path.Combine(game, "mods", "-Randomizer slow")), "a stopped build leaves no half-made seed");
Check(!Directory.EnumerateDirectories(Path.Combine(game, "mods"), Randomizer.Making + "*").Any(), "nor its build folder (the file it held let go)");
await ThrowsAsync<OotrrException>(() => r.MakeAsync(game, s, s.Defaults(), "two\nlines", new RandoCosmetics(), null, CancellationToken.None), "a line break in a seed");
await ThrowsAsync<OotrrException>(() => r.MakeAsync(game, s, s.Defaults(), new string('x', Randomizer.MaxSeed + 1), new RandoCosmetics(), null, CancellationToken.None), "a seed too long");
var full = Ctx(Path.GetDirectoryName(game)!, env: new() { ["TRIFORCE_OOTRR_EXE"] = r.Tool.Exe });
full.FreeBytes = _ => 10L << 20;
var cramped = new Randomizer(full, null, new ModManager(full) { GameRuns = _ => false });
var room = await ThrowsAsync<OotrrException>(() => cramped.MakeAsync(game, s, s.Defaults(), "room", new RandoCosmetics(), null, CancellationToken.None), "a disk without room");
Check(room.Message.Length > 0 && !Directory.Exists(Path.Combine(game, "mods", "Randomizer room")), "refused before anything is written: " + room.Message);
// (the check before a seed: what OOTRR refuses, in the settings' words; nothing written in the mods folder)
var refused = s.Defaults();
refused["bridge"] = "tokens";
Equal("Rainbow Bridge is Tokens, which this build cannot apply yet (only Vanilla and Rewards work)", await r.CheckAsync(s, refused, CancellationToken.None), "refused");
Equal(null, await r.CheckAsync(s, s.Defaults(), CancellationToken.None), "the defaults can be made");
Check(!Directory.Exists(Path.Combine(game, "mods")) || !Directory.EnumerateFileSystemEntries(Path.Combine(game, "mods")).Any(), "the check writes no seed");
// (a program that cannot be started is no answer about the settings: it throws, and is asked again next time)
var notYet = Path.Combine(Path.GetDirectoryName(game)!, "not-yet", "ootrr.exe");
var nctx = Ctx(Path.GetDirectoryName(game)!, env: new() { ["TRIFORCE_OOTRR_EXE"] = notYet });
var nr = new Randomizer(nctx, null, new ModManager(nctx) { GameRuns = _ => false });
var gone = await ThrowsAsync<OotrrException>(() => nr.CheckAsync(s, refused, CancellationToken.None), "no program");
Check(gone.Exit == null, "not a refusal of OOTRR's");
Directory.CreateDirectory(Path.GetDirectoryName(notYet)!);
File.WriteAllText(notYet, "not a program");
var bad = await ThrowsAsync<OotrrException>(() => nr.CheckAsync(s, refused, CancellationToken.None), "a program that cannot be started");
Check(bad.Exit == null && bad.Message.StartsWith("The randomizer could not be started", StringComparison.Ordinal), "said: " + bad.Message);
CopySelf(Path.GetDirectoryName(notYet)!, "ootrr.exe");
Equal("Rainbow Bridge is Tokens, which this build cannot apply yet (only Vanilla and Rewards work)", await nr.CheckAsync(s, refused, CancellationToken.None), "asked again: OOTRR's answer");
var (values, warnings) = await r.DecodeAsync(s, "OOTRR1-ABC", CancellationToken.None);
Equal("tokens", values["bridge"]!.ToString(), "a settings string read by OOTRR");
Equal("6", values["trials"]!.ToJsonString(), "a value it would refuse: the default");
Equal(2, warnings.Count, "its warning, and the value it would refuse: " + string.Join(" | ", warnings));
Check(warnings[1].StartsWith("Trials: 99 cannot be used", StringComparison.Ordinal), "which one");
await ThrowsAsync<OotrrException>(() => r.DecodeAsync(s, "hello there", CancellationToken.None), "not a settings string");
await ThrowsAsync<OotrrException>(() => r.DecodeAsync(s, "NOPE", CancellationToken.None), "OOTRR refuses it");
var mm = new ModManager(Ctx(Path.GetDirectoryName(game)!)) { GameRuns = _ => true };
var running = new Randomizer(Ctx(Path.GetDirectoryName(game)!, env: new() { ["TRIFORCE_OOTRR_EXE"] = r.Tool.Exe }), null, mm);
await ThrowsAsync<OotrrException>(() => running.MakeAsync(game, s, s.Defaults(), "x", new RandoCosmetics(), null, CancellationToken.None), "the game runs");
Directory.Delete(Path.Combine(game, "romfs", "Banc"));
var e2 = await ThrowsAsync<OotrrException>(() => r.MakeAsync(game, s, s.Defaults(), "x", new RandoCosmetics(), null, CancellationToken.None), "no complete romfs");
Check(e2.Message.Contains("romfs"), "it says so");
}
/// <summary>OOTRR_E2E=&lt;ootrr.exe&gt;|&lt;built game folder&gt;: the real program, a real seed built from the real romfs into a copy of
/// the game folder's layout (its romfs read in place; nothing written in the game folder). Skipped without it.</summary>
static async Task RandoRealOotrr()
{
var spec = Environment.GetEnvironmentVariable("OOTRR_E2E");
if (string.IsNullOrEmpty(spec) || spec.Split('|') is not { Length: 2 } parts) { Console.WriteLine(" (skipped: OOTRR_E2E=<ootrr.exe>|<game folder> not set)"); return; }
var root = NewRoot("rando-e2e");
var game = Path.Combine(root, "game");
Directory.CreateDirectory(game);
// (the real romfs through a junction: read in place, never copied, never written)
var link = Path.Combine(game, "romfs");
if (OperatingSystem.IsWindows())
{
// (a junction: no rights needed, unlike a symbolic link)
var si = new System.Diagnostics.ProcessStartInfo("cmd.exe") { UseShellExecute = false, CreateNoWindow = true };
foreach (var a in new[] { "/c", "mklink", "/J", link, Path.Combine(parts[1], "romfs") }) si.ArgumentList.Add(a);
using var p = System.Diagnostics.Process.Start(si)!;
p.WaitForExit();
Check(Directory.Exists(link), "the junction to the real romfs");
}
else Directory.CreateSymbolicLink(link, Path.Combine(parts[1], "romfs"));
// (the link to the real romfs goes whatever happens: a folder cleaned later must never reach the game's files through it)
try
{
var ctx = Ctx(root, env: new() { ["TRIFORCE_OOTRR_EXE"] = parts[0] });
var r = new Randomizer(ctx, null, new ModManager(ctx) { GameRuns = _ => false });
var s = await r.SchemaAsync(CancellationToken.None);
Check(s.Settings.Count > 50 && s.Presets.Count > 0, "the real settings: " + s.Settings.Count);
// (every preset of OOTRR's, as the launcher applies it, makes a seed the build takes)
RandoMade? made = null;
JsonObject values = s.Defaults();
// (one the check refuses must fail the same way at Make, and leave nothing; one it passes must build)
foreach (var p in s.Presets)
{
var v = s.WithPreset(p.Id);
var gaps = s.Gaps(p.Settings);
var says = await r.CheckAsync(s, v, CancellationToken.None);
if (says != null)
{
await ThrowsAsync<OotrrException>(() => r.MakeAsync(game, s, v, "triforce-e2e-" + p.Id, new RandoCosmetics(), null, CancellationToken.None), "Make refuses what the check refused");
Check(!r.Seeds(game).Any(x => x.Seed == "triforce-e2e-" + p.Id), "nothing left of it");
Console.WriteLine(" preset " + p.Id + ": refused by OOTRR " + Ootrr.Version + ": " + says);
continue;
}
values = v;
made = await r.MakeAsync(game, s, v, "triforce-e2e-" + p.Id, new RandoCosmetics(), null, CancellationToken.None);
Console.WriteLine(" preset " + p.Id + ": built" + (gaps.Count > 0 ? ", with the default for " + string.Join("; ", gaps) : ""));
}
Check(made != null, "a seed");
Equal(1, r.Seeds(game).Count(x => x.Mod.On), "one seed on");
var files = Directory.GetFiles(Path.Combine(made!.Seed.Mod.Path, "romfs"), "*", SearchOption.AllDirectories);
Check(files.Length > 50, "the seed's game files: " + files.Length);
Check(made.Seed.Settings.StartsWith(s.StringPrefix, StringComparison.Ordinal), "a real settings string: " + made.Seed.Settings);
Check(new FileInfo(made.Seed.Spoiler).Length > 1000, "a real spoiler");
var (decoded, _) = await r.DecodeAsync(s, made.Seed.Settings, CancellationToken.None);
Equal(s.ForOotrr(values).ToJsonString(), s.ForOotrr(decoded).ToJsonString(), "the seed's settings string reads back as the settings it was made with");
Console.WriteLine(" " + files.Length + " files, " + files.Sum(f => new FileInfo(f).Length) / (1 << 20) + " MB, settings " + made.Seed.Settings);
}
finally
{
try { if (Directory.Exists(link) && new DirectoryInfo(link).Attributes.HasFlag(FileAttributes.ReparsePoint)) Directory.Delete(link); }
catch (Exception e) { Console.WriteLine(" the link to the real romfs could not be removed: " + link + " (" + e.Message + ")"); }
}
}
}