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.
This commit is contained in:
ruckus7382sfgsgdf
2026-11-28 10:54:41 -06:00
parent 2df08c751e
commit b527e29adb
203 changed files with 18821 additions and 2051 deletions

View File

@@ -0,0 +1,237 @@
// (Triforce) OOTRR, the Ocarina of Time Remake Randomizer (github.com/ootrando/ootrr, GPL-3.0 as Triforce is), as the launcher's
// Randomizer page uses it: one release of its command-line program, downloaded on first use and checked against the SHA-256 this
// file names, then run for its settings (settings-dump), a seed (generate) and the seed's files (build, NX2navi's layout:
// <game>\mods\<name>\romfs, which host/mods.c reads). Nothing of OOTRR is in Triforce's source or its release.
//
// randomizer\ootrr\<version>\ootrr(.exe) the program, with its LICENSE, NOTICE and README, and portable.txt (OOTRR keeps its
// caches in a data folder beside itself, not in the user's profile). Not in tools:
// an update of the tools replaces that folder whole (11-26)
// downloads\ootrr\<release file> the release file while it downloads (Downloader: a stopped download goes on from its .part)
//
// A file whose hash is not the pinned one is deleted and never unpacked; only the program's own few files are taken out of it,
// flat into the folder, so nothing in the archive can reach outside it. Another OOTRR release is another pin here.
using System.Diagnostics;
using System.Formats.Tar;
using System.IO.Compression;
using System.Security.Cryptography;
using System.Text;
namespace Triforce.Logic;
/// <summary>One file of an OOTRR release for one system: its name, size and SHA-256 (from the release's SHA256SUMS.txt, which
/// GitHub's build attestation ties to the tagged source).</summary>
public sealed record OotrrFile(string Name, long Size, string Sha256);
/// <summary>What OOTRR said when it did not do what it was asked: a whole sentence for the page.</summary>
public sealed class OotrrException : Exception
{
/// <summary>The code the program ended with, when it ran and refused; null when it never ran (not installed, not started) or
/// the launcher itself says no.</summary>
public int? Exit { get; }
public OotrrException(string message, int? exit = null) : base(message) { Exit = exit; }
}
/// <summary>A run of the program: its exit code and everything it printed.</summary>
public sealed record OotrrRun(int Exit, string Out, string Err);
public sealed class Ootrr
{
/// <summary>The release the launcher uses. To move to another: its version, and each file's size and SHA-256 from its
/// SHA256SUMS.txt (check them with `gh attestation verify &lt;file&gt; --repo ootrando/ootrr`).</summary>
public const string Version = "0.8.2";
public const string Repo = "https://github.com/ootrando/ootrr";
public static readonly OotrrFile Windows = new("OOTRR-0.8.2-windows-x64-portable.zip", 4694013, "0598aa5f7e3fe93e690437d936456a92c00e6d20b59a9bcd24fb2948afb6fbae");
public static readonly OotrrFile Linux = new("OOTRR-0.8.2-linux-x86_64.tar.gz", 4760078, "715ee19e1c6e2e487e1800106f8694fc7a756ebc725bd1b501e1256959c79136");
/// <summary>The files the launcher takes out of a release (the program by its name on each system; the others as they are).</summary>
static readonly string[] Keep = { "LICENSE", "NOTICE", "README.md", "portable.txt" };
const string Stamp = ".triforce-ootrr";
readonly TriforceContext ctx;
readonly Downloader downloader;
readonly OotrrFile? file;
/// <summary>file: the release file to fetch in place of the pinned one for this system (a test's own).</summary>
public Ootrr(TriforceContext ctx, Downloader? downloader = null, OotrrFile? file = null)
{
this.ctx = ctx;
this.downloader = downloader ?? new Downloader(ctx);
this.file = file;
}
public OotrrFile File => file ?? (ctx.IsWindows ? Windows : Linux);
public string ExeName => ctx.IsWindows ? "ootrr.exe" : "ootrr";
public string Folder => Path.Combine(ctx.Home, Randomizer.WorkFolder, "ootrr", Version);
/// <summary>Where the release file comes from: TRIFORCE_OOTRR_URL over GitHub's release page (a test's own server).</summary>
public string Url => (Env("TRIFORCE_OOTRR_URL") is { } u ? u.TrimEnd('/') : Repo + "/releases/download/v" + Version) + "/" + File.Name;
string? Env(string name) => ctx.Env(name) is { Length: > 0 } v ? v.Trim() : null;
/// <summary>The program to run: TRIFORCE_OOTRR_EXE (a test's or a developer's own: in a test run or a local build only, as it
/// runs any program), else the downloaded one. Null before the download (or when the folder holds a program that is not the
/// pinned release's).</summary>
public string? Exe
{
get
{
if (Env("TRIFORCE_OOTRR_EXE") is { } own && (ctx.TestRoot != null || BuildInfo.IsDev || ctx.Env("TRIFORCE_DEV") == "1"))
return System.IO.File.Exists(own) ? own : null;
var exe = Path.Combine(Folder, ExeName);
return System.IO.File.Exists(exe) && ReadStamp() == File.Sha256 ? exe : null;
}
}
public bool Have => Exe != null;
string? ReadStamp()
{
try { return System.IO.File.ReadAllText(Path.Combine(Folder, Stamp)).Trim(); } catch (Exception) { return null; }
}
/// <summary>Downloads the pinned release file, checks its hash and unpacks the program. progress: 0..1 of the download.</summary>
public async Task InstallAsync(HttpClient http, Action<DownloadProgress>? progress, CancellationToken token)
{
if (Have) return;
var f = File;
var file = Path.Combine(ctx.DownloadsFolder, "ootrr", f.Name);
ctx.Require(file);
ctx.Require(Folder);
await downloader.ToFileAsync(http, Url, file, f.Size, progress, token).ConfigureAwait(false);
string hash;
await using (var s = System.IO.File.OpenRead(file)) hash = Convert.ToHexStringLower(await SHA256.HashDataAsync(s, token).ConfigureAwait(false));
if (hash != f.Sha256)
{
try { System.IO.File.Delete(file); } catch (Exception) { }
throw new OotrrException("The randomizer's download is not the file Triforce expects (its SHA-256 is " + hash + "). It was deleted and nothing was installed. Try again later.");
}
var temp = Folder + ".new";
if (Directory.Exists(temp)) Directory.Delete(temp, true);
Directory.CreateDirectory(temp);
try
{
if (f.Name.EndsWith(".zip", StringComparison.OrdinalIgnoreCase)) UnpackZip(file, temp);
else await UnpackTarGz(file, temp, token).ConfigureAwait(false);
if (!System.IO.File.Exists(Path.Combine(temp, ExeName))) throw new OotrrException("The randomizer's download holds no " + ExeName + ". Nothing was installed.");
// (portable: OOTRR keeps its caches in a data folder beside itself, so removing the folder removes all of it)
var portable = Path.Combine(temp, "portable.txt");
if (!System.IO.File.Exists(portable)) System.IO.File.WriteAllText(portable, "OOTRR portable (written by Triforce's launcher)\n");
System.IO.File.WriteAllText(Path.Combine(temp, Stamp), f.Sha256 + "\n");
if (Directory.Exists(Folder)) Directory.Delete(Folder, true);
Directory.Move(temp, Folder);
}
catch
{
try { Directory.Delete(temp, true); } catch (Exception) { }
throw;
}
try { System.IO.File.Delete(file); } catch (Exception) { }
ctx.Log.Write("randomizer: OOTRR " + Version + " installed in " + Folder);
}
/// <summary>The name a release entry is taken out under (flat, in the folder), or null for an entry that is not kept.</summary>
internal string? KeptName(string entry)
{
var name = entry.Replace('\\', '/').TrimEnd('/');
var depth = name.Count(c => c == '/');
if (depth > 2 || name.Split('/').Any(p => p == ".." || p == ".")) return null;
var leaf = name.Substring(name.LastIndexOf('/') + 1);
if (leaf == ExeName) return leaf;
return Keep.FirstOrDefault(k => string.Equals(k, leaf, StringComparison.OrdinalIgnoreCase));
}
void UnpackZip(string file, string to)
{
using var zip = ZipFile.OpenRead(file);
foreach (var e in zip.Entries)
{
if (e.FullName.EndsWith('/')) continue;
var name = KeptName(e.FullName);
if (name == null) continue;
if (e.Length > 256L << 20) throw new OotrrException("The randomizer's download holds a file far larger than the program. Nothing was installed.");
e.ExtractToFile(Path.Combine(to, name), true);
}
}
async Task UnpackTarGz(string file, string to, CancellationToken token)
{
await using var s = System.IO.File.OpenRead(file);
await using var gz = new GZipStream(s, CompressionMode.Decompress);
using var tar = new TarReader(gz);
for (TarEntry? e; (e = await tar.GetNextEntryAsync(false, token).ConfigureAwait(false)) != null;)
{
if (e.EntryType is not (TarEntryType.RegularFile or TarEntryType.V7RegularFile)) continue;
var name = KeptName(e.Name);
if (name == null || e.DataStream == null) continue;
if (e.Length > 256L << 20) throw new OotrrException("The randomizer's download holds a file far larger than the program. Nothing was installed.");
var path = Path.Combine(to, name);
await using (var o = System.IO.File.Create(path)) await e.DataStream.CopyToAsync(o, token).ConfigureAwait(false);
if (!OperatingSystem.IsWindows() && name == ExeName)
System.IO.File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute |
UnixFileMode.GroupRead | UnixFileMode.GroupExecute | UnixFileMode.OtherRead | UnixFileMode.OtherExecute);
}
}
/// <summary>Removes the downloaded program (the folder of this version, its data folder with it).</summary>
public void Remove()
{
ctx.Require(Folder);
if (Directory.Exists(Folder)) Directory.Delete(Folder, true);
}
// ---------------- running it ----------------
/// <summary>Runs the program with these arguments (each one whole, never through a shell) in its own folder. line: each line
/// it prints, as it prints it. Cancelling ends it. Throws OotrrException when it is not there or ends with an error, with the
/// error it printed.</summary>
public async Task<OotrrRun> RunAsync(IEnumerable<string> args, Action<string>? line, CancellationToken token)
{
var exe = Exe ?? throw new OotrrException("The randomizer is not installed yet.");
var si = new ProcessStartInfo(exe)
{
UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true,
StandardOutputEncoding = Encoding.UTF8, StandardErrorEncoding = Encoding.UTF8,
WorkingDirectory = Path.GetDirectoryName(Path.GetFullPath(exe))!,
};
foreach (var a in args) si.ArgumentList.Add(a);
// (OOTRR's own update check and browser stay off: the launcher runs commands, never its web page)
si.Environment["NO_COLOR"] = "1";
using var p = new Process { StartInfo = si };
var o = new StringBuilder();
var e = new StringBuilder();
// (a line handler that throws is logged: thrown on the reader's thread it would end the launcher)
p.OutputDataReceived += (_, d) =>
{
if (d.Data == null) return;
lock (o) o.AppendLine(d.Data);
try { line?.Invoke(d.Data); } catch (Exception x) { ctx.Log.Write("randomizer: a line of its output was not taken: " + x.Message); }
};
p.ErrorDataReceived += (_, d) => { if (d.Data == null) return; lock (e) e.AppendLine(d.Data); };
try { p.Start(); }
catch (Exception x) when (x is System.ComponentModel.Win32Exception || x is IOException)
{
throw new OotrrException("The randomizer could not be started: " + x.Message);
}
p.BeginOutputReadLine();
p.BeginErrorReadLine();
try { await p.WaitForExitAsync(token).ConfigureAwait(false); }
catch (OperationCanceledException)
{
// (it is gone before the caller takes its folders away: a build still writing would keep files open in them)
try { p.Kill(true); p.WaitForExit(5000); } catch (Exception) { }
throw;
}
p.WaitForExit(); // (the last lines of both streams are read)
var run = new OotrrRun(p.ExitCode, o.ToString(), e.ToString());
if (run.Exit != 0) throw new OotrrException(ErrorOf(run), run.Exit);
return run;
}
/// <summary>What a failed run says: its last line on the error stream that is not a warning, else on its output.</summary>
internal static string ErrorOf(OotrrRun run)
{
static string? Last(string text, bool skipWarnings) => text.Split('\n').Select(l => l.Trim()).Where(l => l.Length > 0 &&
!(skipWarnings && l.StartsWith("warning:", StringComparison.OrdinalIgnoreCase))).LastOrDefault();
var why = Last(run.Err, true) ?? Last(run.Out, false) ?? "it ended with code " + run.Exit;
if (why.StartsWith("error:", StringComparison.OrdinalIgnoreCase)) why = why.Substring(6).Trim();
return "The randomizer stopped: " + why;
}
}

