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

@@ -60,20 +60,32 @@ public sealed partial class Backend
"bench.go", new[] { ("no", "Not now", false), ("helpers", "With the helper-thread test", false), ("go", "Start", true) });
}
// ((Triforce, 11-26) 1 while a run is on its way: two clicks on Start ran two, and the second backed up the options the
// first had already changed, so the player's own settings were not put back)
int benchBusy;
async Task RunBench(bool compare, bool helperTest = false)
{
var g = GameDir;
if (g == null || benchCts != null) return;
if (g == null) return;
if (compare && benchRun == null) return;
using var cts = benchCts = new CancellationTokenSource();
var pic = new Saves(ctx).Newest(g) is { } newest ? SavePicUrl(newest) : null;
if (Interlocked.CompareExchange(ref benchBusy, 1, 0) != 0) return;
try { await RunBenchOne(g, compare, helperTest); }
finally { Interlocked.Exchange(ref benchBusy, 0); }
}
async Task RunBenchOne(string g, bool compare, bool helperTest)
{
var bm = new Benchmark(ctx);
(int, string)? second = null;
// (before the run is marked as running: a refusal here left benchCts set, and the page showed an empty run for good)
if (compare)
{
second = benchSecond ?? bm.SecondPass(g, BenchIni.Read(Path.Combine(g, GameOptionsSchema.FileName)));
if (second == null) { Toast("You already use an upscaler: there is nothing to compare it with.", "error"); return; }
}
using var cts = benchCts = new CancellationTokenSource();
var pic = new Saves(ctx).Newest(g) is { } newest ? SavePicUrl(newest) : null;
var t0 = DateTime.UtcNow;
void Running(string line) => Send(new JsonObject
{

View File

@@ -21,6 +21,13 @@ public sealed partial class Backend
// the working screen
CancellationTokenSource? workCts;
// ((Triforce, 11-26) 1 from the click that starts a build, a rebuild or an update until it ends: each command runs on a
// worker of its own, so a double click (or Enter held on Build the game) started two builds into one folder, and Stop
// reached only one. Taken with TakeWork, before anything else is done)
int workBusy;
bool TakeWork() => Interlocked.CompareExchange(ref workBusy, 1, 0) == 0;
void FreeWork() => Interlocked.Exchange(ref workBusy, 0);
int playStarting;
BuildRunner? runner;
string? workKind; // "build" | "update"
Func<Task>? retry;
@@ -72,12 +79,13 @@ public sealed partial class Backend
var d = new Dlss(ctx);
if (d.Chosen) { d.TurnOff(); SendReveal(); break; }
Ask("NVIDIA DLSS", "<p>" + H(d.LicenseText).Replace("\n\n", "</p><p>").Replace("\n", "<br>") + "</p>", "dlssanswer",
new[] { ("no", "Leave it out", false), ("yes", Dlss.AcceptLabel, true) });
new[] { ("no", "Leave it out", false), ("yes", Dlss.AcceptLabel, true) }, AskKey(ref dlssKey));
break;
}
});
On("lang", m => { if ((string?)m["id"] is { } code) { ctx.Settings.Language = code; SendReveal(); } });
On("dlssanswer", m => { if ((string?)m["id"] == "yes") new Dlss(ctx).Accept(); SendReveal(); });
// (only a language the game has: the code goes to the registry or builder.ini, which other programs read)
On("lang", m => { if (Languages.Find((string?)m["id"]) is { } l) { ctx.Settings.Language = l.Code; SendReveal(); } });
On("dlssanswer", m => { if ((string?)m["id"] == "yes" && Answered(ref dlssKey, m)) new Dlss(ctx).Accept(); SendReveal(); });
On("screen", _ => { });
On("open", m => OpenThing((string?)m["arg"] ?? ""));
On("report", _ => Copy(Report.ForBuild(ctx, lastResult, runner?.Details ?? "", new Tools(ctx).InstalledVersion, lastFailure)));
@@ -94,6 +102,7 @@ public sealed partial class Backend
On("uninstallanswer", m =>
{
if ((string?)m["id"] != "yes") { host.Close(); return; }
if (!Answered(ref uninstallKey, m)) return;
new Uninstaller(ctx).Run();
host.Close();
});
@@ -123,7 +132,7 @@ public sealed partial class Backend
{
var plan = new Uninstaller(ctx).Describe();
Ask("Uninstall Triforce?", "<p><b>Removes</b> " + H(string.Join(", ", plan.Removes)) + "</p><p><b>Keeps</b> " + H(string.Join(", ", plan.Keeps)) + "</p>",
"uninstallanswer", new[] { ("no", "Keep it", false), ("yes", "Uninstall", true) });
"uninstallanswer", new[] { ("no", "Keep it", false), ("yes", "Uninstall", true) }, AskKey(ref uninstallKey));
return;
}
var game = GameDir;
@@ -173,6 +182,12 @@ public sealed partial class Backend
Ask(workKind == "update" ? "Close Triforce and stop the update?" : "Close Triforce and stop the build?",
"<p>What is done so far is kept: next time it carries on from where it stopped.</p>", "closeanswer",
new[] { ("no", "Keep going", true), ("yes", "Stop and close", false) });
// ((Triforce, 11-25) a randomizer seed being made, or OOTRR being downloaded: asked too. A seed stopped part way is
// never one the game reads: it is built under a hidden name and named only when whole)
else if (randoCts != null || randoToolBusy)
Ask(randoCts != null ? "Close Triforce and stop the seed?" : "Close Triforce and stop the randomizer's download?",
randoCts != null ? "<p>The seed being made is not kept. Make it again any time.</p>" : "<p>It goes on from where it stopped next time.</p>", "closeanswer",
new[] { ("no", "Keep going", true), ("yes", "Stop and close", false) });
else host.Close();
}
@@ -180,6 +195,7 @@ public sealed partial class Backend
{
try { workCts?.Cancel(); } catch { }
try { runner?.Stop(); } catch { }
try { randoCts?.Cancel(); } catch { } // (a seed being made: OOTRR is ended, its half-made folder taken away)
}
// ---------------- first run: the game handed over ----------------
@@ -252,6 +268,13 @@ public sealed partial class Backend
async Task BuildFirst()
{
if (source == null) { Go("welcome"); return; }
if (!TakeWork()) { Go("work"); return; }
try { await BuildFirstOne(); }
finally { FreeWork(); }
}
async Task BuildFirstOne()
{
var space = new GameIntake(ctx).Space(outFolder!);
if (space.TooLittle) { Toast("Not enough room on " + H(space.Disk) + ": the build needs " + (space.NeedWhileBuilding >> 30) + " GB free.", "error"); return; }
retry = BuildFirst;
@@ -281,20 +304,24 @@ public sealed partial class Backend
{
var g = GameDir;
if (g == null) { Go("welcome"); return; }
if (workCts != null) { Go("work"); return; }
if (!TakeWork()) { Go("work"); return; }
_ = Guarded("rebuild", async () =>
{
retry = () => { StartRebuild(); return Task.CompletedTask; };
workKind = "update";
using var cts = workCts = new CancellationTokenSource();
try
{
await EnsureTools(cts.Token);
await RunBuild(BuildRequest.Update(g), cts.Token);
retry = () => { StartRebuild(); return Task.CompletedTask; };
workKind = "update";
using var cts = workCts = new CancellationTokenSource();
try
{
await EnsureTools(cts.Token);
await RunBuild(BuildRequest.Update(g), cts.Token);
}
catch (OperationCanceledException) { WorkStopped(); }
catch (Exception e) { WorkFailed("The build stopped", Failure.Of(e, false).Note, e); }
finally { workCts = null; }
}
catch (OperationCanceledException) { WorkStopped(); }
catch (Exception e) { WorkFailed("The build stopped", Failure.Of(e, false).Note, e); }
finally { workCts = null; }
finally { FreeWork(); }
});
}
@@ -486,7 +513,13 @@ public sealed partial class Backend
// ---------------- update ----------------
async Task UpdateNow(string? folder)
{
if (workCts != null) { Go("work"); return; }
if (!TakeWork()) { Go("work"); return; }
try { await UpdateNowOne(folder); }
finally { FreeWork(); }
}
async Task UpdateNowOne(string? folder)
{
if (release == null) await CheckRelease();
if (release == null) { Toast("Could not reach the update server. You can still play.", "error"); return; }
var rel = release;
@@ -570,6 +603,9 @@ public sealed partial class Backend
: new JsonObject { ["text"] = release != null ? "Up to date · " + built?.TrimStart('v') : built?.TrimStart('v') ?? "", ["dot"] = "" };
}
if (running) { home["button"] = "Running"; home["off"] = true; pill = new JsonObject { ["text"] = "Playing", ["dot"] = "blue" }; }
// ((Triforce, 11-25) a randomizer seed that is on, said where Play is, whatever else the screen says: a save of the
// plain game does not match it)
if (g != null && RandoSeedOn(g) is { } seed) links.Add(new JsonObject { ["html"] = "<b>&#9670; Randomizer seed " + H(seed) + "</b> is on", ["act"] = "go:rando" });
home["links"] = links;
if (release?.NewIn is { Count: > 0 } ni)
{
@@ -601,9 +637,18 @@ public sealed partial class Backend
// ---------------- Play ----------------
void Play()
{
// ((Triforce, 11-26) one start at a time: two clicks on Play started two games before the first was seen running)
if (Interlocked.CompareExchange(ref playStarting, 1, 0) != 0) return;
try { PlayOne(); }
finally { Interlocked.Exchange(ref playStarting, 0); }
}
void PlayOne()
{
var g = GameDir;
if (g == null) { Go("welcome"); return; }
if (Volatile.Read(ref workBusy) != 0) { Go("work"); return; } // (a build or an update is writing the game folder)
var game = new Game(ctx);
if (game.IsRunning(g)) { Go("playing"); ShowGame(); return; }
gameProc = game.Play(g);
@@ -643,6 +688,19 @@ public sealed partial class Backend
[System.Runtime.InteropServices.DllImport("user32")] static extern bool SetForegroundWindow(IntPtr h);
[System.Runtime.InteropServices.DllImport("user32")] static extern bool ShowWindow(IntPtr h, int c);
// ---------------- answers ----------------
// ((Triforce, 11-26) the questions whose yes cannot be undone (uninstall, the NVIDIA licence) carry a key of their own, made
// when they are asked and good once: a 'yes' the page sends without the question shown (a script that got into the page)
// does nothing. As saves.confirm does)
string? uninstallKey, dlssKey;
static string AskKey(ref string? slot) => slot = Convert.ToHexString(System.Security.Cryptography.RandomNumberGenerator.GetBytes(16));
static bool Answered(ref string? slot, JsonNode m)
{
var want = Interlocked.Exchange(ref slot, null);
var got = m["ctx"] is JsonValue v && v.TryGetValue<string>(out var s) ? s : null;
return want != null && got == want;
}
// ---------------- links ----------------
void OpenThing(string what)
{
@@ -652,7 +710,8 @@ public sealed partial class Backend
"changes" => release?.PageUrl ?? BuildInfo.Home,
_ => what.StartsWith("https://", StringComparison.Ordinal) ? what : null,
};
if (url != null) { try { Process.Start(new ProcessStartInfo(url) { UseShellExecute = true }); } catch { } return; }
// (through OpenLink: https only, whatever the release feed or the page says; a test run opens nothing)
if (url != null) { OpenLink(url); return; }
var folder = what switch
{
"game" => GameDir,

View File

@@ -53,7 +53,16 @@ public sealed partial class Backend
});
}
// ((Triforce, 11-26) one change of the options file at a time: two sliders' values sent together each read, changed and
// wrote the file through one .new file, and one was lost or failed)
readonly object gameOptsGate = new();
void SetGameOption(string key, int v)
{
lock (gameOptsGate) SetGameOptionOne(key, v);
}
void SetGameOptionOne(string key, int v)
{
if (!CanChangeGame(out var f) || GameOptionsSchema.ByKey(key) == null) { RefreshSettingsState(); return; }
f!.Set(key, v);

View File

@@ -41,6 +41,20 @@ public sealed partial class Backend
});
}
/// <summary>((Triforce, 11-26) 1 while a GameBanana file is installed: two at once shared the mods folder's download folder,
/// and the second took away the first one's download and the version it had moved aside</summary>
int gbInstalling;
/// <summary>((Triforce, 11-26) A build or an update reads the mods folder (and records which code patches it built in): no
/// mod changes meanwhile. Says so and is true when refused.</summary>
bool RefusedWhileBuilding()
{
if (Volatile.Read(ref workBusy) == 0) return false;
Toast("Wait for the build to end: it reads the mods folder.", "error");
SendMods();
return true;
}
static string CardKey(GbMod m) => "gb:" + (m.Wip ? "w" : "m") + ":" + m.Id;
GbMod? CardOf(string id) { lock (modsGate) return gbCards.FirstOrDefault(c => CardKey(c) == id); }
@@ -283,7 +297,7 @@ public sealed partial class Backend
{
if (id == null) return;
if (GameDir is not { } game) { Toast("Build the game first: mods go into its mods folder.", "error"); return; }
if (modsBusy.ContainsKey(id)) return;
if (modsBusy.ContainsKey(id) || RefusedWhileBuilding()) return;
if (id.StartsWith("m:", StringComparison.Ordinal))
{
var mod = MineMods(game, true).FirstOrDefault(m => "m:" + m.Rel == id);
@@ -344,7 +358,9 @@ public sealed partial class Backend
async Task Install(string game, GbMod card, GbFile file)
{
var key = CardKey(card);
if (!modsBusy.TryAdd(key, "Downloading " + Size(file.Bytes))) return;
if (RefusedWhileBuilding()) return;
if (Interlocked.CompareExchange(ref gbInstalling, 1, 0) != 0) { Toast("One download at a time: wait for the one on its way.", "error"); return; }
if (!modsBusy.TryAdd(key, "Downloading " + Size(file.Bytes))) { Interlocked.Exchange(ref gbInstalling, 0); return; }
SendMods();
var last = DateTime.MinValue;
void Progress(DownloadProgress p)
@@ -367,6 +383,7 @@ public sealed partial class Backend
finally
{
modsBusy.TryRemove(key, out _);
Interlocked.Exchange(ref gbInstalling, 0);
SendMods();
}
}
@@ -390,7 +407,7 @@ public sealed partial class Backend
void ModsRemove(string? id)
{
if (id == null || GameDir is not { } game) return;
if (id == null || GameDir is not { } game || RefusedWhileBuilding()) return;
var all = MineMods(game, true);
List<Mod> list;
if (id.StartsWith("m:", StringComparison.Ordinal)) list = all.Where(m => "m:" + m.Rel == id).ToList();

View File

@@ -0,0 +1,520 @@
using System.Text.Json.Nodes;
using Triforce.Logic;
namespace Triforce.Launcher;
/// <summary>((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.</summary>
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();
/// <summary>What OOTRR says against the settings as they are (Randomizer.CheckAsync), null when it can make them.</summary>
string? randoProblem;
CancellationTokenSource? randoCheckCts;
readonly SemaphoreSlim randoCheckGate = new(1, 1);
/// <summary>Why OOTRR's settings could not be read (the page offers to try again), null when they were or no try was made.</summary>
string? randoSchemaError;
readonly SemaphoreSlim randoSchemaGate = new(1, 1);
/// <summary>1 while a seed is made / OOTRR is downloaded: two clicks (each command runs on a worker of its own) start one.</summary>
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?", "<p>It lists where every item of this seed is, and one way through the game. Open it only if you want to know.</p>",
"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 ----------------
/// <summary>The page's state. The settings' descriptions (labels, tips, choices) go once per program, the values each time.</summary>
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<RandoSeed> 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<string> { 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); }
}
}
/// <summary>The page opened: the kept choices, and OOTRR's settings once it is installed (read once a run).</summary>
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(); }
}
/// <summary>The seed's text, as typed: no longer than a seed may be, no line breaks.</summary>
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",
"<p>Triforce's randomizer is <b>OOTRR</b>, the Ocarina of Time Remake Randomizer by its own team (free software, GPL-3.0, as Triforce is).</p>" +
"<p><b>" + H(Rando.Tool.File.Name) + "</b>, " + 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.</p>",
"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("<b>&#9670;</b> 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<string>(out var sid) ? sid : value?.ToJsonString() ?? "";
Toast(!x.IsLive(asked) ? "OOTRR " + H(Ootrr.Version) + " cannot apply <b>" + H(RandoSchema.Show(x, value)) + "</b> 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();
}
/// <summary>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.</summary>
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: <b>" + H(p.Name) + "</b>" + (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 = "<b>&#9670;</b> Seed <b>" + H(made.Seed.Seed) + "</b> is on · start a <b>new game</b> 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 ----------------
/// <summary>The seed text of the seed that is on in a game folder, or null (the home screen's line).</summary>
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 <b>" + H(x.Seed) + "</b> 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 <b>" + H(x.Seed) + "</b> 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();
}
/// <summary>A text file in the system's own program for it. A test run opens nothing: it says so instead.</summary>
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"); }
}
}

