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,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);
}