using System.Text.Json.Nodes; using Triforce.Logic; namespace Triforce.Launcher; /// ((Triforce, 11-25) The Randomizer page: OOTRR (Triforce.Logic.Ootrr, downloaded on first use and checked against its /// pinned SHA-256) makes seeds of the game that can be beaten, from OOTRR's own settings (its settings-dump: groups, presets, /// what depends on what), into the game folder's mods folder (Triforce.Logic.Randomizer). New seed: a preset or any setting, the /// seed's text, cosmetics, a pasted settings string. Your seeds: one on at a time, its spoiler log (asked first), its settings /// string, removed to mods\.removed as the Mods page does. public sealed partial class Backend { Randomizer? rando; Randomizer Rando => rando ??= new Randomizer(ctx); RandoSchema? randoSchema; RandoChoices randoChoices = new(); JsonObject randoValues = new(); int randoSchemaV; bool randoLoaded, randoSchemaSent; CancellationTokenSource? randoCts; string randoLine = "", randoToolLine = ""; double randoToolFrac; bool randoToolBusy; readonly object randoGate = new(); /// What OOTRR says against the settings as they are (Randomizer.CheckAsync), null when it can make them. string? randoProblem; CancellationTokenSource? randoCheckCts; readonly SemaphoreSlim randoCheckGate = new(1, 1); /// Why OOTRR's settings could not be read (the page offers to try again), null when they were or no try was made. string? randoSchemaError; readonly SemaphoreSlim randoSchemaGate = new(1, 1); /// 1 while a seed is made / OOTRR is downloaded: two clicks (each command runs on a worker of its own) start one. int randoMaking, randoInstalling; void RegisterRandomizer() { OnAsync("rando.open", _ => RandoOpen()); OnAsync("rando.install", _ => RandoInstallAsk()); OnAsync("rando.install.go", m => (string?)m["id"] == "go" ? RandoInstall() : Task.CompletedTask); On("rando.set", m => RandoSet((string?)m["id"], m["value"])); // (the page's choice sheets answer {id: the choice, ctx: what it was for}) On("rando.pick", m => RandoSet((string?)m["ctx"], JsonValue.Create((string?)m["id"]))); On("rando.preset", m => RandoPreset((string?)m["id"])); On("rando.preset.pick", m => RandoPreset((string?)m["id"])); On("rando.cos.pick", m => RandoCos((string?)m["ctx"], (string?)m["id"])); On("rando.reset", _ => { if (randoSchema is { } s) { lock (randoGate) randoValues = s.Defaults(); RandoKeep(); RandoCheckSoon(); } SendRando(); }); On("rando.seed", m => RandoSeedText((string?)m["text"] ?? "")); On("rando.reseed", _ => { randoChoices.Seed = Randomizer.RandomSeed(); RandoKeep(); SendRando(); }); On("rando.cos", m => RandoCos((string?)m["key"], (string?)m["value"])); OnAsync("rando.decode", m => RandoDecode((string?)m["text"] ?? "")); OnAsync("rando.make", _ => RandoMake()); On("rando.stop", _ => { try { randoCts?.Cancel(); } catch { } }); On("rando.use", m => RandoSeedDo((string?)m["id"], "use")); On("rando.off", _ => RandoAllOff()); On("rando.remove", m => RandoSeedDo((string?)m["id"], "remove")); On("rando.copy", m => RandoSeedDo((string?)m["id"], "copy")); On("rando.folder", m => RandoSeedDo((string?)m["id"], "folder")); On("rando.spoiler", m => { var id = (string?)m["id"]; if (RandoFind(id) == null) return; Ask("Open the spoiler log?", "

It lists where every item of this seed is, and one way through the game. Open it only if you want to know.