View File

@@ -123,8 +123,10 @@ public sealed partial class Backend
PickThen(true, into ? "Choose the folder with your saves" : "Choose where the saves go", path => SavesFolderPicked(into, path));
return;
}
if (!id.StartsWith('s') || !int.TryParse(id.AsSpan(1), out var i) || i < 0 || i >= savesFound.Count) return;
SavesAsk(into, savesFound[i]);
// ((Triforce, 11-26) the list as it is now, once: another worker may put a new list in its place between the check and the read)
var found = savesFound;
if (!id.StartsWith('s') || !int.TryParse(id.AsSpan(1), out var i) || i < 0 || i >= found.Count) return;
SavesAsk(into, found[i]);
}
void SavesFolderPicked(bool into, string path)
@@ -212,7 +214,7 @@ public sealed partial class Backend
if (OperatingSystem.IsWindows()) System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(url) { UseShellExecute = true })?.Dispose();
else
{
var si = new System.Diagnostics.ProcessStartInfo("xdg-open") { UseShellExecute = false };
var si = new System.Diagnostics.ProcessStartInfo(LinuxPlatform.XdgOpen) { UseShellExecute = false };
si.ArgumentList.Add(url);
System.Diagnostics.Process.Start(si)?.Dispose();
}

View File

@@ -20,14 +20,14 @@ public sealed partial class Backend
On("settings.lang", m => LanguageChosen((string?)m["id"]));
On("settings.dlss", m =>
{
if ((string?)m["id"] != "yes") return;
if ((string?)m["id"] != "yes" || !Answered(ref dlssKey, m)) return;
new Dlss(ctx).Accept();
Toast("NVIDIA DLSS is included from the next build.", "success");
SendSettings();
});
On("settings.uninstall", m =>
{
if ((string?)m["id"] != "yes") return;
if ((string?)m["id"] != "yes" || !Answered(ref uninstallKey, m)) return;
Log.Write("uninstall from Settings");
try { new Uninstaller(ctx).Run(); }
catch (Exception e) { Log.Write("uninstall: " + e); Toast("Triforce could not be removed: " + H(e.Message), "error"); return; }
@@ -173,7 +173,7 @@ public sealed partial class Backend
return;
}
var html = string.Join("", dlss.LicenseText.Split("\n\n").Select(p => "<p>" + H(p).Replace("\n", "<br>") + "</p>"));
Ask("NVIDIA DLSS", html, "settings.dlss", new[] { ("no", "Cancel", false), ("yes", Dlss.AcceptLabel, true) });
Ask("NVIDIA DLSS", html, "settings.dlss", new[] { ("no", "Cancel", false), ("yes", Dlss.AcceptLabel, true) }, AskKey(ref dlssKey));
break;
}
case "rebuild":
@@ -207,7 +207,7 @@ public sealed partial class Backend
var plan = new Uninstaller(ctx).Describe();
string List(IEnumerable<string> l) => "<ul style=\"margin:4px 0 0 20px\">" + string.Join("", l.Select(x => "<li>" + H(Capital(x)) + "</li>")) + "</ul>";
Ask("Uninstall Triforce", "<p>This removes:</p>" + List(plan.Removes) + "<p>This keeps:</p>" + List(plan.Keeps), "settings.uninstall",
new[] { ("no", "Keep Triforce", false), ("yes", "Uninstall", true) });
new[] { ("no", "Keep Triforce", false), ("yes", "Uninstall", true) }, AskKey(ref uninstallKey));
break;
}
}