View File

@@ -0,0 +1,301 @@
// (Triforce) OOTRR's settings as its own `settings-dump` describes them, so the Randomizer page draws them as OOTRR has them
// (groups, labels, tips, choices, limits, what each depends on) and is right for whatever release Ootrr.cs pins:
// {schema_version, string_prefix, groups:[{id,label,tip}], settings:[{id,num,label,group,kind,tag,tip,default,choices?,min?,
// max?,max_by?,step?,times?,max_items?,deps:[{on,is|not|in}],disabled?,legacy?,unsupported?}], menu, presets:[{id,name,tip,
// order,settings}]}
// A setting whose dependencies do not hold is either left out (it means nothing then) or, when it names a "disabled" value, held
// at that value. The values the page keeps are a plain map id -> value; what goes to OOTRR (generate's settings file) is the
// values that differ from the defaults, after the held ones. OOTRR's menu (the dump's "menu") marks the options its build cannot
// apply yet ("live": false), its own presets among them in 0.8.2: those values are refused, and a preset or a pasted string that
// asks for one gets the default there, and says so (Gaps).
using System.Text.Json;
using System.Text.Json.Nodes;
namespace Triforce.Logic;
public sealed record RandoGroup(string Id, string Label, string Tip);
public sealed record RandoChoice(string Id, string Label, string Tip);
/// <summary>One dependency: the setting on, and the values it must have (Not: must not have).</summary>
public sealed record RandoDep(string On, bool Not, IReadOnlyList<JsonNode?> Values);
public sealed class RandoSetting
{
public string Id { get; init; } = "";
public int Num { get; init; }
public string Label { get; init; } = "";
public string Group { get; init; } = "";
/// <summary>toggle, choice, multi, number or list.</summary>
public string Kind { get; init; } = "";
public string Tag { get; init; } = "";
public string Tip { get; init; } = "";
public JsonNode? Default { get; init; }
public IReadOnlyList<RandoChoice> Choices { get; init; } = Array.Empty<RandoChoice>();
public long Min { get; init; }
public long Max { get; init; }
public long Step { get; init; } = 1;
public string? MaxBy { get; init; }
/// <summary>A number that stands for a multiple: the value over Times (enemy health 150 with Times 100 is 1.5x). 0: a plain number.</summary>
public long Times { get; init; }
public int MaxItems { get; init; }
public IReadOnlyList<RandoDep> Deps { get; init; } = Array.Empty<RandoDep>();
/// <summary>The value held while the dependencies do not hold (null: the setting is left out then).</summary>
public JsonNode? Disabled { get; init; }
public bool HasDisabled { get; init; }
public bool Legacy { get; init; }
/// <summary>OOTRR's build does not apply it yet (its own menu marks it so).</summary>
public bool Unsupported { get; init; }
/// <summary>Values OOTRR's own menu marks as not working yet in this release (its "live": false options): a choice's id, or
/// "true" / "false" for a toggle. They are refused as values, so no seed asks the build for what it cannot do.</summary>
public IReadOnlySet<string> NotLive { get; init; } = new HashSet<string>();
public bool IsLive(string choice) => !NotLive.Contains(choice);
}
public sealed record RandoPreset(string Id, string Name, string Tip, int Order, JsonObject Settings);
/// <summary>How a setting shows with the values as they are: left out, held at a value (and why), or open.</summary>
public enum RandoState { Hidden, Held, Open }
public sealed class RandoSchema
{
public int Version { get; init; }
public string StringPrefix { get; init; } = "";
public IReadOnlyList<RandoGroup> Groups { get; init; } = Array.Empty<RandoGroup>();
public IReadOnlyList<RandoSetting> Settings { get; init; } = Array.Empty<RandoSetting>();
public IReadOnlyList<RandoPreset> Presets { get; init; } = Array.Empty<RandoPreset>();
public RandoSetting? Find(string id) => Settings.FirstOrDefault(s => s.Id == id);
static string Str(JsonNode? n, string key) => n?[key] is JsonValue v && v.TryGetValue<string>(out var s) ? s : "";
static long Num(JsonNode? n, string key, long otherwise) => n?[key] is JsonValue v && v.TryGetValue<long>(out var x) ? x : otherwise;
static bool Flag(JsonNode? n, string key) => n?[key] is JsonValue v && v.TryGetValue<bool>(out var b) && b;
/// <summary>settings-dump's JSON; FormatException for one without groups or settings.</summary>
public static RandoSchema Parse(string json)
{
JsonNode? root;
try { root = JsonNode.Parse(json); } catch (JsonException e) { throw new FormatException("The randomizer's settings could not be read: " + e.Message); }
if (root?["groups"] is not JsonArray groups || root["settings"] is not JsonArray settings || settings.Count == 0)
throw new FormatException("The randomizer's settings could not be read: no groups or no settings.");
var gs = groups.Select(g => new RandoGroup(Str(g, "id"), Str(g, "label"), Str(g, "tip"))).Where(g => g.Id.Length > 0).ToList();
var dead = new Dictionary<string, HashSet<string>>();
NotLiveIn(root["menu"], dead);
var ss = new List<RandoSetting>();
foreach (var s in settings)
{
if (s == null || Str(s, "id").Length == 0) continue;
var deps = (s["deps"] as JsonArray ?? new JsonArray()).Select(d =>
{
if (d?["in"] is JsonArray any) return new RandoDep(Str(d, "on"), false, any.Select(x => x?.DeepClone()).ToList());
if (d != null && ((JsonObject)d).ContainsKey("not")) return new RandoDep(Str(d, "on"), true, new[] { d["not"]?.DeepClone() });
return new RandoDep(Str(d, "on"), false, new[] { d?["is"]?.DeepClone() });
}).Where(d => d.On.Length > 0).ToList();
var obj = (JsonObject)s;
ss.Add(new RandoSetting
{
Id = Str(s, "id"), Num = (int)Num(s, "num", 0), Label = Str(s, "label"), Group = Str(s, "group"), Kind = Str(s, "kind"),
Tag = Str(s, "tag"), Tip = Str(s, "tip"), Default = s["default"]?.DeepClone(),
Choices = (s["choices"] as JsonArray ?? new JsonArray()).Select(c => new RandoChoice(Str(c, "id"), Str(c, "label"), Str(c, "tip"))).ToList(),
Min = Num(s, "min", 0), Max = Num(s, "max", 0), Step = Math.Max(1, Num(s, "step", 1)), MaxBy = Str(s, "max_by") is { Length: > 0 } mb ? mb : null, Times = Math.Max(0, Num(s, "times", 0)),
MaxItems = (int)Num(s, "max_items", 0), Deps = deps,
HasDisabled = obj.ContainsKey("disabled") && s["disabled"] != null, Disabled = s["disabled"]?.DeepClone(),
Legacy = Flag(s, "legacy"), Unsupported = Flag(s, "unsupported"),
NotLive = dead.TryGetValue(Str(s, "id"), out var nl) ? nl : new HashSet<string>(),
});
}
var ps = (root["presets"] as JsonArray ?? new JsonArray()).Where(p => p?["settings"] is JsonObject)
.Select(p => new RandoPreset(Str(p, "id"), Str(p, "name"), Str(p, "tip"), (int)Num(p, "order", 0), (JsonObject)p!["settings"]!.DeepClone()))
.OrderBy(p => p.Order).ToList();
return new RandoSchema { Version = (int)Num(root, "schema_version", 0), StringPrefix = Str(root, "string_prefix"), Groups = gs, Settings = ss, Presets = ps };
}
/// <summary>The menu's items with a setting's id and a view whose options say "live": false, anywhere in it: id -> those
/// options' values ("ours"; one with none stands for no value of OOTRR's and is not a choice).</summary>
static void NotLiveIn(JsonNode? n, Dictionary<string, HashSet<string>> dead)
{
if (n is JsonArray a) { foreach (var x in a) NotLiveIn(x, dead); return; }
if (n is not JsonObject o) return;
if (Str(o, "id") is { Length: > 0 } id && o["view"]?["opts"] is JsonArray opts)
foreach (var opt in opts)
if (Str(opt, "ours") is { Length: > 0 } ours && opt?["live"] is JsonValue lv && lv.TryGetValue<bool>(out var live) && !live)
(dead.TryGetValue(id, out var set) ? set : dead[id] = new HashSet<string>()).Add(ours);
foreach (var (_, v) in o) NotLiveIn(v, dead);
}
/// <summary>What a map asks for that this release cannot apply yet, or does not know: (the setting's label, the value asked
/// for, the value it gets). For a preset (each value it names) or a settings string read back.</summary>
public List<(string Setting, string Asked, string Gets)> Gaps(JsonObject asked)
{
var o = new List<(string, string, string)>();
foreach (var (k, v) in asked)
if (Find(k) is { } s && !s.Legacy && Clean(s, v) == null)
o.Add((s.Label, Show(s, v), Show(s, s.Default)));
return o;
}
public RandoPreset? Preset(string id) => Presets.FirstOrDefault(p => p.Id == id);
/// <summary>Every setting at its default.</summary>
public JsonObject Defaults()
{
var o = new JsonObject();
foreach (var s in Settings) o[s.Id] = s.Default?.DeepClone();
return o;
}
/// <summary>The defaults with a preset's values over them (a preset names only what it changes).</summary>
public JsonObject WithPreset(string id)
{
var o = Defaults();
var p = Presets.FirstOrDefault(x => x.Id == id) ?? throw new FormatException("The randomizer has no preset " + id + ".");
foreach (var (k, v) in p.Settings) if (Find(k) is { } s) o[k] = Clean(s, v) ?? s.Default?.DeepClone();
return o;
}
/// <summary>A saved map read back against this schema: settings it does not know are dropped, values it would refuse are the
/// defaults, missing ones the defaults.</summary>
public JsonObject Adopt(JsonObject? saved)
{
var o = Defaults();
if (saved == null) return o;
foreach (var (k, v) in saved) if (Find(k) is { } s && Clean(s, v) is { } ok) o[k] = ok;
return o;
}
static bool Same(JsonNode? a, JsonNode? b) => JsonNode.DeepEquals(a, b);
/// <summary>Does one dependency hold for these values?</summary>
static bool Holds(RandoDep d, JsonObject values)
{
var v = values[d.On];
var any = d.Values.Any(x => Same(x, v));
return d.Not ? !any : any;
}
public bool DepsHold(RandoSetting s, JsonObject values) => s.Deps.All(d => Holds(d, values));
/// <summary>How a setting shows with these values (its dependencies read from the values as held, in one pass in order).</summary>
public RandoState StateOf(RandoSetting s, JsonObject values) =>
DepsHold(s, values) ? RandoState.Open : s.HasDisabled ? RandoState.Held : RandoState.Hidden;
/// <summary>The values as OOTRR takes them: each held setting at its held value.</summary>
public JsonObject Effective(JsonObject values)
{
var o = (JsonObject)values.DeepClone();
// (a held value can make another's dependency fail: a few passes settle it, as the chain is short)
for (var pass = 0; pass < 4; pass++)
{
var changed = false;
foreach (var s in Settings)
if (s.HasDisabled && !DepsHold(s, o) && !Same(o[s.Id], s.Disabled)) { o[s.Id] = s.Disabled?.DeepClone(); changed = true; }
if (!changed) break;
}
// (a number no higher than another's value (max_by) comes down to it, on its own step, when that one is lower now: the
// value kept goes back up with it)
foreach (var s in Settings)
if (s.Kind == "number" && s.MaxBy != null && Whole(o[s.Id]) is { } n && n > MaxOf(s, o))
o[s.Id] = JsonValue.Create(Snap(s, MaxOf(s, o)));
return o;
}
/// <summary>The highest value on a number's step that is not above v (and not below its minimum).</summary>
public static long Snap(RandoSetting s, long v) => Math.Max(s.Min, s.Min + (long)Math.Floor((v - s.Min) / (double)Math.Max(1, s.Step)) * Math.Max(1, s.Step));
/// <summary>The settings file for generate: the effective values that differ from the defaults (legacy settings left out).</summary>
public JsonObject ForOotrr(JsonObject values)
{
var eff = Effective(values);
var o = new JsonObject();
// (a setting left out with the values as they are means nothing: it is not told, so it goes back to its default)
foreach (var s in Settings)
if (!s.Legacy && StateOf(s, eff) != RandoState.Hidden && eff[s.Id] is var v && !Same(v, s.Default)) o[s.Id] = v?.DeepClone();
return o;
}
/// <summary>The highest value a number may take with these values (max_by: no higher than another setting's value).</summary>
public long MaxOf(RandoSetting s, JsonObject values) =>
s.MaxBy != null && Whole(values[s.MaxBy]) is { } by ? Math.Min(s.Max, by) : s.Max;
/// <summary>A JSON number that is a whole number (5 or 5.0), whatever .NET type holds it; null for anything else.</summary>
public static long? Whole(JsonNode? v)
{
if (v is not JsonValue jv || jv.GetValueKind() != JsonValueKind.Number) return null;
var text = jv.ToJsonString();
if (long.TryParse(text, System.Globalization.NumberStyles.AllowLeadingSign, System.Globalization.CultureInfo.InvariantCulture, out var l)) return l;
return double.TryParse(text, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var d) &&
Math.Abs(d - Math.Round(d)) < 1e-9 && Math.Abs(d) < 1e15 ? (long)Math.Round(d) : null;
}
/// <summary>A value for a setting, as the setting takes it, or null when it does not (a toggle takes true or false; a choice one of
/// its ids; multi a list of its ids, each once; a number a whole number in its range and step; a list strings, so many at most).</summary>
public static JsonNode? Clean(RandoSetting s, JsonNode? v)
{
switch (s.Kind)
{
case "toggle":
return v is JsonValue b && b.TryGetValue<bool>(out var on) && s.IsLive(on ? "true" : "false") ? JsonValue.Create(on) : null;
case "choice":
return v is JsonValue c && c.TryGetValue<string>(out var id) && s.Choices.Any(x => x.Id == id) && s.IsLive(id) ? JsonValue.Create(id) : null;
case "multi":
if (v is not JsonArray m) return null;
var picked = new List<string>();
foreach (var x in m)
{
if (x is not JsonValue xv || !xv.TryGetValue<string>(out var xid) || !s.Choices.Any(ch => ch.Id == xid)) return null;
if (!picked.Contains(xid)) picked.Add(xid);
}
// (in the order OOTRR lists them, so a map compares equal whichever order they were ticked in)
return new JsonArray(s.Choices.Where(ch => picked.Contains(ch.Id)).Select(ch => (JsonNode?)JsonValue.Create(ch.Id)).ToArray());
case "number":
if (Whole(v) is not { } n || n < s.Min || n > s.Max || (n - s.Min) % s.Step != 0) return null;
return JsonValue.Create(n);
case "list":
if (v is not JsonArray a || a.Count > Math.Max(0, s.MaxItems)) return null;
var items = new JsonArray();
foreach (var x in a)
{
if (x is not JsonValue xv || !xv.TryGetValue<string>(out var t) || t.Length == 0 || t.Length > 200) return null;
items.Add(t);
}
return items;
default:
return null;
}
}
/// <summary>A value as the page shows it in a row: On / Off, a choice's label, the labels ticked (or None), the number.</summary>
public static string Show(RandoSetting s, JsonNode? v)
{
switch (s.Kind)
{
case "toggle": return v is JsonValue b && b.TryGetValue<bool>(out var on) && on ? "On" : "Off";
case "choice":
var id = v is JsonValue c && c.TryGetValue<string>(out var x) ? x : "";
return s.Choices.FirstOrDefault(ch => ch.Id == id)?.Label ?? id;
case "multi":
case "list":
var ids = (v as JsonArray ?? new JsonArray()).Select(n => n is JsonValue nv && nv.TryGetValue<string>(out var t) ? t : "").Where(t => t.Length > 0).ToList();
if (ids.Count == 0) return "None";
var labels = ids.Select(i => s.Choices.FirstOrDefault(ch => ch.Id == i)?.Label ?? i).ToList();
return labels.Count <= 3 ? string.Join(", ", labels) : string.Join(", ", labels.Take(2)) + " and " + (labels.Count - 2) + " more";
case "number": return Whole(v) is { } n ? Number(s, n) : v?.ToJsonString() ?? "";
default: return v?.ToJsonString() ?? "";
}
}
/// <summary>A number as the page shows it: a multiple as 1.5x, else the number.</summary>
public static string Number(RandoSetting s, long n) =>
s.Times > 0 ? (n / (double)s.Times).ToString("0.##", System.Globalization.CultureInfo.InvariantCulture) + "×" : n.ToString(System.Globalization.CultureInfo.InvariantCulture);
/// <summary>The preset these values are, or null (Custom).</summary>
public string? PresetOf(JsonObject values)
{
var eff = Effective(values);
foreach (var p in Presets)
{
var want = Effective(WithPreset(p.Id));
// (what either leaves out does not count)
if (Settings.All(s => StateOf(s, eff) == RandoState.Hidden && StateOf(s, want) == RandoState.Hidden || Same(eff[s.Id], want[s.Id]))) return p.Id;
}
return null;
}
}