", "rando.spoiler.go", new[] { ("no", "Keep it closed", false), ("go", "Open it", true) }, id); }); On("rando.spoiler.go", m => { if ((string?)m["id"] == "go") RandoSeedDo((string?)m["ctx"], "spoiler"); }); On("rando.page", _ => OpenLink(Ootrr.Repo)); } // ---------------- state ---------------- /// The page's state. The settings' descriptions (labels, tips, choices) go once per program, the values each time. JsonObject RandoPageState(bool withSchema) { var g = GameDir; var tool = Rando.Tool; var o = new JsonObject { ["tool"] = new JsonObject { ["have"] = tool.Have, ["version"] = Ootrr.Version, ["size"] = Size(tool.File.Size), ["busy"] = randoToolBusy, ["frac"] = randoToolFrac, ["line"] = randoToolLine, }, ["game"] = g != null, ["busy"] = randoCts != null, ["line"] = randoLine, ["schemaV"] = randoSchemaV, ["problem"] = randoProblem, ["schemaError"] = randoSchemaError, ["maxSeed"] = Randomizer.MaxSeed, ["seed"] = randoChoices.Seed, ["cos"] = new JsonObject { ["music"] = randoChoices.Cosmetics.Music, ["sfx"] = randoChoices.Cosmetics.Sfx, ["colors"] = randoChoices.Cosmetics.Colors, ["title"] = randoChoices.Cosmetics.Title }, }; var s = randoSchema; if (s != null) { JsonObject values; lock (randoGate) values = (JsonObject)randoValues.DeepClone(); var eff = s.Effective(values); var rows = new JsonObject(); foreach (var x in s.Settings) { if (x.Legacy) continue; var st = s.StateOf(x, eff); var row = new JsonObject { ["st"] = st switch { RandoState.Open => "open", RandoState.Held => "held", _ => "hidden" }, ["v"] = eff[x.Id]?.DeepClone(), ["show"] = RandoSchema.Show(x, eff[x.Id]), }; if (x.Kind == "number") row["max"] = s.MaxOf(x, eff); if (st == RandoState.Held) row["why"] = "Set by " + string.Join(", ", x.Deps.Select(d => s.Find(d.On)?.Label ?? d.On).Distinct()); rows[x.Id] = row; } o["rows"] = rows; o["preset"] = s.PresetOf(values); o["changed"] = s.ForOotrr(values).Count; if (withSchema) { o["schema"] = new JsonObject { ["prefix"] = s.StringPrefix, ["groups"] = new JsonArray(s.Groups.Select(x => (JsonNode)new JsonObject { ["id"] = x.Id, ["label"] = x.Label, ["tip"] = x.Tip }).ToArray()), ["presets"] = new JsonArray(s.Presets.Select(x => (JsonNode)new JsonObject { ["id"] = x.Id, ["name"] = x.Name, ["tip"] = x.Tip }).ToArray()), ["settings"] = new JsonArray(s.Settings.Where(x => !x.Legacy && x.Kind != "list").Select(x => { var j = new JsonObject { ["id"] = x.Id, ["label"] = x.Label, ["group"] = x.Group, ["kind"] = x.Kind, ["tip"] = x.Tip, ["tag"] = x.Tag, ["unsupported"] = x.Unsupported, }; if (x.Choices.Count > 0) j["choices"] = new JsonArray(x.Choices.Select(c => (JsonNode)new JsonObject { ["id"] = c.Id, ["label"] = c.Label, ["tip"] = c.Tip, ["live"] = x.IsLive(c.Id) }).ToArray()); if (x.Kind == "toggle" && !x.IsLive("true")) j["noOn"] = true; if (x.Kind == "number") { j["min"] = x.Min; j["max"] = x.Max; j["step"] = x.Step; if (x.Times > 0) j["times"] = x.Times; } return (JsonNode)j; }).ToArray()), }; randoSchemaSent = true; } } o["seeds"] = RandoSeedsState(g); o["note"] = g == null ? "Build the game first: seeds go into its mods folder." : ""; return o; } JsonArray RandoSeedsState(string? g) { var arr = new JsonArray(); if (g == null) return arr; List seeds; try { seeds = Rando.Seeds(g); } catch (Exception e) { Log.Write("randomizer: seeds: " + e.Message); return arr; } foreach (var x in seeds.OrderByDescending(x => x.Made ?? DateTime.MinValue)) { var parts = new List { x.Mod.On ? "On" : "Off" }; if (x.Preset.Length > 0) parts.Add(x.Preset); if (x.Made is { } d) parts.Add("made " + d.ToLocalTime().ToString("d MMM yyyy, HH:mm", System.Globalization.CultureInfo.InvariantCulture)); if (x.Version.Length > 0) parts.Add("OOTRR " + x.Version); if (x.Mod.OffAbove != null) parts.Add("off with its folder " + x.Mod.OffAbove); arr.Add(new JsonObject { ["id"] = x.Mod.Rel, ["seed"] = x.Seed, ["on"] = x.Mod.On, ["sub"] = string.Join(" · ", parts), ["settings"] = x.Settings, ["spoiler"] = File.Exists(x.Spoiler), ["cos"] = string.Join(", ", new[] { x.Cosmetics.Music != "off" ? "music " + x.Cosmetics.Music : "", x.Cosmetics.Sfx != "off" ? "sounds " + x.Cosmetics.Sfx : "", x.Cosmetics.Colors != "off" ? "colors " + x.Cosmetics.Colors : "" }.Where(t => t.Length > 0)), }); } return arr; } void SendRando(bool withSchema = false) { JsonObject state; try { state = RandoPageState(withSchema || !randoSchemaSent); } // (the note is text: the page escapes it) catch (Exception e) { Log.Write("randomizer: " + e); state = new JsonObject { ["note"] = e.Message, ["seeds"] = new JsonArray() }; } SendState(new JsonObject { ["rando"] = state }); } void RandoKeep() { // ((Triforce, 11-26) one save at a time: the page's commands run on workers of their own, and two saves wrote one .new file) lock (randoGate) { randoChoices.Values = randoSchema != null ? randoSchema.ForOotrr(randoValues) : randoChoices.Values; try { Rando.SaveChoices(randoChoices); } catch (Exception e) { Log.Write("randomizer: " + e.Message); } } } /// The page opened: the kept choices, and OOTRR's settings once it is installed (read once a run). async Task RandoOpen() { if (!randoLoaded) { randoChoices = Rando.LoadChoices(); if (randoChoices.Seed.Length == 0) randoChoices.Seed = Randomizer.RandomSeed(); randoLoaded = true; } // (a seed stopped by the launcher's close left its hidden build folder: it goes now, while no seed is made) if (GameDir is { } g && Volatile.Read(ref randoMaking) == 0) Rando.LeftOvers(Mods.FolderOf(g)); await RandoLoadSchema(); SendRando(true); } async Task RandoLoadSchema() { if (randoSchema != null || !Rando.Tool.Have) return; // (the page opened twice at once, or the download's end and an open: one read) await randoSchemaGate.WaitAsync(); try { if (randoSchema != null) return; var s = await Rando.SchemaAsync(CancellationToken.None); lock (randoGate) { randoSchema = s; // (the kept values are the ones that differed from the defaults: they go over this release's defaults; the first // time, OOTRR's first preset) randoValues = randoChoices.Values == null && s.Presets.Count > 0 ? s.WithPreset(s.Presets[0].Id) : s.Adopt(randoChoices.Values); randoSchemaV++; randoSchemaError = null; } RandoCheckSoon(); } catch (Exception e) when (e is not OperationCanceledException) { Log.Write("randomizer: settings: " + e); randoSchemaError = e.Message; Toast("The randomizer's settings could not be read: " + H(e.Message), "error"); } finally { randoSchemaGate.Release(); } } /// The seed's text, as typed: no longer than a seed may be, no line breaks. void RandoSeedText(string text) { var t = new string(text.Where(c => !char.IsControl(c)).ToArray()).Trim(); if (t.Length > Randomizer.MaxSeed) { t = t.Substring(0, Randomizer.MaxSeed).Trim(); Toast("A seed is " + Randomizer.MaxSeed + " letters at most: the rest was left out."); } randoChoices.Seed = t; RandoKeep(); SendRando(); } // ---------------- installing OOTRR ---------------- Task RandoInstallAsk() { if (Rando.Tool.Have || randoToolBusy) return Task.CompletedTask; Ask("Get the randomizer", "