View File

@@ -80,7 +80,17 @@ public sealed partial class Backend
"texpack.go", new[] { ("no", "Not now", false), ("go", have == TexturePackHave.Partial ? "Continue" : "Download", true) });
}
// ((Triforce, 11-26) 1 while the pack downloads: two clicks started two installs into one folder)
int packBusy;
async Task RunPack()
{
if (Interlocked.CompareExchange(ref packBusy, 1, 0) != 0) return;
try { await RunPackOne(); }
finally { Interlocked.Exchange(ref packBusy, 0); }
}
async Task RunPackOne()
{
var g = GameDir;
if (g == null || packCts != null || packManifest == null) return;

View File

@@ -10,7 +10,8 @@ namespace Triforce.Launcher;
/// Backend.Core.cs first run, build, home, update, Play (RegisterCore)
/// Backend.Saves.cs the Saves page (RegisterSaves)
/// Backend.Mods.cs the Mods page (RegisterMods)
/// Backend.Settings.cs the Settings page, sound, uninstall (RegisterSettings)</summary>
/// Backend.Settings.cs the Settings page, sound, uninstall (RegisterSettings)
/// Backend.Randomizer.cs the Randomizer page (OOTRR's seeds) (RegisterRandomizer)</summary>
public sealed partial class Backend
{
readonly IHost host;
@@ -25,7 +26,7 @@ public sealed partial class Backend
this.host = host; this.content = content; this.ctx = ctx; this.start = start; this.dataDir = dataDir;
content.Media = MediaFor;
content.SavePicture = SavePicture;
RegisterCore(); RegisterSaves(); RegisterMods(); RegisterSettings(); RegisterBench(); RegisterGameOpts(); RegisterTexturePack();
RegisterCore(); RegisterSaves(); RegisterMods(); RegisterSettings(); RegisterBench(); RegisterGameOpts(); RegisterTexturePack(); RegisterRandomizer();
}
partial void RegisterSaves();
@@ -50,14 +51,16 @@ public sealed partial class Backend
public void OnMessage(string json, string[] files)
{
JsonNode? m;
try { m = JsonNode.Parse(json); } catch { Log.Write("bad message " + json); return; }
if (m == null) return;
var t = (string?)m["t"];
try { m = JsonNode.Parse(json); } catch { Log.Write("bad message " + (json.Length > 200 ? json.Substring(0, 200) + "..." : json)); return; }
// ((Triforce, 11-26) only an object with a string t: an array or a number threw out of the window's message event)
if (m is not JsonObject || m["t"] is not JsonValue tv || !tv.TryGetValue<string>(out var t)) { Log.Write("bad message (not a command)"); return; }
try
{
switch (t)
{
case "ready": OnReady(); break;
// (on a worker, as commands are: reading the game's art and music, the saves and the settings rows took the
// window's own thread, and the window hung until they were done)
case "ready": _ = Guarded("ready", () => Task.Run(OnReady)); break;
case "win":
switch ((string?)m["a"])
{

View File

@@ -110,6 +110,8 @@ public sealed class WinHost : IHost
// Only our own page lives in this window; a link elsewhere opens in the player's browser.
if (!e.Uri.StartsWith(Origin, StringComparison.OrdinalIgnoreCase)) { e.Cancel = true; OpenUrl(e.Uri); }
};
// ((Triforce, 11-26) no frame of another site inside the page: the page has none, and one could post messages)
web.FrameNavigationStarting += (_, e) => { if (!e.Uri.StartsWith(Origin, StringComparison.OrdinalIgnoreCase)) e.Cancel = true; };
web.ProcessFailed += (_, e) => Log.Write("webview process failed: " + e.ProcessFailedKind);
web.Navigate(Origin + "ui/index.html" + Environment.GetEnvironmentVariable("TRIFORCE_START"));
ctl.MoveFocus(CoreWebView2MoveFocusReason.Programmatic);
@@ -122,17 +124,28 @@ public sealed class WinHost : IHost
}
}
/// <summary>((Triforce, 11-26) What the page may load and run: its own scripts only (no inline script, no eval), styles of its
/// own and inline ones (style attributes), pictures of its own and over https (GameBanana's), no frames, no plugins. A text
/// that got into the page unescaped then cannot run a script, nor load one.</summary>
const string Csp = "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https:; " +
"media-src 'self' blob: data:; font-src 'self' data:; connect-src 'self'; object-src 'none'; frame-src 'none'; " +
"base-uri 'none'; form-action 'none'";
void OnRequest(object? sender, CoreWebView2WebResourceRequestedEventArgs e)
{
var path = new Uri(e.Request.Uri).AbsolutePath;
var got = content.Get(path);
// (no Access-Control-Allow-Origin: only the page itself, on this origin, reads what is served here)
e.Response = got is { } g
? env!.CreateWebResourceResponse(new MemoryStream(g.data), 200, "OK", "Content-Type: " + g.mime + "\r\nCache-Control: no-store\r\nAccess-Control-Allow-Origin: *")
? env!.CreateWebResourceResponse(new MemoryStream(g.data), 200, "OK", "Content-Type: " + g.mime + "\r\nCache-Control: no-store" +
(g.mime.StartsWith("text/html", StringComparison.OrdinalIgnoreCase) ? "\r\nContent-Security-Policy: " + Csp : ""))
: env!.CreateWebResourceResponse(null, 404, "Not Found", "Cache-Control: no-store");
}
void OnMessage(object? sender, CoreWebView2WebMessageReceivedEventArgs e)
{
// ((Triforce, 11-26) only the launcher's own page speaks to the launcher)
if (!e.Source.StartsWith(Origin, StringComparison.OrdinalIgnoreCase)) { Log.Write("message from " + e.Source + " left out"); return; }
string json;
try { json = e.TryGetWebMessageAsString(); } catch { json = e.WebMessageAsJson; }
var files = new List<string>();