Files
Triforce-Source/launcher/App/Backend.Character.cs
ruckus7382sfgsgdf 822ee913bc Triforce v0.9.0
Character tab, faster renderer defaults, HD rumble shipped, and the 11-30 bug pass: ending softlock below 60 fps, adult first-night lock, Intel Arc robust buffers, adult map, randomizer load order.
2026-11-30 20:55:14 -06:00

428 lines
23 KiB
C#

using System.Text.Json.Nodes;
using Triforce.Core.GameFiles;
using Triforce.Logic;
namespace Triforce.Launcher;
/// <summary>((Triforce, 11-29) The Character page (char.js, char3d.js): Link in 3D from the player's own game files
/// (Core LinkScene), young and adult, in his own colours (Logic LinkColors: OOTRR's recolouring, the randomizer's program).
/// The page is sent what it draws through Content's char/ route, made on a worker first (the route runs on the window's
/// thread and only hands over bytes that are ready):
/// char/scene/N.json, N.bin look N's parts and its posed mesh
/// char/tex/NAME.bin a texture (u32 width, u32 height, RGBA8)
/// char/mask/NAME.bin a colour map's calibration mask (where each of its parts lies)
/// char/exact/N/NAME.bin OOTRR's own recoloured colour map, from preview N
/// Picking a colour is live on the page (a tint over the mask) at once, and OOTRR's exact maps follow a moment later.
/// Apply writes the colours into the game as a mod (mods\~Link colors): every save shows them.</summary>
public sealed partial class Backend
{
LinkColors? linkColors;
LinkColors Colors => linkColors ??= new LinkColors(ctx, Rando.Tool, Rando.Manager);
LinkColors.Choice? charChoice;
LinkColors.Choice CharChoice => charChoice ??= Colors.LoadChoice();
readonly object charGate = new();
readonly Dictionary<string, byte[]> charFiles = new(StringComparer.Ordinal);
readonly Dictionary<string, (LinkScene Scene, string Game)> charScenes = new(StringComparer.Ordinal);
IReadOnlyList<LinkColors.CalMap>? charCal;
string? charCalGame, charCalError;
bool charCalBusy, charBusy;
string charLine = "";
int charN, charApplying;
readonly Dictionary<string, CancellationTokenSource> charPreviewCts = new();
CancellationTokenSource? charApplyCts;
void RegisterCharacter()
{
TextureRecolor.Astc = (texels, w, h) => AstcEncode.EncodeBlock(texels, w, h);
content.Character = CharContent;
OnAsync("char.open", _ => CharOpen());
OnAsync("char.look", m => CharLook((string?)m["look"] ?? "child", (m["have"] as JsonArray)?.Select(x => (string?)x).OfType<string>().ToHashSet() ?? new HashSet<string>()));
On("char.loaded", m => { var n = (int?)m["n"] ?? -1; lock (charGate) foreach (var k in charFiles.Keys.Where(k => k.StartsWith("tex/") || k.StartsWith("scene/" + n + ".")).ToList()) charFiles.Remove(k); });
On("char.set", m => CharSet((string?)m["age"], (string?)m["part"], (string?)m["hex"]));
On("char.many", m => CharMany((string?)m["age"], m["colors"] as JsonObject));
On("char.revert", _ => { charChoice = Colors.Applied(GameDir ?? "")?.Colors.Copy() ?? new LinkColors.Choice(); Colors.SaveChoice(CharChoice); CharPreviewSoon("child"); CharPreviewSoon("adult"); SendChar(); });
OnAsync("char.apply", _ => CharApply());
On("char.install", _ => CharInstallAsk());
On("char.hero", m => CharHero((string?)m["hero"]));
On("char.linkle", _ => CharLinkleAsk());
OnAsync("char.linkle.go", m => (string?)m["id"] == "go" ? CharLinkleGet() : Task.CompletedTask);
On("char.stop", _ => { try { charApplyCts?.Cancel(); } catch { } });
On("char.remove", _ =>
{
if (GameDir is not { } g || Colors.Applied(g) == null) return;
Ask("Back to the game's own colors?", "<p>Link's colors leave the game. Your picks stay here, so you can apply them again.</p>",
"char.remove.go", new[] { ("no", "Keep them", false), ("go", "Use the game's colors", true) });
});
On("char.remove.go", m =>
{
if ((string?)m["id"] != "go" || GameDir is not { } g) return;
try { Colors.Remove(g); Toast("Link wears the game's own colors again", "success"); }
catch (Exception e) when (e is OotrrException || e is IOException || e is UnauthorizedAccessException) { Toast(H(e.Message), "error"); }
SendChar();
});
}
void CharInstallAsk()
{
if (Colors.Tool.Have || randoToolBusy) return;
Ask("Get the color tool",
"<p>Link's colors are dyed by <b>OOTRR</b>, the Ocarina of Time Remake Randomizer's own program (free software, GPL-3.0, as Triforce is), " +
"the one the Randomizer page uses. It recolors the game's own textures exactly, block by block, so nothing is redrawn or blurred.</p>" +
"<p><b>" + H(Colors.Tool.File.Name) + "</b>, " + Size(Colors.Tool.File.Size) + ", is downloaded once from its release on GitHub and checked " +
"against the fingerprint Triforce knows for it. It reads your game files on this PC only; nothing is uploaded.</p>",
"rando.install.go", new[] { ("no", "Not now", false), ("go", "Download", true) });
}
// ---------------- the page's files ----------------
(byte[], string)? CharContent(string path)
{
// (the name part is unescaped by Content already)
string key;
if (path.StartsWith("scene/", StringComparison.Ordinal) || path.StartsWith("tex/", StringComparison.Ordinal) || path.StartsWith("mask/", StringComparison.Ordinal)
|| path.StartsWith("exact/", StringComparison.Ordinal)) key = path;
else return null;
byte[]? data;
lock (charGate) charFiles.TryGetValue(key, out data);
if (data == null) return null;
return (data, key.EndsWith(".json", StringComparison.Ordinal) ? "application/json" : "application/octet-stream");
}
static byte[] TexFile(int w, int h, byte[] rgba)
{
var f = new byte[8 + rgba.Length];
BitConverter.GetBytes(w).CopyTo(f, 0);
BitConverter.GetBytes(h).CopyTo(f, 4);
rgba.CopyTo(f, 8);
return f;
}
// ---------------- state ----------------
async Task CharOpen()
{
var g = GameDir;
if (g != null) try { Colors.LeftOvers(g); } catch (Exception) { }
SendChar();
// (the exact previews first, then the calibration: once per game, in the background; the page tints live once it is there)
CharPreviewSoon("child", 0); CharPreviewSoon("adult", 0);
if (g != null && Colors.Tool.Have && charCal == null && !charCalBusy) { await Task.Delay(6000); if (charCal == null && !charCalBusy) await CharCalibrate(g); }
else if (charCal != null) SendCal();
}
JsonObject WithLinkleProgress(JsonObject o)
{
o["busy"] = charLinkleGetting == 1; o["frac"] = charLinkleFrac; o["line"] = charLinkleLine;
o["name"] = Linkle.Name; o["author"] = Linkle.Author; o["page"] = Linkle.Page;
return o;
}
void SendChar()
{
var g = GameDir;
var applied = g != null ? Colors.Applied(g) : null;
var choice = CharChoice;
// (who the game shows now: Linkle when her mod is on, whatever the colours' marker says)
var linkleOn = g != null && Linkle.Find(Rando.Manager, g) is { On: true };
var inGame = applied?.Colors.Copy() ?? new LinkColors.Choice();
inGame.Hero = linkleOn ? "linkle" : "link";
var tool = Colors.Tool;
var o = new JsonObject
{
["game"] = g != null,
["tool"] = new JsonObject { ["have"] = tool.Have, ["busy"] = randoToolBusy, ["frac"] = randoToolFrac, ["size"] = Size(tool.File.Size), ["version"] = Ootrr.Version },
["hero"] = choice.Hero,
["linkle"] = g == null ? null : WithLinkleProgress(Linkle.Find(Rando.Manager, g) is { } lm ? new JsonObject { ["have"] = true, ["on"] = lm.On } : new JsonObject { ["have"] = false }),
["parts"] = new JsonArray((choice.Hero == "linkle" ? Linkle.Parts : LinkColors.Parts).Select(p => (JsonNode?)new JsonObject
{
["id"] = p.Id, ["label"] = p.Label, ["group"] = p.Group, ["ages"] = p.Ages, ["tunic"] = p.Tunic, ["swatch"] = p.Swatch,
}).ToArray()),
["colors"] = choice.ToJson(),
["applied"] = applied?.Colors.ToJson(),
["appliedOn"] = applied?.On ?? false,
["same"] = inGame.Same(choice) || (applied == null && !linkleOn && choice.Empty),
["appliedHero"] = inGame.Hero,
["busy"] = charBusy, ["line"] = charLine,
["calBusy"] = charCalBusy, ["calError"] = charCalError,
["others"] = g != null ? new JsonArray(Colors.Others(g).Select(x => (JsonNode?)x).ToArray()) : new JsonArray(),
};
SendState(new JsonObject { ["char"] = o });
}
// ---------------- Link in 3D ----------------
async Task CharLook(string look, HashSet<string> have)
{
if (!LinkScene.Looks.Contains(look) || GameDir is not { } g) return;
var n = Interlocked.Increment(ref charN);
try
{
var data = await Task.Run(() =>
{
var romfs = Path.Combine(g, "romfs");
var hero = CharChoice.Hero;
var her = hero == "linkle" ? Linkle.Find(Rando.Manager, g) : null;
if (hero == "linkle" && her == null) throw new IOException("Linkle is not in the mods folder");
using IGameSource src = her != null ? Linkle.Source(her, g) : new FolderSource(romfs);
var zs = new Zs(src);
LinkScene scene;
lock (charGate)
{
var sk = hero + "/" + look;
if (!charScenes.TryGetValue(sk, out var c) || c.Game != g) charScenes[sk] = c = (LinkScene.Build(src, zs, look, hero, hero == "linkle" ? Linkle.SceneRenames : null), g);
scene = c.Scene;
}
var files = new Dictionary<string, byte[]>
{
["scene/" + n + ".json"] = System.Text.Encoding.UTF8.GetBytes(scene.Info.ToJsonString()),
["scene/" + n + ".bin"] = scene.Mesh,
};
var names = new HashSet<string>(StringComparer.Ordinal);
foreach (var p in (JsonArray)scene.Info["parts"]!)
foreach (var role in new[] { "alb", "nrm", "nrm2", "ao", "lut", "grey", "emc" })
if ((string?)p![role] is { } name && !have.Contains(name)) names.Add(name);
Parallel.ForEach(names, new ParallelOptions { MaxDegreeOfParallelism = Math.Max(2, Environment.ProcessorCount / 2) }, name =>
{
try
{
var max = name.EndsWith("_Alb", StringComparison.Ordinal) || name.StartsWith("eye:", StringComparison.Ordinal) ? LinkScene.MaxTexture : LinkScene.MaxTexture / 2;
if (LinkScene.Texture(src, zs, hero == "linkle" ? Linkle.Original(name) : name, max) is { } t)
lock (files) files["tex/" + name + ".bin"] = TexFile(t.W, t.H, t.Rgba);
}
catch (Exception e) { Log.Write("character: texture " + name + ": " + e.Message); }
});
return files;
});
lock (charGate) foreach (var (k, v) in data) charFiles[k] = v;
Send(new JsonObject { ["t"] = "charLook", ["look"] = look, ["n"] = n, ["hero"] = CharChoice.Hero });
}
catch (Exception e) when (e is IOException || e is InvalidDataException || e is NotSupportedException || e is DirectoryNotFoundException)
{
Log.Write("character: " + look + ": " + e);
Send(new JsonObject { ["t"] = "charLook", ["look"] = look, ["n"] = n, ["error"] = "Link could not be read from your game: " + e.Message });
}
}
// ---------------- colours ----------------
void CharSet(string? age, string? part, string? hex)
{
var hero = CharChoice.Hero;
if (age == null || part == null || !LinkColors.Valid(hero, age, part)) return;
var clean = hex == null ? null : LinkColors.CleanHex(hex);
var ages = LinkColors.Shared.Contains(part) ? new[] { "child", "adult" } : new[] { age };
lock (charGate)
foreach (var a in ages)
if (clean == null) CharChoice.Age(LinkColors.Key(hero, a)).Remove(part); else CharChoice.Age(LinkColors.Key(hero, a))[part] = clean;
Colors.SaveChoice(CharChoice);
foreach (var a in ages) CharPreviewSoon(a);
SendChar();
}
/// <summary>Several parts at once (a preset, Randomize, Reset): colors {part: hex | null}; parts not named stay.</summary>
void CharMany(string? age, JsonObject? colors)
{
if (age is not ("child" or "adult") || colors == null) return;
lock (charGate)
foreach (var (part, v) in colors)
{
if (!LinkColors.Valid(CharChoice.Hero, age, part)) continue;
var hex = v is JsonValue jv && jv.TryGetValue<string>(out var s) ? LinkColors.CleanHex(s) : null;
foreach (var a in LinkColors.Shared.Contains(part) ? new[] { "child", "adult" } : new[] { age })
if (hex == null) CharChoice.Age(LinkColors.Key(CharChoice.Hero, a)).Remove(part); else CharChoice.Age(LinkColors.Key(CharChoice.Hero, a))[part] = hex;
}
Colors.SaveChoice(CharChoice);
CharPreviewSoon("child"); CharPreviewSoon("adult");
SendChar();
}
JsonArray? charCalMsg;
void SendCal() { if (charCalMsg != null) Send(new JsonObject { ["t"] = "charCal", ["maps"] = charCalMsg.DeepClone() }); }
async Task CharCalibrate(string g)
{
charCalBusy = true; charCalError = null; SendChar();
try
{
var stamp = GameStamp(g);
var cal = await Colors.CalibrateAsync(g, stamp, CancellationToken.None);
var arr = new JsonArray();
lock (charGate)
foreach (var m in cal)
{
charFiles["mask/" + m.Texture + ".bin"] = TexFile(m.Width, m.Height, m.Mask);
arr.Add(new JsonObject
{
["tex"] = LinkColors.ModelName(m.Texture), ["file"] = m.Texture,
["parts"] = new JsonArray(m.Parts.Select(p => (JsonNode?)p).ToArray()),
["ym"] = new JsonArray(m.Ym.Select(y => (JsonNode?)y).ToArray()), ["qm"] = new JsonArray(m.Qm.Select(y => (JsonNode?)y).ToArray()),
["ty"] = new JsonArray(m.Ty.Select(y => (JsonNode?)y).ToArray()),
["g"] = new JsonArray(m.G.Select(y => (JsonNode?)y).ToArray()),
});
}
charCal = cal; charCalGame = g; charCalMsg = arr;
SendCal();
}
catch (Exception e) when (e is OotrrException || e is IOException || e is UnauthorizedAccessException || e is InvalidDataException || e is InvalidOperationException)
{
Log.Write("character: calibration: " + e);
charCalError = e.Message;
}
finally { charCalBusy = false; SendChar(); }
}
/// <summary>A name for this game's files (the folder and Link's model as they are): the calibration is kept under it.</summary>
static string GameStamp(string g)
{
var f = new FileInfo(Path.Combine(g, "romfs", "Model", "Player_Child.Player_Child.bfres.zs"));
var key = g.ToLowerInvariant() + "|" + (f.Exists ? f.Length + "-" + f.LastWriteTimeUtc.Ticks : "none") + "|" + Ootrr.Version;
return Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(key)))[..16].ToLowerInvariant();
}
/// <summary>OOTRR's exact maps for one age, a moment after the last change (a newer change cancels a preview that runs).</summary>
void CharPreviewSoon(string age, int delayMs = 650)
{
if (GameDir is not { } g || (!Colors.Tool.Have && CharChoice.Hero != "linkle")) return;
CancellationTokenSource cts;
lock (charPreviewCts)
{
if (charPreviewCts.TryGetValue(age, out var old)) { try { old.Cancel(); } catch { } }
charPreviewCts[age] = cts = new CancellationTokenSource();
}
Dictionary<string, string> colors;
string hero;
lock (charGate) { hero = CharChoice.Hero; colors = new Dictionary<string, string>(CharChoice.Of(age)); }
var key = LinkColors.Key(hero, age);
_ = Task.Run(async () =>
{
try
{
await Task.Delay(delayMs, cts.Token);
var maps = hero == "linkle" ? await LinklePreview(g, age, colors, cts.Token) : await Colors.PreviewAsync(g, colors, cts.Token);
cts.Token.ThrowIfCancellationRequested();
var n = Interlocked.Increment(ref charN);
lock (charGate)
{
foreach (var k in charFiles.Keys.Where(k => k.StartsWith("exact/" + key + "/", StringComparison.Ordinal)).ToList()) charFiles.Remove(k);
foreach (var (tex, t) in maps) charFiles["exact/" + key + "/" + n + "/" + tex + ".bin"] = TexFile(t.W, t.H, t.Rgba);
}
Send(new JsonObject
{
["t"] = "charExact", ["age"] = age, ["hero"] = hero, ["key"] = key, ["n"] = n,
["colors"] = new JsonObject(colors.Select(kv => KeyValuePair.Create(kv.Key, (JsonNode?)kv.Value))),
["tex"] = new JsonArray(maps.Keys.Select(k => (JsonNode?)k).ToArray()),
});
}
catch (OperationCanceledException) { }
catch (Exception e) when (e is OotrrException || e is IOException || e is InvalidDataException || e is NotSupportedException)
{
Log.Write("character: preview " + age + ": " + e.Message);
}
});
}
/// <summary>Linkle's dyed textures for one age (the launcher's own dye), and adult hair from the colour tool.</summary>
async Task<Dictionary<string, (int W, int H, byte[] Rgba)>> LinklePreview(string g, string age, Dictionary<string, string> colors, CancellationToken token)
{
var maps = new Dictionary<string, (int W, int H, byte[] Rgba)>(StringComparer.Ordinal);
if (colors.Count == 0) return maps;
var mod = Linkle.Find(Rando.Manager, g);
if (mod == null) return maps;
await Task.Run(() =>
{
using var her = Linkle.Source(mod, g);
var zs = new Zs(her);
foreach (var (tex, (_, _, prev)) in Linkle.Dye(her, zs, age, colors)) maps[tex] = prev;
}, token);
if (age == "adult" && colors.TryGetValue("hair", out var hair) && Colors.Tool.Have)
foreach (var (tex, m) in await Colors.PreviewAsync(g, new Dictionary<string, string> { ["hair"] = hair }, token))
if (tex == "Mt_Hairs_Player_Adult_Alb") maps[tex] = m;
return maps;
}
void CharHero(string? hero)
{
if (hero is not ("link" or "linkle") || hero == CharChoice.Hero) return;
lock (charGate) CharChoice.Hero = hero;
Colors.SaveChoice(CharChoice);
SendChar();
if (hero == "link" || (GameDir is { } g && Linkle.Find(Rando.Manager, g) != null)) { CharPreviewSoon("child", 0); CharPreviewSoon("adult", 0); }
}
int charLinkleGetting;
double charLinkleFrac;
string charLinkleLine = "";
void CharLinkleAsk()
{
Ask("Get Linkle",
"<p><b>" + H(Linkle.Name) + "</b> by <b>" + H(Linkle.Author) + "</b> replaces Link with Linkle from Hyrule Warriors, young and adult, " +
"with her own voice, gear and fairy, Liri.</p><p>It is downloaded from its page on GameBanana (about 320 MB) into your mods folder, " +
"as the Mods page does. It is the author's work: Triforce only installs it and switches it on and off.</p>",
"char.linkle.go", new[] { ("no", "Not now", false), ("go", "Download", true) });
}
async Task CharLinkleGet()
{
if (GameDir is not { } g || Interlocked.CompareExchange(ref charLinkleGetting, 1, 0) != 0) return;
charLinkleFrac = 0; charLinkleLine = "Asking GameBanana"; SendChar();
try
{
var d = await Gb.DetailsAsync(Linkle.GameBananaId, false);
if (d.Files.Count == 0) throw new ModsException("Its GameBanana page has no file to download.");
var file = d.Files[d.DefaultFile(false)];
var card = new GbMod(Linkle.GameBananaId, false, Linkle.Name, Linkle.Author, "", Linkle.Page, 0, 0, 0, null);
var last = DateTime.MinValue;
await new GameBananaInstaller(ctx).InstallAsync(gbHttp.Value, card, file, g, p =>
{
charLinkleFrac = p.Fraction; charLinkleLine = p.Fraction >= 1 ? "Unpacking" : "Downloading, " + (int)(p.Fraction * 100) + " %";
if ((DateTime.UtcNow - last).TotalMilliseconds < 500) return;
last = DateTime.UtcNow; SendChar();
}, CancellationToken.None);
Toast("<b>&#9670;</b> Linkle is in your mods folder", "success");
CharHero("linkle");
}
catch (Exception e) when (e is ModsException || e is HttpRequestException || e is IOException || e is UnauthorizedAccessException || e is TaskCanceledException || e is InvalidOperationException || e is System.Text.Json.JsonException)
{
Log.Write("character: linkle: " + e);
Toast("Linkle could not be downloaded: " + H(e.Message), "error");
}
finally { charLinkleLine = ""; Interlocked.Exchange(ref charLinkleGetting, 0); SendChar(); }
}
async Task CharApply()
{
if (GameDir is not { } g) return;
if (!Colors.Tool.Have) { CharInstallAsk(); return; }
if (Interlocked.CompareExchange(ref charApplying, 1, 0) != 0) return;
LinkColors.Choice choice;
lock (charGate) choice = CharChoice.Copy();
charBusy = true; charLine = "Getting ready"; SendChar();
var cts = charApplyCts = new CancellationTokenSource();
try
{
var dest = await Colors.ApplyAsync(g, choice, l => { charLine = l; SendChar(); }, cts.Token);
if (dest == null) Toast("Link wears the game's own colors again", "success");
else
{
var others = Colors.Others(g);
Toast("<b>&#9670;</b> Link's colors are in your game · every save, the next time you play" +
(others.Count > 0 ? " · they show over " + H(string.Join(", ", others)) : ""), "success");
Sfx("success");
}
}
catch (OperationCanceledException) { Toast("Stopped: your game keeps the colors it had"); }
catch (Exception e) when (e is OotrrException || e is IOException || e is UnauthorizedAccessException || e is InvalidOperationException || e is InvalidDataException || e is ModsException)
{
Log.Write("character: apply: " + e);
Toast("The colors could not be applied: " + H(e.Message), "error");
}
finally
{
charBusy = false; charLine = ""; charApplyCts = null;
Interlocked.Exchange(ref charApplying, 0);
SendChar();
}
}
}