View File

@@ -0,0 +1,382 @@
// (Triforce) The Randomizer page's seeds: made with OOTRR (Ootrr.cs) from the built game folder's own romfs and put in its mods
// folder as one mod each, so the game, the Mods page and a player arranging folders by hand all see the same thing:
// <game>\mods\Randomizer <seed>\romfs\... the seed's game files (OOTRR's build, NX2navi's layout)
// <game>\mods\Randomizer <seed>\ootrr\seed.ootrr the seed file (its settings string inside), spoiler.txt, settings.json
// <game>\mods\Randomizer <seed>\triforce_rando.json what the page lists it by: seed, settings string, OOTRR's version
// <game>\mods\Randomizer <seed>\triforce_mod.json its name, author and page on the Mods page
// The game reads only romfs (and exefs, cheats) under a mod, so the other files lie there unread. One seed is on at a time: making
// or choosing one switches the others off (ModManager's rename, "-" in front). Nothing is made while the game runs.
using System.Security.Cryptography;
using System.Text.Json;
using System.Text.Json.Nodes;
namespace Triforce.Logic;
/// <summary>The cosmetics OOTRR applies at build time (its --music, --sfx, --colors, --no-title-logo).</summary>
public sealed record RandoCosmetics(string Music = "off", string Sfx = "off", string Colors = "off", bool Title = true)
{
public static readonly string[] Shuffles = { "off", "grouped", "anywhere" };
public static readonly string[] ColorModes = { "off", "random" };
public RandoCosmetics Clean() => new(Shuffles.Contains(Music) ? Music : "off", Shuffles.Contains(Sfx) ? Sfx : "off", ColorModes.Contains(Colors) ? Colors : "off", Title);
}
/// <summary>A seed in the mods folder.</summary>
public sealed record RandoSeed(Mod Mod, string Seed, string Settings, string Version, DateTime? Made, RandoCosmetics Cosmetics, string Preset = "")
{
public string Files => Path.Combine(Mod.Path, Randomizer.FilesFolder);
public string Spoiler => Path.Combine(Files, "spoiler.txt");
public string SeedFile => Path.Combine(Files, "seed.ootrr");
}
/// <summary>A seed just made: it, and the mods that are on and carry some of its files (Wins: that mod sorts after it, so the game
/// takes that mod's copy).</summary>
public sealed record RandoMade(RandoSeed Seed, IReadOnlyList<(string Name, int Files, bool Wins)> Shared);
/// <summary>What the page keeps between runs: the settings, the seed text and the cosmetics (randomizer\choices.json in the launcher's folder).</summary>
public sealed class RandoChoices
{
public JsonObject? Values { get; set; }
public string Seed { get; set; } = "";
public RandoCosmetics Cosmetics { get; set; } = new();
}
public sealed class Randomizer
{
public const string Marker = "triforce_rando.json";
public const string FilesFolder = "ootrr";
public const string Prefix = "Randomizer ";
readonly TriforceContext ctx;
public Ootrr Tool { get; }
public ModManager Manager { get; }
public Randomizer(TriforceContext ctx, Ootrr? tool = null, ModManager? mods = null)
{
this.ctx = ctx;
Tool = tool ?? new Ootrr(ctx);
Manager = mods ?? new ModManager(ctx);
}
// ---------------- the settings OOTRR has ----------------
/// <summary>OOTRR's settings, from the installed program (settings-dump).</summary>
public async Task<RandoSchema> SchemaAsync(CancellationToken token)
{
var run = await Tool.RunAsync(new[] { "settings-dump", "--compact" }, null, token).ConfigureAwait(false);
return RandoSchema.Parse(run.Out);
}
/// <summary>A settings string (OOTRR1-...) read by OOTRR into values over the defaults, and what it warned about.</summary>
public async Task<(JsonObject Values, IReadOnlyList<string> Warnings)> DecodeAsync(RandoSchema schema, string text, CancellationToken token)
{
text = text.Trim();
if (text.Length == 0 || text.Length > 4000 || text.Any(char.IsWhiteSpace))
throw new OotrrException("That is not a settings string: one comes as a single word that starts with " + (schema.StringPrefix.Length > 0 ? schema.StringPrefix : "OOTRR") + ".");
var run = await Tool.RunAsync(new[] { "settings-dump", "--decode", text, "--compact" }, null, token).ConfigureAwait(false);
JsonNode? root;
try { root = JsonNode.Parse(run.Out); } catch (JsonException) { throw new OotrrException("The randomizer's answer could not be read."); }
var warnings = (root?["warnings"] as JsonArray ?? new JsonArray()).Select(w => w?.ToString() ?? "").Where(w => w.Length > 0).ToList();
var raw = root?["settings"] as JsonObject;
// (what this OOTRR cannot apply yet, or would refuse: the default there, and said)
if (raw != null) warnings.AddRange(schema.Gaps(raw).Select(g => g.Setting + ": " + g.Asked + " cannot be used with OOTRR " + Ootrr.Version + ", so it is " + g.Gets));
return (schema.Adopt(raw), warnings);
}
string? checkedFor, checkedSays;
/// <summary>Can OOTRR make a seed with these settings? It places a throwaway seed (a fraction of a second: generate only, no
/// build), so what it refuses is said before anything is written: null when it can, else what it says, in the settings' own
/// words (Friendly). OOTRR 0.8.2 refuses three of its own five presets this way. The answer is kept for the same settings, when
/// OOTRR gave one: a program that could not be run throws (OotrrException without Exit) and is asked again next time.</summary>
public async Task<string?> CheckAsync(RandoSchema schema, JsonObject values, CancellationToken token)
{
var settings = schema.ForOotrr(values).ToJsonString();
if (settings == checkedFor) return checkedSays;
var work = Path.Combine(ctx.Home, WorkFolder, "check");
ctx.Require(work);
Directory.CreateDirectory(work);
var file = Path.Combine(work, "settings.json");
await File.WriteAllTextAsync(file, settings, token).ConfigureAwait(false);
string? says = null;
try { await Tool.RunAsync(new[] { "generate", file, "check", Path.Combine(work, "check.ootrr") }, null, token).ConfigureAwait(false); }
catch (OotrrException e) when (e.Exit != null) { says = Friendly(schema, e.Message.StartsWith("The randomizer stopped: ", StringComparison.Ordinal) ? e.Message.Substring(24) : e.Message); }
(checkedFor, checkedSays) = (settings, says);
return says;
}
static readonly System.Text.RegularExpressions.Regex IsValue = new(@"\b([a-z][a-z0-9_]*) is ([a-z0-9_]+)", System.Text.RegularExpressions.RegexOptions.CultureInvariant);
static readonly System.Text.RegularExpressions.Regex Only = new(@"\(only ([a-z0-9_, ]+?) (and ([a-z0-9_]+) )?(works?)\)", System.Text.RegularExpressions.RegexOptions.CultureInvariant);
/// <summary>OOTRR's "bridge is stones, which this build cannot apply yet (only vanilla and dungeons work)" with the setting's and
/// its choices' labels: "Rainbow Bridge is Stones, which ... (only Vanilla and Rewards work)".</summary>
public static string Friendly(RandoSchema schema, string message)
{
var m = IsValue.Match(message);
if (!m.Success || schema.Find(m.Groups[1].Value) is not { } s) return message;
string Label(string id) => s.Choices.FirstOrDefault(c => c.Id == id.Trim())?.Label ?? id.Trim();
var o = message.Substring(0, m.Index) + s.Label + " is " + Label(m.Groups[2].Value) + message.Substring(m.Index + m.Length);
return Only.Replace(o, x =>
{
var list = x.Groups[1].Value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Select(Label).ToList();
if (x.Groups[3].Success) list.Add(Label(x.Groups[3].Value));
return "(only " + (list.Count > 1 ? string.Join(", ", list.Take(list.Count - 1)) + " and " + list[^1] : list.FirstOrDefault() ?? "") + " " + x.Groups[4].Value + ")";
});
}
// ---------------- what the page keeps ----------------
/// <summary>The launcher's own folder for the randomizer (in its folder, beside tools: Uninstaller.OwnFolders): the kept choices,
/// the check's throwaway seed, each seed's work while it is made.</summary>
public const string WorkFolder = "randomizer";
string ChoicesFile => Path.Combine(ctx.Home, WorkFolder, "choices.json");
public RandoChoices LoadChoices()
{
try
{
if (!File.Exists(ChoicesFile)) return new RandoChoices();
// (a file that is not an object of objects, written by hand or cut short, is no choices: the defaults)
if (JsonNode.Parse(File.ReadAllText(ChoicesFile)) is not JsonObject root) return new RandoChoices();
var cos = root["cosmetics"] as JsonObject;
string S(JsonObject? n, string k, string otherwise) => n?[k] is JsonValue v && v.TryGetValue<string>(out var s) ? s : otherwise;
return new RandoChoices
{
Values = root["values"] as JsonObject is { } vals ? (JsonObject)vals.DeepClone() : null,
Seed = S(root, "seed", "") is var seed && seed.Length <= MaxSeed && !seed.Any(char.IsControl) ? seed.Trim() : "",
Cosmetics = new RandoCosmetics(S(cos, "music", "off"), S(cos, "sfx", "off"), S(cos, "colors", "off"),
!(cos?["title"] is JsonValue t && t.TryGetValue<bool>(out var on) && !on)).Clean(),
};
}
catch (Exception e) when (e is IOException || e is JsonException || e is UnauthorizedAccessException || e is InvalidOperationException)
{
ctx.Log.Write("randomizer: " + ChoicesFile + " could not be read: " + e.Message);
return new RandoChoices();
}
}
public void SaveChoices(RandoChoices c)
{
if (ctx.NoWrites || !ctx.Allowed(ChoicesFile)) return;
var o = new JsonObject
{
["values"] = c.Values?.DeepClone(),
["seed"] = c.Seed,
["cosmetics"] = new JsonObject { ["music"] = c.Cosmetics.Music, ["sfx"] = c.Cosmetics.Sfx, ["colors"] = c.Cosmetics.Colors, ["title"] = c.Cosmetics.Title },
};
try
{
Directory.CreateDirectory(Path.GetDirectoryName(ChoicesFile)!);
var tmp = ChoicesFile + ".new";
File.WriteAllText(tmp, o.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));
File.Move(tmp, ChoicesFile, true);
}
catch (Exception e) when (e is IOException || e is UnauthorizedAccessException) { ctx.Log.Write("randomizer: choices not kept: " + e.Message); }
}
// ---------------- seeds ----------------
/// <summary>A seed text for a new seed: eight letters and digits that read clearly (no 0/O, 1/I).</summary>
public static string RandomSeed()
{
const string abc = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
return string.Concat(Enumerable.Range(0, 8).Select(_ => abc[RandomNumberGenerator.GetInt32(abc.Length)]));
}
/// <summary>A seed text as a folder may carry it (OOTRR takes a mod name of letters, digits, space, _ - ! . and at most 64 of them;
/// the game leaves out a folder that starts with - or _).</summary>
public static string FolderName(string seed)
{
var chars = seed.Trim().Select(c => char.IsAsciiLetterOrDigit(c) || c == '-' || c == '!' ? c : c == ' ' || c == '_' || c == '.' ? ' ' : '-').ToArray();
var clean = string.Join(" ", new string(chars).Split(' ', StringSplitOptions.RemoveEmptyEntries)).Trim('-', ' ');
while (clean.Contains("--")) clean = clean.Replace("--", "-");
if (clean.Length == 0) clean = "seed";
var name = Prefix + clean;
return name.Length <= 60 ? name : name.Substring(0, 60).TrimEnd(' ', '-');
}
/// <summary>A folder name for a new seed that no folder of the mods folder has yet, on or off (" 2", " 3" ... after it).</summary>
internal static string FreeName(string mods, string name)
{
bool Taken(string n) => new[] { n, "-" + n, "_" + n }.Any(x => Directory.Exists(Path.Combine(mods, x)) || File.Exists(Path.Combine(mods, x)));
if (!Taken(name)) return name;
for (var k = 2; ; k++) if (!Taken(name + " " + k)) return name + " " + k;
}
/// <summary>The seeds in a game folder's mods folder, in the game's order.</summary>
public List<RandoSeed> Seeds(string game)
{
var list = new List<RandoSeed>();
foreach (var m in Manager.ListGame(game, false))
if (Read(m) is { } s) list.Add(s);
return list;
}
static RandoSeed? Read(Mod m)
{
try
{
var file = Path.Combine(m.Path, Marker);
if (!File.Exists(file)) return null;
if (JsonNode.Parse(File.ReadAllText(file)) is not JsonObject r) return null;
// (the file lies in a folder anyone can write to: its texts are kept short, and the cosmetics are only the known ones)
string S(string k, int max = 400) => r[k] is JsonValue v && v.TryGetValue<string>(out var s) ? (s.Length <= max ? s : s.Substring(0, max)) : "";
DateTime? made = DateTime.TryParse(S("made"), null, System.Globalization.DateTimeStyles.RoundtripKind, out var d) ? d : null;
return new RandoSeed(m, S("seed", MaxSeed), S("settings", 8000), S("ootrr", 40), made,
new RandoCosmetics(S("music"), S("sfx"), S("colors"), !(r["title"] is JsonValue t && t.TryGetValue<bool>(out var on) && !on)).Clean(), S("preset", 80));
}
catch (Exception e) when (e is IOException || e is JsonException || e is UnauthorizedAccessException || e is InvalidOperationException) { return null; }
}
static readonly string[] RomfsNeeds = { "Pack", "Banc", "Event", "System" };
/// <summary>The folder a seed is built in before it gets its name: a dot in front, so neither the game (host/mods.c) nor the
/// Mods page looks at it. A build stopped by anything (Stop, the launcher closed, the PC off) leaves only such a folder, and
/// the next seed takes it away: a half-made seed is never one the game loads.</summary>
public const string Making = ".making-";
/// <summary>The room a seed needs in the mods folder (a seed is 80 to 90 MB; with music or sounds shuffled, more).</summary>
public const long Room = 400L << 20;
/// <summary>The longest seed text taken.</summary>
public const int MaxSeed = 200;
/// <summary>Makes a seed and puts it in the game's mods folder, on, with every other seed off. preset: the name its settings
/// go by (a preset's, or Custom), kept with it. progress: a line for the page as OOTRR works.</summary>
public async Task<RandoMade> MakeAsync(string game, RandoSchema schema, JsonObject values, string seed, RandoCosmetics cos, Action<string>? progress, CancellationToken token, string? preset = null)
{
seed = seed.Trim();
if (seed.Length == 0) seed = RandomSeed();
if (seed.Length > MaxSeed) throw new OotrrException("That seed is too long: " + MaxSeed + " letters at most.");
if (seed.Any(char.IsControl)) throw new OotrrException("A seed cannot hold line breaks or other control characters.");
cos = cos.Clean();
var romfs = Path.Combine(game, "romfs");
if (!RomfsNeeds.All(d => Directory.Exists(Path.Combine(romfs, d))))
throw new OotrrException("The game folder has no complete romfs folder, which the randomizer reads. Build the game again first.");
if (Manager.GameRuns(game)) throw new OotrrException("Close the game first: it reads its mods when it starts.");
if (!Tool.Have) throw new OotrrException("The randomizer is not installed yet.");
var mods = Mods.FolderOf(game);
ctx.Require(mods);
Directory.CreateDirectory(mods);
if (ctx.SpaceProblem("The seed", Room, mods) is { } room) throw new OotrrException(room);
LeftOvers(mods);
var staging = Making + Guid.NewGuid().ToString("N").Substring(0, 10);
var building = Path.Combine(mods, staging);
var work = Path.Combine(ctx.Home, WorkFolder, "work", Guid.NewGuid().ToString("N").Substring(0, 12));
ctx.Require(work);
Directory.CreateDirectory(work);
string folder;
try
{
var settingsFile = Path.Combine(work, "settings.json");
var seedFile = Path.Combine(work, "seed.ootrr");
var spoiler = Path.Combine(work, "spoiler.txt");
await File.WriteAllTextAsync(settingsFile, schema.ForOotrr(values).ToJsonString(new JsonSerializerOptions { WriteIndented = true }), token).ConfigureAwait(false);
progress?.Invoke("Placing the items");
await Tool.RunAsync(new[] { "generate", settingsFile, seed, seedFile, "--spoiler", spoiler }, null, token).ConfigureAwait(false);
if (!File.Exists(seedFile)) throw new OotrrException("The randomizer made no seed file.");
string settingsString = "", generator = "";
try
{
var sf = JsonNode.Parse(await File.ReadAllTextAsync(seedFile, token).ConfigureAwait(false));
settingsString = sf?["settings"]?.ToString() ?? "";
generator = sf?["generator"]?.ToString() ?? "";
}
catch (JsonException) { }
progress?.Invoke("Writing the seed's game files");
var args = new List<string> { "build", seedFile, romfs, mods, staging, "--host", "nx2navi", "--music", cos.Music, "--sfx", cos.Sfx, "--colors", cos.Colors };
if (!cos.Title) args.Add("--no-title-logo");
await Tool.RunAsync(args, l => { if (l.Trim() is { Length: > 0 } t && t.Length < 200) progress?.Invoke(t); }, token).ConfigureAwait(false);
if (!Directory.Exists(Path.Combine(building, "romfs")) || !Directory.EnumerateFiles(Path.Combine(building, "romfs"), "*", SearchOption.AllDirectories).Any())
throw new OotrrException("The randomizer wrote no game files for the seed.");
// (an empty exefs folder from the build carries nothing: it goes, so the Mods page does not list one)
var exefs = Path.Combine(building, "exefs");
if (Directory.Exists(exefs) && !Directory.EnumerateFileSystemEntries(exefs).Any()) Directory.Delete(exefs);
var files = Path.Combine(building, FilesFolder);
Directory.CreateDirectory(files);
File.Copy(seedFile, Path.Combine(files, "seed.ootrr"), true);
File.Copy(settingsFile, Path.Combine(files, "settings.json"), true);
if (File.Exists(spoiler)) File.Copy(spoiler, Path.Combine(files, "spoiler.txt"), true);
var opts = new JsonSerializerOptions { WriteIndented = true, Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping };
await File.WriteAllTextAsync(Path.Combine(building, Marker), new JsonObject
{
["seed"] = seed, ["settings"] = settingsString, ["ootrr"] = Ootrr.Version, ["generator"] = generator, ["preset"] = preset ?? "",
["made"] = DateTime.UtcNow.ToString("o"), ["music"] = cos.Music, ["sfx"] = cos.Sfx, ["colors"] = cos.Colors, ["title"] = cos.Title,
}.ToJsonString(opts), token).ConfigureAwait(false);
await File.WriteAllTextAsync(Path.Combine(building, "triforce_mod.json"), new JsonObject
{
["name"] = "Randomizer · " + seed, ["author"] = "OOTRR " + Ootrr.Version, ["page"] = Ootrr.Repo,
}.ToJsonString(opts), token).ConfigureAwait(false);
token.ThrowIfCancellationRequested();
// (whole, it gets its name, off: "-" in front. Use then switches the other seeds off before this one on, so the game
// never finds two seeds on, even when a folder cannot be renamed. A folder of that name made meanwhile: the next free one)
folder = Path.Combine(mods, "-" + FreeName(mods, FolderName(seed)));
Directory.Move(building, folder);
}
finally
{
if (Directory.Exists(building))
try { Directory.Delete(building, true); } catch (Exception e) { ctx.Log.Write("randomizer: half-made " + building + " left (the game does not read it): " + e.Message); }
try { Directory.Delete(work, true); } catch (Exception) { }
}
var mine = Manager.ListGame(game, false).FirstOrDefault(m => SamePlace(m.Path, folder))
?? throw new OotrrException("The seed's folder is not where it was written: " + folder);
var s = Read(mine) ?? throw new OotrrException("The seed's folder has no " + Marker + ".");
string on;
try { on = Use(game, s); }
catch (Exception e) when (e is ModsException || e is IOException || e is UnauthorizedAccessException)
{
ctx.Log.Write("randomizer: seed " + seed + " made in " + folder + ", left off: " + e.Message);
throw new OotrrException("Seed " + seed + " is made, but it stays off: " + e.Message + " Turn it on in Your seeds once that is fixed.");
}
ctx.Log.Write("randomizer: seed " + seed + " made in " + on);
var now = Seeds(game).FirstOrDefault(x => SamePlace(x.Mod.Path, on)) ?? throw new OotrrException("The seed's folder is not where it was switched on: " + on);
return new RandoMade(now, Shared(game, now.Mod.Rel));
}
static bool SamePlace(string a, string b) =>
string.Equals(Path.GetFullPath(a).TrimEnd('\\', '/'), Path.GetFullPath(b).TrimEnd('\\', '/'), OperatingSystem.IsWindows() ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal);
/// <summary>Takes away what a stopped build left in the mods folder (.making-*): never a folder the game reads. The page calls
/// it when it opens (while no seed is made), Make before each seed.</summary>
public void LeftOvers(string mods)
{
if (!ctx.Allowed(mods) || !Directory.Exists(mods)) return;
try
{
foreach (var d in Directory.GetDirectories(mods, Making + "*"))
try { Directory.Delete(d, true); ctx.Log.Write("randomizer: a stopped build's " + d + " taken away"); }
catch (Exception e) { ctx.Log.Write("randomizer: " + d + " could not be taken away: " + e.Message); }
}
catch (Exception e) when (e is IOException || e is UnauthorizedAccessException) { }
}
/// <summary>The mods that are on and carry some of a seed's files, and whether each wins them.</summary>
public IReadOnlyList<(string Name, int Files, bool Wins)> Shared(string game, string rel)
{
var on = Manager.ListGame(game, true).Where(m => m.On).ToList();
var mod = on.FirstOrDefault(m => m.Rel == rel);
if (mod == null) return Array.Empty<(string, int, bool)>();
// (Mods.Shared says whether the seed wins; here it is whether the other mod does)
return Mods.Shared(mod, on, Mods.Conflicts(on)).Select(x => (x.Other.Info?.Name is { Length: > 0 } n ? n : x.Other.Name, x.Files, !x.Wins)).ToList();
}
/// <summary>Switches a seed on and every other seed off, the others first: a rename that fails leaves no two seeds on. Returns
/// the seed's folder now.</summary>
public string Use(string game, RandoSeed seed)
{
var mods = Mods.FolderOf(game);
foreach (var other in Seeds(game).Where(x => x.Mod.On && x.Mod.Rel != seed.Mod.Rel)) Manager.SetOn(mods, other.Mod, false);
// (switching the others off renames only their folders: this one is where it was)
var now = Seeds(game).FirstOrDefault(x => x.Mod.Rel == seed.Mod.Rel) ?? seed;
return now.Mod.On ? now.Mod.Path : Manager.SetOn(mods, now.Mod, true);
}
/// <summary>Switches every seed off: the game is the plain game again.</summary>
public void Off(string game)
{
var mods = Mods.FolderOf(game);
foreach (var s in Seeds(game).Where(x => x.Mod.On)) Manager.SetOn(mods, s.Mod, false);
}
/// <summary>Takes a seed out: its folder goes to mods\.removed, as the Mods page's Remove does.</summary>
public void Remove(string game, RandoSeed seed) => Manager.Remove(Mods.FolderOf(game), seed.Mod);
}