Triforce's randomizer is OOTRR, the Ocarina of Time Remake Randomizer by its own team (free software, GPL-3.0, as Triforce is).

" + "

" + H(Rando.Tool.File.Name) + ", " + Size(Rando.Tool.File.Size) + ", is downloaded from its release on GitHub, checked against the fingerprint " + "Triforce knows for it, and unpacked into the launcher's tools folder. It reads your game files on this PC only; nothing is uploaded.

", "rando.install.go", new[] { ("no", "Not now", false), ("go", "Download", true) }); return Task.CompletedTask; } async Task RandoInstall() { if (Rando.Tool.Have || Interlocked.CompareExchange(ref randoInstalling, 1, 0) != 0) return; randoToolBusy = true; randoToolFrac = 0; randoToolLine = "Downloading"; SendRando(); var last = DateTime.MinValue; try { await Rando.Tool.InstallAsync(http, p => { randoToolFrac = p.Fraction; randoToolLine = "Downloading, " + (int)(p.Fraction * 100) + " %"; if ((DateTime.UtcNow - last).TotalMilliseconds < 400) return; last = DateTime.UtcNow; SendRando(); }, CancellationToken.None); randoToolLine = "Reading its settings"; SendRando(); await RandoLoadSchema(); Toast("◆ The randomizer is ready · OOTRR " + H(Ootrr.Version), "success"); Sfx("success"); } catch (Exception e) when (e is OotrrException || e is HttpRequestException || e is IOException || e is UnauthorizedAccessException || e is InvalidOperationException || e is TaskCanceledException || e is NoRoomException || e is InvalidDataException) { Log.Write("randomizer: install: " + e); Toast("The randomizer could not be installed: " + H(e.Message), "error"); } finally { randoToolBusy = false; randoToolLine = ""; Interlocked.Exchange(ref randoInstalling, 0); SendRando(true); } } // ---------------- the settings ---------------- void RandoSet(string? id, JsonNode? value) { var s = randoSchema; if (s == null || id == null || s.Find(id) is not { } x) return; if (x.Legacy) return; var v = RandoSchema.Clean(x, value); if (v == null) { var asked = value is JsonValue jv && jv.TryGetValue(out var sid) ? sid : value?.ToJsonString() ?? ""; Toast(!x.IsLive(asked) ? "OOTRR " + H(Ootrr.Version) + " cannot apply " + H(RandoSchema.Show(x, value)) + " for " + H(x.Label) + " yet." : "That value does not fit " + H(x.Label) + ".", "error"); SendRando(); return; } if (x.Kind == "number" && RandoSchema.Whole(v) is { } n) { JsonObject now; lock (randoGate) now = s.Effective(randoValues); if (n > s.MaxOf(x, now)) v = JsonValue.Create(RandoSchema.Snap(x, s.MaxOf(x, now))); } lock (randoGate) randoValues[id] = v; RandoKeep(); RandoCheckSoon(); SendRando(); } /// Asks OOTRR, a moment after the last change, whether it can make the settings as they are; the card says what it /// refuses and Make the seed waits until it can. void RandoCheckSoon() { var s = randoSchema; if (s == null || !Rando.Tool.Have) return; try { randoCheckCts?.Cancel(); } catch { } var cts = randoCheckCts = new CancellationTokenSource(); JsonObject values; lock (randoGate) values = (JsonObject)randoValues.DeepClone(); _ = Task.Run(async () => { try { await Task.Delay(250, cts.Token); await randoCheckGate.WaitAsync(cts.Token); string? says; try { says = await Rando.CheckAsync(s, values, cts.Token); } finally { randoCheckGate.Release(); } if (cts.IsCancellationRequested) return; if (says != randoProblem) { randoProblem = says; SendRando(); } } catch (OperationCanceledException) { } catch (Exception e) { Log.Write("randomizer: check: " + e.Message); } }); } void RandoPreset(string? id) { var s = randoSchema; if (s == null || id == null || s.Presets.All(p => p.Id != id)) return; lock (randoGate) randoValues = s.WithPreset(id); RandoKeep(); RandoCheckSoon(); var p = s.Presets.First(x => x.Id == id); var gaps = s.Gaps(p.Settings); Toast("Settings: " + H(p.Name) + "" + (gaps.Count == 0 ? "" : " · " + H(string.Join("; ", gaps.Select(g => g.Setting + " is " + g.Gets + " (" + g.Asked + " needs a newer OOTRR)"))))); SendRando(); } void RandoCos(string? key, string? value) { var c = randoChoices.Cosmetics; randoChoices.Cosmetics = (key switch { "music" => c with { Music = value ?? "off" }, "sfx" => c with { Sfx = value ?? "off" }, "colors" => c with { Colors = value ?? "off" }, "title" => c with { Title = value == "on" }, _ => c, }).Clean(); RandoKeep(); SendRando(); } async Task RandoDecode(string text) { var s = randoSchema; if (s == null) { Toast("Get the randomizer first.", "error"); return; } try { var (values, warnings) = await Rando.DecodeAsync(s, text, CancellationToken.None); lock (randoGate) randoValues = values; RandoKeep(); RandoCheckSoon(); Toast(warnings.Count == 0 ? "Settings taken from the string" : "Settings taken from the string · " + H(string.Join("; ", warnings.Take(3))) + (warnings.Count > 3 ? " · and " + (warnings.Count - 3) + " more (the launcher's log has them)" : ""), warnings.Count == 0 ? "success" : null); foreach (var w in warnings) Log.Write("randomizer: settings string: " + w); } catch (OotrrException e) { Toast(H(e.Message), "error"); } SendRando(); } // ---------------- making a seed ---------------- async Task RandoMake() { var s = randoSchema; if (s == null) { Toast("Get the randomizer first.", "error"); return; } if (GameDir is not { } game) { Toast("Build the game first: seeds go into its mods folder.", "error"); return; } // ((Triforce, 11-26) a build or an update rewrites the romfs a seed is made from, and reads the mods folder) if (RefusedWhileBuilding()) { SendRando(); return; } if (Interlocked.CompareExchange(ref randoMaking, 1, 0) != 0) return; try { await RandoMakeOne(s, game); } finally { Interlocked.Exchange(ref randoMaking, 0); } } async Task RandoMakeOne(RandoSchema s, string game) { if (randoChoices.Seed.Length == 0) randoChoices.Seed = Randomizer.RandomSeed(); JsonObject values; lock (randoGate) values = (JsonObject)randoValues.DeepClone(); // (what OOTRR says now, not what an earlier check said: a check may be on its way) string? says; await randoCheckGate.WaitAsync(); try { says = await Rando.CheckAsync(s, values, CancellationToken.None); } catch (Exception e) when (e is OotrrException || e is IOException || e is UnauthorizedAccessException) { says = null; Log.Write("randomizer: check before make: " + e.Message); } finally { randoCheckGate.Release(); } if (says != null) { randoProblem = says; Toast("OOTRR cannot make these settings yet: " + H(says), "error"); SendRando(); return; } var preset = s.Preset(s.PresetOf(values) ?? "")?.Name ?? "Custom"; var used = randoChoices.Seed; using var cts = randoCts = new CancellationTokenSource(); randoLine = "Starting"; SendRando(); var last = DateTime.MinValue; try { var made = await Rando.MakeAsync(game, s, values, used, randoChoices.Cosmetics, l => { randoLine = l; if ((DateTime.UtcNow - last).TotalMilliseconds < 300) return; last = DateTime.UtcNow; SendRando(); }, cts.Token, preset); var wins = made.Shared.Where(x => x.Wins).ToList(); var msg = "◆ Seed " + H(made.Seed.Seed) + " is on · start a new game in an empty file"; if (wins.Count > 0) msg += " · " + H(string.Join(", ", wins.Select(x => x.Name))) + " " + (wins.Count == 1 ? "changes" : "change") + " some of the same files and " + (wins.Count == 1 ? "wins" : "win") + " them (Mods page)"; Toast(msg, "success"); Sfx("success"); // (the next seed gets a new text: the one just used is kept with its seed. One typed while this one was made stays) if (randoChoices.Seed == used) randoChoices.Seed = Randomizer.RandomSeed(); RandoKeep(); SendState(new JsonObject { ["randoMade"] = made.Seed.Mod.Rel }); } catch (OperationCanceledException) { Toast("Stopped · no seed was made"); } catch (Exception e) when (e is OotrrException || e is ModsException || e is IOException || e is UnauthorizedAccessException || e is InvalidOperationException) { Log.Write("randomizer: make: " + e); Toast(H(e.Message), "error"); } finally { randoCts = null; randoLine = ""; SendRando(); RefreshHome(); } } // ---------------- your seeds ---------------- /// The seed text of the seed that is on in a game folder, or null (the home screen's line). string? RandoSeedOn(string game) { try { return Rando.Seeds(game).FirstOrDefault(x => x.Mod.On)?.Seed; } catch (Exception e) { Log.Write("randomizer: " + e.Message); return null; } } RandoSeed? RandoFind(string? id) => id != null && GameDir is { } g ? Rando.Seeds(g).FirstOrDefault(x => x.Mod.Rel == id) : null; void RandoSeedDo(string? id, string what) { if (GameDir is not { } game) return; if (what is "use" or "remove" && RefusedWhileBuilding()) { SendRando(); return; } var x = RandoFind(id); if (x == null) { Toast("That seed is no longer in the mods folder.", "error"); SendRando(); return; } try { switch (what) { case "use": Rando.Use(game, x); Toast("Seed " + H(x.Seed) + " is on · its saves are the ones you make with it on", "success"); break; case "remove": if (randoCts != null) { Toast("Wait for the seed being made.", "error"); return; } Rando.Remove(game, x); Toast("Seed " + H(x.Seed) + " is removed. Its folder is kept in mods" + Path.DirectorySeparatorChar + Mods.Removed + ".", "success"); break; case "copy": if (x.Settings.Length == 0) { Toast("This seed has no settings string.", "error"); return; } Copy(x.Settings); break; case "folder": OpenPlace(x.Mod.Path); break; case "spoiler": RandoOpenFile(x.Spoiler); break; } } catch (Exception e) when (e is ModsException || e is IOException || e is InvalidOperationException) { Toast(H(e.Message), "error"); } SendRando(); if (what is "use" or "remove") RefreshHome(); // (the Play screen says which seed is on) } void RandoAllOff() { if (GameDir is not { } game || RefusedWhileBuilding()) { SendRando(); return; } try { Rando.Off(game); Toast("Every seed is off: the game is the game as it comes", "success"); } catch (Exception e) when (e is ModsException || e is IOException || e is InvalidOperationException) { Toast(H(e.Message), "error"); } SendRando(); RefreshHome(); } /// A text file in the system's own program for it. A test run opens nothing: it says so instead. void RandoOpenFile(string file) { if (!File.Exists(file)) { Toast("That file is not there: " + H(file), "error"); return; } if (ctx.TestRoot != null) { Toast("Test run: no window opens. " + H(file)); Log.Write("open file (test run, not opened): " + file); return; } try { if (OperatingSystem.IsWindows()) System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(file) { UseShellExecute = true })?.Dispose(); else { var si = new System.Diagnostics.ProcessStartInfo(LinuxPlatform.XdgOpen) { UseShellExecute = false }; si.ArgumentList.Add(file); System.Diagnostics.Process.Start(si)?.Dispose(); } } catch (Exception e) { Log.Write("open " + file + ": " + e.Message); Toast("The file could not be opened: " + H(file), "error"); } } }