mirror of
https://git.triforceproject.com/triforce/source
synced 2026-12-01 05:18:50 -04:00
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.
This commit is contained in:
652
launcher/Logic/Character/LinkColors.cs
Normal file
652
launcher/Logic/Character/LinkColors.cs
Normal file
@@ -0,0 +1,652 @@
|
||||
// (Triforce, 11-29) The Character page's colours: young Link's and adult Link's tunics, gear and hair, each in its own colours.
|
||||
// The recolouring is OOTRR's (the randomizer's program, already used by the Randomizer page: Ootrr.cs): its colors-preview
|
||||
// gives the recoloured colour maps as pictures in seconds (the page's exact preview), and its build writes the game files
|
||||
// (block-exact edits of the compressed textures, so nothing is re-encoded). A build recolours a part for every age at once,
|
||||
// so young and adult Link each get a build of their own and the files are taken from each: young Link's from the first,
|
||||
// adult Link's from the second. The one texture both ages share (OOTRR's own copy of the cloth tile, Angin_Tile_L_Alb) is
|
||||
// renamed once more for young Link (Angin_Tile_Y_Alb, the same length) and his models point at it: the same one-letter edit
|
||||
// OOTRR makes to point Link away from the tile the Kokiri share.
|
||||
//
|
||||
// The result is a mod of its own, <game>\mods\~Link colors (its name sorts after every other mod's, so its files win over a
|
||||
// randomizer seed's colours), with triforce_mod.json (its name on the Mods page) and link_colors.json (the colours, which the
|
||||
// page reads back). It changes the game's files, not a save: every save, old or new, shows the colours.
|
||||
//
|
||||
// <home>\character\choices.json the colours being picked (not applied yet)
|
||||
// <home>\character\<game stamp>\cal\ the calibration: where each part lies on each colour map (masks) and its brightness
|
||||
// <home>\character\work\<id>\ a build or preview while it runs (taken away after)
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using System.Text.RegularExpressions;
|
||||
using Triforce.Core.GameFiles;
|
||||
using ZstdSharp;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
/// <summary>A part of Link the page can colour: OOTRR's id, its name on the page, its group, the ages and tunics it shows on,
|
||||
/// and roughly the game's own colour (for the swatch while it is unchanged).</summary>
|
||||
public sealed record LinkPart(string Id, string Label, string Group, string Ages, string Tunic, string Swatch);
|
||||
|
||||
public sealed class LinkColors
|
||||
{
|
||||
public const string ModFolder = "~Link colors";
|
||||
public const string Marker = "link_colors.json";
|
||||
public const string WorkFolder = "character";
|
||||
|
||||
/// <summary>Ages: "child" (young Link) and "adult". Tunic: "" any, else kokiri / goron / zora (the adult's tunic it shows on).</summary>
|
||||
public static readonly LinkPart[] Parts =
|
||||
{
|
||||
new("kokiri", "Tunic and cap", "Tunic", "child,adult", "kokiri", "#2f8f3a"),
|
||||
new("kokiri_pants", "Leggings", "Tunic", "child", "", "#3d7a33"),
|
||||
new("kokiri_shirt", "Undershirt and leggings", "Tunic", "adult", "kokiri", "#d8d1bd"),
|
||||
new("feathers", "Cap feather", "Tunic", "child,adult", "kokiri", "#e6dfcf"),
|
||||
new("goron", "Goron Tunic", "Tunic", "adult", "goron", "#b3262c"),
|
||||
new("goron_trim", "Goron trim", "Tunic", "adult", "goron", "#d4a634"),
|
||||
new("goron_belt", "Goron belt", "Tunic", "adult", "goron", "#6b4a2b"),
|
||||
new("goron_beads", "Goron beads", "Tunic", "adult", "goron", "#c9b07a"),
|
||||
new("zora", "Zora Tunic", "Tunic", "adult", "zora", "#2a4fb0"),
|
||||
new("zora_shirt", "Zora undershirt", "Tunic", "adult", "zora", "#d4d8de"),
|
||||
new("zora_belt", "Zora belt", "Tunic", "adult", "zora", "#8a3c8e"),
|
||||
new("zora_scales", "Zora scales", "Tunic", "adult", "zora", "#3d8fb8"),
|
||||
new("kokiri_belt", "Belts and straps", "Leather", "child,adult", "kokiri", "#6b4a2b"),
|
||||
new("leather_trim", "Leather trim", "Leather", "child,adult", "", "#9c2f25"),
|
||||
new("boots", "Boots", "Leather", "adult", "", "#5b3f26"),
|
||||
new("gloves", "Gloves", "Leather", "adult", "", "#7a5534"),
|
||||
new("hair", "Hair", "Hair", "child,adult", "", "#e0b84a"),
|
||||
new("navi", "Navi", "Navi", "child,adult", "", "#dff3ff"),
|
||||
};
|
||||
|
||||
public static IEnumerable<LinkPart> PartsOf(string age) => Parts.Where(p => p.Ages.Split(',').Contains(age));
|
||||
public static bool Valid(string age, string part) => PartsOf(age).Any(p => p.Id == part);
|
||||
/// <summary>(11-29) The heroes: Link, and Linkle (a mod: Linkle.cs). A colour key is the age, "linkle:" in front for her.</summary>
|
||||
public static readonly string[] Heroes = { "link", "linkle" };
|
||||
public static string Key(string hero, string age) => hero == "linkle" ? "linkle:" + age : age;
|
||||
public static (string Hero, string Age) FromKey(string key) => key.StartsWith("linkle:", StringComparison.Ordinal) ? ("linkle", key[7..]) : ("link", key);
|
||||
public static IEnumerable<LinkPart> PartsOf(string hero, string age) => (hero == "linkle" ? Linkle.Parts : Parts).Where(p => p.Ages.Split(',').Contains(age));
|
||||
public static bool Valid(string hero, string age, string part) => PartsOf(hero, age).Any(p => p.Id == part);
|
||||
static readonly string[] Keys = { "child", "adult", "linkle:child", "linkle:adult" };
|
||||
/// <summary>Parts the game has once for both ages (Navi is one fairy): set for one age, set for both.</summary>
|
||||
public static readonly string[] Shared = { "navi" };
|
||||
static readonly Regex Hex = new("^#[0-9a-f]{6}$", RegexOptions.CultureInvariant);
|
||||
public static string? CleanHex(string? hex)
|
||||
{
|
||||
hex = (hex ?? "").Trim().ToLowerInvariant();
|
||||
if (hex.Length == 6) hex = "#" + hex;
|
||||
return Hex.IsMatch(hex) ? hex : null;
|
||||
}
|
||||
|
||||
readonly TriforceContext ctx;
|
||||
public Ootrr Tool { get; }
|
||||
public ModManager Mods { get; }
|
||||
public LinkColors(TriforceContext ctx, Ootrr tool, ModManager mods) { this.ctx = ctx; Tool = tool; Mods = mods; }
|
||||
|
||||
string Home => Path.Combine(ctx.Home, WorkFolder);
|
||||
|
||||
// ---------------- the colours being picked ----------------
|
||||
|
||||
/// <summary>age -> part -> #rrggbb. A part not in it keeps the game's colour.</summary>
|
||||
public sealed class Choice
|
||||
{
|
||||
public Dictionary<string, Dictionary<string, string>> Colors { get; } = new() { ["child"] = new(), ["adult"] = new() };
|
||||
/// <summary>Who the player plays: "link" or "linkle".</summary>
|
||||
public string Hero { get; set; } = "link";
|
||||
/// <summary>The colours of the hero being played, by age.</summary>
|
||||
public Dictionary<string, string> Of(string age) => Age(Key(Hero, age));
|
||||
public Dictionary<string, string> Age(string age) => Colors.TryGetValue(age, out var d) ? d : Colors[age] = new();
|
||||
public Choice Copy()
|
||||
{
|
||||
var c = new Choice { Hero = Hero };
|
||||
foreach (var (age, d) in Colors) c.Colors[age] = new Dictionary<string, string>(d);
|
||||
return c;
|
||||
}
|
||||
/// <summary>The same hero, and the same colours for that hero (the other hero's picks are not in the game).</summary>
|
||||
public bool Same(Choice o) => Hero == o.Hero && new[] { Key(Hero, "child"), Key(Hero, "adult") }.All(a =>
|
||||
{
|
||||
var x = Colors.TryGetValue(a, out var p) ? p : new(); var y = o.Colors.TryGetValue(a, out var q) ? q : new();
|
||||
return x.Count == y.Count && x.All(kv => y.TryGetValue(kv.Key, out var v) && v == kv.Value);
|
||||
});
|
||||
/// <summary>Nothing to write: Link in the game's own colours.</summary>
|
||||
public bool Empty => Hero == "link" && Of("child").Count == 0 && Of("adult").Count == 0;
|
||||
public JsonObject ToJson()
|
||||
{
|
||||
var o = new JsonObject(Colors.Select(kv => KeyValuePair.Create(kv.Key, (JsonNode?)new JsonObject(kv.Value.Select(p => KeyValuePair.Create(p.Key, (JsonNode?)p.Value))))));
|
||||
o["hero"] = Hero;
|
||||
return o;
|
||||
}
|
||||
public static Choice FromJson(JsonNode? n)
|
||||
{
|
||||
var c = new Choice();
|
||||
if (n is not JsonObject o) return c;
|
||||
if (o["hero"] is JsonValue h && h.TryGetValue<string>(out var hero) && Heroes.Contains(hero)) c.Hero = hero;
|
||||
foreach (var key in Keys)
|
||||
{
|
||||
var (kh, age) = FromKey(key);
|
||||
if (o[key] is JsonObject a)
|
||||
foreach (var (part, v) in a)
|
||||
if (Valid(kh, age, part) && CleanHex(v is JsonValue jv && jv.TryGetValue<string>(out var s) ? s : null) is { } hex) c.Age(key)[part] = hex;
|
||||
}
|
||||
return c;
|
||||
}
|
||||
}
|
||||
|
||||
string ChoicesFile => Path.Combine(Home, "choices.json");
|
||||
|
||||
public Choice LoadChoice()
|
||||
{
|
||||
try { return File.Exists(ChoicesFile) ? Choice.FromJson(JsonNode.Parse(File.ReadAllText(ChoicesFile))) : new Choice(); }
|
||||
catch (Exception e) when (e is IOException || e is JsonException || e is UnauthorizedAccessException) { return new Choice(); }
|
||||
}
|
||||
|
||||
public void SaveChoice(Choice c)
|
||||
{
|
||||
if (!ctx.Allowed(Home)) return;
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(Home);
|
||||
var tmp = ChoicesFile + ".tmp";
|
||||
File.WriteAllText(tmp, new JsonObject { ["colors"] = c.ToJson() }["colors"]!.ToJsonString());
|
||||
File.Move(tmp, ChoicesFile, true);
|
||||
}
|
||||
catch (Exception e) when (e is IOException || e is UnauthorizedAccessException) { ctx.Log.Write("character: colours not kept: " + e.Message); }
|
||||
}
|
||||
|
||||
// ---------------- what the game has now ----------------
|
||||
|
||||
public static string ModPath(string game) => Path.Combine(Triforce.Logic.Mods.FolderOf(game), ModFolder);
|
||||
|
||||
/// <summary>The colours the game has now (the mod's marker), or null when the mod is not there. On is false when the
|
||||
/// player switched it off on the Mods page.</summary>
|
||||
public (Choice Colors, bool On, string Path)? Applied(string game)
|
||||
{
|
||||
var mods = Triforce.Logic.Mods.FolderOf(game);
|
||||
foreach (var path in new[] { Path.Combine(mods, ModFolder), Path.Combine(mods, "-" + ModFolder), Path.Combine(mods, "_" + ModFolder) })
|
||||
{
|
||||
var marker = Path.Combine(path, Marker);
|
||||
if (!File.Exists(marker)) continue;
|
||||
try { return (Choice.FromJson(JsonNode.Parse(File.ReadAllText(marker))?["colors"]), !System.IO.Path.GetFileName(path).StartsWith('-') && !System.IO.Path.GetFileName(path).StartsWith('_'), path); }
|
||||
catch (Exception e) when (e is IOException || e is JsonException) { return (new Choice(), true, path); }
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Other mods that are on and carry Link's model or one of the colour maps: the page says which wins.</summary>
|
||||
public IReadOnlyList<string> Others(string game)
|
||||
{
|
||||
try
|
||||
{
|
||||
return Mods.ListGame(game, false).Where(m => m.On && !m.Path.EndsWith(ModFolder, StringComparison.OrdinalIgnoreCase)
|
||||
&& m.Files.Any(f => f.StartsWith("model/player_child", StringComparison.Ordinal) || f.StartsWith("model/player_adult", StringComparison.Ordinal)))
|
||||
.Select(m => m.Info?.Name is { Length: > 0 } n ? n : m.Name).ToList();
|
||||
}
|
||||
catch (Exception) { return Array.Empty<string>(); }
|
||||
}
|
||||
|
||||
// ---------------- calibration: where each part lies on each colour map ----------------
|
||||
|
||||
/// <summary>One colour map's parts: up to two (slot 0 in the mask's red, slot 1 in its green), each with the median
|
||||
/// linear luminance of its texels before (Ym) and after (Qm) the calibration colour of luminance Ty. OOTRR keeps the
|
||||
/// shading and compresses brightness: a colour of luminance Y comes out near Qm * (Y / Ty)^0.62 at the median texel.</summary>
|
||||
/// ((11-30) G: the contrast OOTRR gives its texels, after_Y ~ before_Y^G over the part's texels (0.98 to 1.6 on Link's maps:
|
||||
/// the live tint follows it, or the tint and OOTRR's exact map differed enough that a pick seemed to "switch back")
|
||||
public sealed record CalMap(string Texture, string[] Parts, float[] Ym, float[] Qm, float[] Ty, float[] G, int Width, int Height, byte[] Mask);
|
||||
|
||||
static readonly string[] Trims = { "leather_trim", "goron_trim" };
|
||||
const string Primary = "#ff00ff", Trim = "#00ffff";
|
||||
|
||||
public string CalFolder(string stamp) => Path.Combine(Home, stamp, "cal5"); // ((11-30) cal5: with G and the mask by strength, made again once
|
||||
static JsonArray Floats(float[] v) => new(v.Select(x => (JsonNode?)x).ToArray());
|
||||
|
||||
/// <summary>The calibration, read from the cache or made (one colors-preview of every part: about 15 s, once per game).</summary>
|
||||
public async Task<IReadOnlyList<CalMap>> CalibrateAsync(string game, string stamp, CancellationToken token)
|
||||
{
|
||||
var dir = CalFolder(stamp);
|
||||
var index = Path.Combine(dir, "cal.json");
|
||||
if (File.Exists(index))
|
||||
try { return ReadCal(dir, index); } catch (Exception e) when (e is IOException || e is JsonException || e is InvalidDataException) { ctx.Log.Write("character: calibration unreadable, made again: " + e.Message); }
|
||||
ctx.Require(Home);
|
||||
var work = Path.Combine(Home, "work", "cal-" + Guid.NewGuid().ToString("N")[..8]);
|
||||
Directory.CreateDirectory(work);
|
||||
try
|
||||
{
|
||||
var args = new List<string> { "colors-preview", Romfs(game), work, "custom", "triforce" };
|
||||
args.AddRange(Parts.Select(p => p.Id + "=" + (Trims.Contains(p.Id) ? Trim : Primary)));
|
||||
var run = await Tool.RunAsync(args, null, token).ConfigureAwait(false);
|
||||
var maps = new List<CalMap>();
|
||||
foreach (var (tex, parts) in PreviewLines(run.Out))
|
||||
{
|
||||
var before = Path.Combine(work, tex + "_before.png");
|
||||
var after = Path.Combine(work, tex + "_after.png");
|
||||
if (!File.Exists(before) || !File.Exists(after) || parts.Count == 0) continue;
|
||||
var (w, h, b) = Png.Decode(File.ReadAllBytes(before));
|
||||
var (w2, h2, a) = Png.Decode(File.ReadAllBytes(after));
|
||||
if (w != w2 || h != h2) continue;
|
||||
var slots = parts.Take(2).ToArray();
|
||||
var mask = new byte[w * h * 4];
|
||||
var yb = slots.Select(_ => new List<float>()).ToArray();
|
||||
var ya = slots.Select(_ => new List<float>()).ToArray();
|
||||
for (var i = 0; i < w * h; i++)
|
||||
{
|
||||
int dr = a[4 * i] - b[4 * i], dg = a[4 * i + 1] - b[4 * i + 1], db = a[4 * i + 2] - b[4 * i + 2];
|
||||
// ((11-30) by how far OOTRR moved it: the leather 100 and more (of 765), metal, buckles and charms under 60
|
||||
// and nearly grey; the tint fades in from 20 to 100, so it no longer paints the buckle and ring)
|
||||
var moved = Math.Abs(dr) + Math.Abs(dg) + Math.Abs(db);
|
||||
if (moved < 20) continue;
|
||||
// (which part moved it: the trim parts were set to cyan, the others to magenta)
|
||||
var slot = 0;
|
||||
if (slots.Length > 1)
|
||||
{
|
||||
var cyan = a[4 * i + 1] - a[4 * i]; // (cyan: green over red; magenta: red over green)
|
||||
var trimSlot = Array.FindIndex(slots, s => Trims.Contains(s));
|
||||
slot = trimSlot >= 0 ? (cyan > 0 ? trimSlot : 1 - trimSlot) : 0;
|
||||
}
|
||||
mask[4 * i + slot] = (byte)Math.Clamp((moved - 20) * 255 / 80, 0, 255);
|
||||
mask[4 * i + 3] = 255;
|
||||
if (moved < 60) continue; // (the part's own texels alone in its medians and contrast)
|
||||
yb[slot].Add(Lum(b, 4 * i));
|
||||
ya[slot].Add(Lum(a, 4 * i));
|
||||
}
|
||||
var ym = new float[slots.Length]; var qm = new float[slots.Length]; var ty = new float[slots.Length]; var g = new float[slots.Length];
|
||||
for (var s = 0; s < slots.Length; s++)
|
||||
{
|
||||
ty[s] = LumOf(Trims.Contains(slots[s]) ? Trim : Primary);
|
||||
g[s] = Contrast(yb[s], ya[s]);
|
||||
ym[s] = yb[s].Count > 0 ? Math.Max(Median(yb[s]), 1e-4f) : 0.05f;
|
||||
qm[s] = ya[s].Count > 0 ? Math.Max(Median(ya[s]), 1e-4f) : 0.1f;
|
||||
}
|
||||
maps.Add(new CalMap(tex, slots, ym, qm, ty, g, w, h, Blur(mask, w, h)));
|
||||
}
|
||||
Directory.CreateDirectory(dir);
|
||||
var j = new JsonArray();
|
||||
foreach (var m in maps)
|
||||
{
|
||||
await File.WriteAllBytesAsync(Path.Combine(dir, m.Texture + ".mask"), m.Mask, token).ConfigureAwait(false);
|
||||
j.Add(new JsonObject
|
||||
{
|
||||
["tex"] = m.Texture, ["parts"] = new JsonArray(m.Parts.Select(p => (JsonNode?)p).ToArray()), ["w"] = m.Width, ["h"] = m.Height,
|
||||
["ym"] = Floats(m.Ym), ["qm"] = Floats(m.Qm), ["ty"] = Floats(m.Ty), ["g"] = Floats(m.G),
|
||||
});
|
||||
}
|
||||
await File.WriteAllTextAsync(index, j.ToJsonString(), token).ConfigureAwait(false);
|
||||
ctx.Log.Write("character: calibration made, " + maps.Count + " colour maps");
|
||||
return maps;
|
||||
}
|
||||
finally { try { Directory.Delete(work, true); } catch (Exception) { } }
|
||||
}
|
||||
|
||||
static IReadOnlyList<CalMap> ReadCal(string dir, string index)
|
||||
{
|
||||
var list = new List<CalMap>();
|
||||
foreach (var n in JsonNode.Parse(File.ReadAllText(index)) as JsonArray ?? new JsonArray())
|
||||
{
|
||||
var tex = (string)n!["tex"]!;
|
||||
if (tex.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) continue;
|
||||
int w = (int)n["w"]!, h = (int)n["h"]!;
|
||||
var mask = File.ReadAllBytes(Path.Combine(dir, tex + ".mask"));
|
||||
if (mask.Length != w * h * 4) throw new InvalidDataException("a mask of the wrong size");
|
||||
float[] F(string k) => ((JsonArray)n[k]!).Select(x => (float)x!).ToArray();
|
||||
if (n["g"] is not JsonArray) throw new InvalidDataException("a calibration without the contrast (g)");
|
||||
list.Add(new CalMap(tex, ((JsonArray)n["parts"]!).Select(x => (string)x!).ToArray(), F("ym"), F("qm"), F("ty"), F("g"), w, h, mask));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>A mask softened by one texel, so the live tint has no hard stairs at its edges.</summary>
|
||||
static byte[] Blur(byte[] m, int w, int h)
|
||||
{
|
||||
var o = new byte[m.Length];
|
||||
for (var y = 0; y < h; y++)
|
||||
for (var x = 0; x < w; x++)
|
||||
for (var c = 0; c < 4; c++)
|
||||
{
|
||||
int s = 0, n = 0;
|
||||
for (var dy = -1; dy <= 1; dy++)
|
||||
for (var dx = -1; dx <= 1; dx++)
|
||||
{
|
||||
int xx = x + dx, yy = y + dy;
|
||||
if (xx < 0 || yy < 0 || xx >= w || yy >= h) continue;
|
||||
s += m[(yy * w + xx) * 4 + c]; n++;
|
||||
}
|
||||
o[(y * w + x) * 4 + c] = (byte)(s / n);
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
static float Lin(byte v) { var x = v / 255f; return x <= 0.04045f ? x / 12.92f : MathF.Pow((x + 0.055f) / 1.055f, 2.4f); }
|
||||
static float Lum(byte[] p, int i) => 0.2126f * Lin(p[i]) + 0.7152f * Lin(p[i + 1]) + 0.0722f * Lin(p[i + 2]);
|
||||
public static float LumOf(string hex)
|
||||
{
|
||||
var c = Convert.FromHexString(hex[1..]);
|
||||
return 0.2126f * Lin(c[0]) + 0.7152f * Lin(c[1]) + 0.0722f * Lin(c[2]);
|
||||
}
|
||||
static float Median(List<float> v) { v.Sort(); return v[v.Count / 2]; }
|
||||
|
||||
/// <summary>((11-30)) The slope of log(after) on log(before) over a part's texels (least squares), in [0.7, 1.8]; 1 when too few
|
||||
/// texels or no spread. Measured on young Link's belt: 1.15 for red, 0.98 for blue; his vest: 1.6.</summary>
|
||||
internal static float Contrast(List<float> before, List<float> after)
|
||||
{
|
||||
double sx = 0, sy = 0, sxx = 0, sxy = 0; var n = 0;
|
||||
for (var i = 0; i < before.Count && i < after.Count; i++)
|
||||
{
|
||||
if (before[i] < 1e-4f || after[i] < 1e-4f) continue;
|
||||
double x = Math.Log(before[i]), y = Math.Log(after[i]);
|
||||
sx += x; sy += y; sxx += x * x; sxy += x * y; n++;
|
||||
}
|
||||
if (n < 64) return 1f;
|
||||
var vx = sxx - sx * sx / n;
|
||||
if (vx < 1e-6) return 1f;
|
||||
return (float)Math.Clamp((sxy - sx * sy / n) / vx, 0.7, 1.8);
|
||||
}
|
||||
|
||||
/// <summary>colors-preview's lines: "Tex_Name: part #RRGGBB, part2 #RRGGBB, n of m blocks changed ...".</summary>
|
||||
static IEnumerable<(string Tex, List<string> Parts)> PreviewLines(string output)
|
||||
{
|
||||
foreach (var raw in output.Split('\n'))
|
||||
{
|
||||
var l = raw.Trim();
|
||||
var colon = l.IndexOf(": ", StringComparison.Ordinal);
|
||||
if (colon <= 0) continue;
|
||||
var tex = l[..colon];
|
||||
if (tex.Contains(' ') || tex.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) continue;
|
||||
var parts = Regex.Matches(l[(colon + 2)..], @"([a-z_]+) #[0-9A-Fa-f]{6}").Select(m => m.Groups[1].Value).Where(p => Parts.Any(x => x.Id == p)).ToList();
|
||||
if (parts.Count > 0) yield return (tex, parts);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------- the exact preview ----------------
|
||||
|
||||
/// <summary>OOTRR's own recoloured colour maps for one age's colours (pictures of the colour maps it would write, at the
|
||||
/// size colors-preview gives them). Keys are the texture names as the model names them (OOTRR's renamed copy of the cloth
|
||||
/// tile is given under the tile's own name).</summary>
|
||||
public async Task<Dictionary<string, (int W, int H, byte[] Rgba)>> PreviewAsync(string game, IReadOnlyDictionary<string, string> colors, CancellationToken token)
|
||||
{
|
||||
var maps = new Dictionary<string, (int, int, byte[])>(StringComparer.Ordinal);
|
||||
if (colors.Count == 0) return maps;
|
||||
ctx.Require(Home);
|
||||
var work = Path.Combine(Home, "work", "pv-" + Guid.NewGuid().ToString("N")[..8]);
|
||||
Directory.CreateDirectory(work);
|
||||
try
|
||||
{
|
||||
var args = new List<string> { "colors-preview", Romfs(game), work, "custom", "triforce" };
|
||||
args.AddRange(colors.Select(kv => kv.Key + "=" + kv.Value));
|
||||
var run = await Tool.RunAsync(args, null, token).ConfigureAwait(false);
|
||||
using var src = new FolderSource(Romfs(game));
|
||||
var zs = new Zs(src);
|
||||
foreach (var (tex, _) in PreviewLines(run.Out))
|
||||
{
|
||||
var after = Path.Combine(work, tex + "_after.png");
|
||||
var before = Path.Combine(work, tex + "_before.png");
|
||||
if (!File.Exists(after) || !File.Exists(before)) continue;
|
||||
var a = Png.Decode(await File.ReadAllBytesAsync(after, token).ConfigureAwait(false));
|
||||
var b = Png.Decode(await File.ReadAllBytesAsync(before, token).ConfigureAwait(false));
|
||||
var name = ModelName(tex);
|
||||
// (colors-preview's pictures are small: the change they show is carried onto the game's own full-size map)
|
||||
var full = LinkScene.Texture(src, zs, name);
|
||||
maps[name] = full is { } f && a.Width == b.Width && a.Height == b.Height ? Carry(f, b, a) : a;
|
||||
token.ThrowIfCancellationRequested();
|
||||
}
|
||||
return maps;
|
||||
}
|
||||
finally { try { Directory.Delete(work, true); } catch (Exception) { } }
|
||||
}
|
||||
|
||||
static readonly float[] ToLin = Enumerable.Range(0, 256).Select(i => Lin((byte)i)).ToArray();
|
||||
static readonly byte[] ToSrgb = Enumerable.Range(0, 4096).Select(i =>
|
||||
{
|
||||
var x = i / 4095f;
|
||||
var s = x <= 0.0031308f ? x * 12.92f : 1.055f * MathF.Pow(x, 1 / 2.4f) - 0.055f;
|
||||
return (byte)Math.Clamp(MathF.Round(s * 255), 0, 255);
|
||||
}).ToArray();
|
||||
|
||||
/// <summary>The full-size map with the change from before to after (two small pictures of it) carried over: each texel is
|
||||
/// scaled, channel by channel in linear light, as the small pictures change at its place.</summary>
|
||||
static (int, int, byte[]) Carry((int W, int H, byte[] Rgba) full, (int Width, int Height, byte[] Rgba) before, (int Width, int Height, byte[] Rgba) after)
|
||||
{
|
||||
// ((11-30) E 0.012 -> 0.002: measured on young Link's belt at #FF0000, 0.012 made the red 11% darker than OOTRR's own
|
||||
// picture (0.220 against 0.246 linear at the median), 0.002 within 1%; the factor is held to 16 where a texel was near black)
|
||||
const float E = 0.002f, MaxGain = 16f;
|
||||
int w = full.W, h = full.H, sw = before.Width, sh = before.Height;
|
||||
var o = new byte[w * h * 4];
|
||||
Parallel.For(0, h, y =>
|
||||
{
|
||||
var fy = Math.Clamp((y + .5f) * sh / h - .5f, 0, sh - 1);
|
||||
int y0 = (int)fy, y1 = Math.Min(y0 + 1, sh - 1); var ty = fy - y0;
|
||||
for (var x = 0; x < w; x++)
|
||||
{
|
||||
var fx = Math.Clamp((x + .5f) * sw / w - .5f, 0, sw - 1);
|
||||
int x0 = (int)fx, x1 = Math.Min(x0 + 1, sw - 1); var tx = fx - x0;
|
||||
var i = (y * w + x) * 4;
|
||||
for (var c = 0; c < 3; c++)
|
||||
{
|
||||
float S(byte[] p, int xx, int yy) => ToLin[p[(yy * sw + xx) * 4 + c]];
|
||||
float Bi(byte[] p) => (S(p, x0, y0) * (1 - tx) + S(p, x1, y0) * tx) * (1 - ty) + (S(p, x0, y1) * (1 - tx) + S(p, x1, y1) * tx) * ty;
|
||||
var v = ToLin[full.Rgba[i + c]] * Math.Min((Bi(after.Rgba) + E) / (Bi(before.Rgba) + E), MaxGain);
|
||||
o[i + c] = ToSrgb[Math.Clamp((int)(v * 4095 + .5f), 0, 4095)];
|
||||
}
|
||||
o[i + 3] = full.Rgba[i + 3];
|
||||
}
|
||||
});
|
||||
return (w, h, o);
|
||||
}
|
||||
|
||||
/// <summary>OOTRR's renamed copies under the name the game's models give them.</summary>
|
||||
public static string ModelName(string tex) => tex switch
|
||||
{
|
||||
"Angin_Tile_L_Alb" => "Angin_Tile_A_Alb",
|
||||
_ => tex,
|
||||
};
|
||||
|
||||
// ---------------- apply: the mod ----------------
|
||||
|
||||
static readonly string[] RomfsNeeds = { "Model", "Tex", "Pack" };
|
||||
static string Romfs(string game)
|
||||
{
|
||||
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. Build the game again first.");
|
||||
return romfs;
|
||||
}
|
||||
|
||||
/// <summary>The seed every colour build uses: the randomizer's defaults, made once (only the colours are taken from the
|
||||
/// build; the seed's own files are thrown away).</summary>
|
||||
async Task<string> SeedAsync(CancellationToken token)
|
||||
{
|
||||
var seed = Path.Combine(Home, "colors-" + Ootrr.Version + ".ootrr");
|
||||
if (File.Exists(seed)) return seed;
|
||||
var settings = Path.Combine(Home, "colors-settings.json");
|
||||
await File.WriteAllTextAsync(settings, "{}", token).ConfigureAwait(false);
|
||||
await Tool.RunAsync(new[] { "generate", settings, "TRIFORCECOLORS", seed }, null, token).ConfigureAwait(false);
|
||||
if (!File.Exists(seed)) throw new OotrrException("The randomizer made no seed for the colours.");
|
||||
return seed;
|
||||
}
|
||||
|
||||
const string ChildTile = "Angin_Tile_L_Alb", ChildTileMine = "Angin_Tile_Y_Alb";
|
||||
|
||||
/// <summary>Writes the mod for these colours (or takes it away when there are none) and returns the folder. progress: a
|
||||
/// line for the page.</summary>
|
||||
public async Task<string?> ApplyAsync(string game, Choice choice, Action<string>? progress, CancellationToken token)
|
||||
{
|
||||
var mods = Triforce.Logic.Mods.FolderOf(game);
|
||||
ctx.Require(mods);
|
||||
if (Mods.GameRuns(game)) throw new OotrrException("Close the game first: it reads its files when it starts.");
|
||||
var linkleMod = Linkle.Find(Mods, game);
|
||||
var linkle = choice.Hero == "linkle";
|
||||
if (linkle && linkleMod == null) throw new OotrrException("Get Linkle first: she is a mod from GameBanana, downloaded on the Character page.");
|
||||
if (choice.Empty) { Remove(game); SetLinkle(game, linkleMod, false); return null; }
|
||||
// (what the colour tool dyes: all of Link's colours; for Linkle only adult hair, the game's own texture she wears)
|
||||
var ootrr = new[] { "child", "adult" }.ToDictionary(a => a, a => linkle
|
||||
? (a == "adult" && choice.Of(a).TryGetValue("hair", out var hh) ? new Dictionary<string, string> { ["hair"] = hh } : new Dictionary<string, string>())
|
||||
: new Dictionary<string, string>(choice.Of(a)));
|
||||
if (ootrr.Values.Any(d => d.Count > 0) && !Tool.Have) throw new OotrrException("The colour tool is not installed yet.");
|
||||
var romfs = Romfs(game);
|
||||
Directory.CreateDirectory(Home);
|
||||
var seed = ootrr.Values.Any(d => d.Count > 0) ? await SeedAsync(token).ConfigureAwait(false) : "";
|
||||
var work = Path.Combine(Home, "work", "apply-" + Guid.NewGuid().ToString("N")[..8]);
|
||||
Directory.CreateDirectory(work);
|
||||
var staging = Path.Combine(mods, ".colors-" + Guid.NewGuid().ToString("N")[..8]);
|
||||
try
|
||||
{
|
||||
progress?.Invoke("Dyeing the cloth");
|
||||
var ages = new[] { "child", "adult" }.Where(a => ootrr[a].Count > 0).ToList();
|
||||
await Task.WhenAll(ages.Select(age =>
|
||||
{
|
||||
var args = new List<string> { "build", seed, romfs, work, age, "--host", "nx2navi", "--colors", "custom", "--no-title-logo" };
|
||||
foreach (var (part, hex) in ootrr[age]) { args.Add("--color-part"); args.Add(part + "=" + hex); }
|
||||
return Tool.RunAsync(args, null, token);
|
||||
})).ConfigureAwait(false);
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
progress?.Invoke("Putting the colours in place");
|
||||
var into = Path.Combine(staging, "romfs");
|
||||
Directory.CreateDirectory(Path.Combine(into, "Model"));
|
||||
Directory.CreateDirectory(Path.Combine(into, "Tex"));
|
||||
var src = new FolderSource(romfs);
|
||||
var zs = new Zs(src);
|
||||
foreach (var age in ages)
|
||||
{
|
||||
var built = Path.Combine(work, age, "romfs");
|
||||
var child = age == "child";
|
||||
foreach (var f in Directory.EnumerateFiles(Path.Combine(built, "Tex"), "*.bntx.zs"))
|
||||
{
|
||||
var name = Path.GetFileName(f)[..^".bntx.zs".Length];
|
||||
if (linkle) { if (name == "Mt_Hairs_Player_Adult_Alb") File.Copy(f, Path.Combine(into, "Tex", Path.GetFileName(f)), true); continue; }
|
||||
var mine = name.Contains("_Adult", StringComparison.Ordinal) ? !child : name.Contains("_Child", StringComparison.Ordinal) ? child
|
||||
: (child ? !src.Exists("Tex/" + name + ".bntx.zs") || name.Contains("_Dark_", StringComparison.Ordinal) || name.StartsWith("Npc_Navi", StringComparison.Ordinal) : true);
|
||||
if (!mine) continue;
|
||||
if (child && name == ChildTile)
|
||||
{
|
||||
// (young Link's own copy of the tile, under a name adult Link's models do not use)
|
||||
var data = Rename(zs, "Tex/" + name + ".bntx.zs", await File.ReadAllBytesAsync(f, token).ConfigureAwait(false), ChildTile, ChildTileMine);
|
||||
await File.WriteAllBytesAsync(Path.Combine(into, "Tex", ChildTileMine + ".bntx.zs"), data, token).ConfigureAwait(false);
|
||||
continue;
|
||||
}
|
||||
var to = Path.Combine(into, "Tex", Path.GetFileName(f));
|
||||
if (child && File.Exists(to)) continue; // (a map both ages write in place: adult Link's wins)
|
||||
File.Copy(f, to, true);
|
||||
}
|
||||
var modelDir = Path.Combine(built, "Model");
|
||||
if (linkle || !Directory.Exists(modelDir)) continue;
|
||||
foreach (var f in Directory.EnumerateFiles(modelDir, "*.bfres.zs"))
|
||||
{
|
||||
var name = Path.GetFileName(f);
|
||||
var isChild = name.Contains("_Child", StringComparison.Ordinal);
|
||||
var both = name.StartsWith("Npc_Navi", StringComparison.Ordinal); // (Navi: either build's, adult Link's last)
|
||||
if (isChild != child && !both) continue;
|
||||
var data = await File.ReadAllBytesAsync(f, token).ConfigureAwait(false);
|
||||
if (child) data = Rename(zs, "Model/" + name, data, ChildTile, ChildTileMine);
|
||||
await File.WriteAllBytesAsync(Path.Combine(into, "Model", name), data, token).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
if (linkle)
|
||||
{
|
||||
progress?.Invoke("Dyeing Linkle's clothes");
|
||||
using var her = Linkle.Source(linkleMod!, game);
|
||||
var hzs = new Zs(her);
|
||||
var written = new List<LinklePiece>();
|
||||
foreach (var age in new[] { "child", "adult" })
|
||||
{
|
||||
var dyed = Linkle.Dye(her, hzs, age, choice.Of(age));
|
||||
foreach (var (tex, (writeName, bntx, _)) in dyed)
|
||||
{
|
||||
await File.WriteAllBytesAsync(Path.Combine(into, "Tex", writeName + ".bntx.zs"), Linkle.Pack(hzs, "Tex/" + writeName + ".bntx.zs", bntx), token).ConfigureAwait(false);
|
||||
written.AddRange(Linkle.Pieces.Where(kv => kv.Key.Age == age).SelectMany(kv => kv.Value).Where(p => (p.Copy ?? p.Texture) == tex));
|
||||
}
|
||||
token.ThrowIfCancellationRequested();
|
||||
}
|
||||
foreach (var (model, data) in Linkle.PatchModels(her, hzs, written))
|
||||
await File.WriteAllBytesAsync(Path.Combine(into, model.Replace('/', Path.DirectorySeparatorChar)), data, token).ConfigureAwait(false);
|
||||
}
|
||||
if (!Directory.EnumerateFiles(into, "*", SearchOption.AllDirectories).Any())
|
||||
{
|
||||
// (Linkle in her own colours: nothing to write, she only goes on)
|
||||
Remove(game);
|
||||
SetLinkle(game, linkleMod, linkle);
|
||||
return null;
|
||||
}
|
||||
var opts = new JsonSerializerOptions { WriteIndented = true };
|
||||
await File.WriteAllTextAsync(Path.Combine(staging, "triforce_mod.json"), new JsonObject
|
||||
{
|
||||
["name"] = "Link's colors", ["author"] = "Triforce · Character page",
|
||||
}.ToJsonString(opts), token).ConfigureAwait(false);
|
||||
await File.WriteAllTextAsync(Path.Combine(staging, Marker), new JsonObject
|
||||
{
|
||||
["colors"] = choice.ToJson(), ["ootrr"] = Ootrr.Version, ["made"] = DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture),
|
||||
}.ToJsonString(opts), token).ConfigureAwait(false);
|
||||
token.ThrowIfCancellationRequested();
|
||||
|
||||
// (in place: the old one goes aside first, the new one moves in, the old one goes; a switched-off one stays off)
|
||||
var old = Applied(game);
|
||||
var dest = old is { On: false } o ? o.Path : Path.Combine(mods, ModFolder);
|
||||
string? aside = null;
|
||||
if (old != null)
|
||||
{
|
||||
aside = Path.Combine(mods, ".colors-old-" + Guid.NewGuid().ToString("N")[..8]);
|
||||
Directory.Move(old.Value.Path, aside);
|
||||
}
|
||||
try { Directory.Move(staging, dest); }
|
||||
catch
|
||||
{
|
||||
if (aside != null) try { Directory.Move(aside, old!.Value.Path); aside = null; } catch (Exception) { }
|
||||
throw;
|
||||
}
|
||||
if (aside != null) try { Directory.Delete(aside, true); } catch (Exception e) { ctx.Log.Write("character: the old colours' folder stays: " + e.Message); }
|
||||
ctx.Log.Write("character: colours applied in " + dest);
|
||||
SetLinkle(game, linkleMod, linkle);
|
||||
return dest;
|
||||
}
|
||||
finally
|
||||
{
|
||||
try { if (Directory.Exists(staging)) Directory.Delete(staging, true); } catch (Exception) { }
|
||||
try { Directory.Delete(work, true); } catch (Exception) { }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Linkle's mod on (she is played) or off (Link is).</summary>
|
||||
void SetLinkle(string game, Mod? mod, bool on)
|
||||
{
|
||||
if (mod == null || mod.On == on) return;
|
||||
Mods.SetOn(Triforce.Logic.Mods.FolderOf(game), mod, on);
|
||||
ctx.Log.Write("character: Linkle " + (on ? "on" : "off"));
|
||||
}
|
||||
|
||||
/// <summary>Takes the colours' mod away: the game has its own colours again.</summary>
|
||||
public void Remove(string game)
|
||||
{
|
||||
if (Mods.GameRuns(game)) throw new OotrrException("Close the game first: it reads its files when it starts.");
|
||||
var old = Applied(game);
|
||||
if (old == null) return;
|
||||
ctx.Require(old.Value.Path);
|
||||
Directory.Delete(old.Value.Path, true);
|
||||
ctx.Log.Write("character: colours taken away (" + old.Value.Path + ")");
|
||||
}
|
||||
|
||||
/// <summary>Takes away what a stopped apply left in the mods folder (.colors-*: never a folder the game reads).</summary>
|
||||
public void LeftOvers(string game)
|
||||
{
|
||||
var mods = Triforce.Logic.Mods.FolderOf(game);
|
||||
if (!ctx.Allowed(mods) || !Directory.Exists(mods)) return;
|
||||
foreach (var d in Directory.GetDirectories(mods, ".colors-*"))
|
||||
try { Directory.Delete(d, true); } catch (Exception) { }
|
||||
}
|
||||
|
||||
/// <summary>A .zs file with one name changed to another of the same length (every place it is written), packed again with
|
||||
/// the game's dictionary for that file.</summary>
|
||||
static byte[] Rename(Zs zs, string romfsPath, byte[] packed, string from, string to)
|
||||
{
|
||||
if (from.Length != to.Length) throw new ArgumentException("names of different lengths");
|
||||
var data = zs.Unpack(romfsPath, packed);
|
||||
byte[] f = Encoding.ASCII.GetBytes(from), t = Encoding.ASCII.GetBytes(to);
|
||||
var n = 0;
|
||||
for (var i = data.AsSpan().IndexOf(f); i >= 0;)
|
||||
{
|
||||
t.CopyTo(data, i); n++;
|
||||
var next = data.AsSpan(i + f.Length).IndexOf(f);
|
||||
i = next < 0 ? -1 : i + f.Length + next;
|
||||
}
|
||||
if (n == 0) return packed;
|
||||
zs.Dictionaries.TryGetValue(Zs.DictionaryFor(romfsPath), out var dict);
|
||||
using var c = new Compressor(9);
|
||||
if (dict != null) c.LoadDictionary(dict);
|
||||
return c.Wrap(data).ToArray();
|
||||
}
|
||||
}
|
||||
167
launcher/Logic/Character/Linkle.cs
Normal file
167
launcher/Logic/Character/Linkle.cs
Normal file
@@ -0,0 +1,167 @@
|
||||
// (Triforce, 11-29) Linkle on the Character page: "Playable Linkle - Total Conversion" by ThatGuyOnCops
|
||||
// (https://gamebanana.com/mods/746375), a mod the launcher downloads from its GameBanana page on the player's word and
|
||||
// installs into the mods folder like any other (its license allows downloading and installing it; nothing of it ships with
|
||||
// Triforce). Choosing Link or Linkle switches that mod off or on.
|
||||
//
|
||||
// Her colours: the randomizer's colour tool cannot read her textures (some are uncompressed, the rest it does not edit), so
|
||||
// the launcher dyes them itself (Core TextureRecolor: the same colour-band rule). Each part names the textures it dyes and the
|
||||
// band of each; a texture she shares with the game's other characters is dyed as a copy of her own (a name of the same length,
|
||||
// her model pointed at it). Adult hair is the game's own BC7 texture, which the colour tool does dye (LinkColors).
|
||||
using System.Text;
|
||||
using Triforce.Core.GameFiles;
|
||||
using ZstdSharp;
|
||||
|
||||
namespace Triforce.Logic;
|
||||
|
||||
/// <summary>A texture a part dyes: its name, the band of the part on it, and the name of her own copy when the texture is shared
|
||||
/// (the copy is written under that name and Model is pointed at it).</summary>
|
||||
public sealed record LinklePiece(string Texture, ColorBand Band, string? Copy = null, string? Model = null);
|
||||
|
||||
public static class Linkle
|
||||
{
|
||||
public const int GameBananaId = 746375;
|
||||
public const string Name = "Playable Linkle - Total Conversion";
|
||||
public const string Author = "ThatGuyOnCops";
|
||||
public const string Page = "https://gamebanana.com/mods/746375";
|
||||
/// <summary>A file only this mod has (young Linkle's model), as the Mods list keeps file names.</summary>
|
||||
public const string Signature = "model/npc_kokiri_wc_002.player_linkle_child.bfres.zs";
|
||||
|
||||
const string ChildModel = "Model/Npc_Kokiri_WC_002.Player_Linkle_Child.bfres.zs";
|
||||
const string AdultModel = "Model/Player_Adult.Player_Adult.bfres.zs";
|
||||
|
||||
/// <summary>Her parts (ids as Link's where they mean the same, so a look can dress either).</summary>
|
||||
public static readonly LinkPart[] Parts =
|
||||
{
|
||||
new("kokiri", "Outfit", "Outfit", "child", "", "#4f7d2f"),
|
||||
new("kokiri", "Tunic and hood", "Outfit", "adult", "kokiri", "#3f8a2c"),
|
||||
new("skirt", "Skirt (every outfit)", "Outfit", "adult", "", "#c8641e"),
|
||||
new("kokiri_shirt", "Shirt and sleeves", "Outfit", "adult", "kokiri", "#d8d1bd"),
|
||||
new("goron", "Goron Tunic", "Outfit", "adult", "goron", "#b3262c"),
|
||||
new("zora", "Zora Tunic", "Outfit", "adult", "zora", "#2a4fb0"),
|
||||
new("flowers", "Flowers", "Outfit", "child", "", "#e0b84a"),
|
||||
new("shoes", "Shoes", "Leather", "child", "", "#8a7a3a"),
|
||||
new("kokiri_belt", "Belts and straps", "Leather", "adult", "", "#5b3f26"),
|
||||
new("boots", "Boots", "Leather", "adult", "", "#5b3f26"),
|
||||
new("gloves", "Gloves", "Leather", "adult", "", "#7a5534"),
|
||||
new("hair", "Hair", "Hair", "child,adult", "", "#e0b84a"),
|
||||
new("navi", "Liri", "Navi", "child,adult", "", "#d8e070"),
|
||||
};
|
||||
|
||||
static readonly ColorBand Green = new(70, 130, 0.15f);
|
||||
/// <summary>Her adult outfit sheets (Kokiri, Goron and Zora tunics share one layout): face and hair at the top left, the
|
||||
/// cape at the top right, the vest in the middle left, the shirt in the middle, the hood at the bottom left, the skirt panel
|
||||
/// below the shirt. The tunic is the vest, cape and hood; the skirt its panel.</summary>
|
||||
static readonly float[][] TunicRects = { new[] { 0f, .24f, .47f, .55f }, new[] { .62f, 0f, .97f, .25f }, new[] { 0f, .55f, .29f, .88f }, new[] { .29f, .55f, .50f, .80f } };
|
||||
static readonly float[][] SkirtRects = { new[] { .48f, .55f, .85f, .68f } };
|
||||
static readonly float[][] ShirtRects = { new[] { .46f, .25f, .68f, .55f }, new[] { .68f, .35f, .85f, .55f } };
|
||||
static readonly ColorBand Brown = new(8, 42, 0.18f, 0.04f, 0.6f);
|
||||
|
||||
/// <summary>(age, part) to the textures it dyes.</summary>
|
||||
public static readonly Dictionary<(string Age, string Part), LinklePiece[]> Pieces = new()
|
||||
{
|
||||
[("child", "kokiri")] = new[] { new LinklePiece("CmnTex_Chara_Mt_Cloth_Npc_Kokiri_WC_001_Alb.01", Green, "CmnTex_Chara_Mt_Cloth_Npc_Kokiri_WC_001_Alb.09", ChildModel) },
|
||||
[("child", "flowers")] = new[] { new LinklePiece("Mt_PantsParts_Player_Child_Alb", new ColorBand(28, 62, 0.25f)) },
|
||||
[("child", "shoes")] = new[] { new LinklePiece("CmnTex_Chara_Mt_Shoes_Npc_Kokiri_WC_001_Alb.03", ColorBand.All, "CmnTex_Chara_Mt_Shoes_Npc_Kokiri_WC_001_Alb.08", ChildModel) },
|
||||
[("child", "hair")] = new[] { new LinklePiece("Mt_Cloth_Parts_Player_Child_Alb", new ColorBand(30, 62, 0.15f)) },
|
||||
[("adult", "kokiri")] = new[]
|
||||
{
|
||||
new LinklePiece("Mt_Vest_Player_Adult_Alb", Green with { Rects = TunicRects }),
|
||||
new LinklePiece("Angin_Tile_A_Alb", ColorBand.All, "Angin_Tile_K_Alb", AdultModel),
|
||||
},
|
||||
// (the skirt panel in every outfit's sheet: she wears it with each tunic)
|
||||
[("adult", "skirt")] = new[]
|
||||
{
|
||||
new LinklePiece("Mt_Vest_Player_Adult_Alb", new ColorBand(0, 50, 0.3f, 0.1f) { Rects = SkirtRects }),
|
||||
new LinklePiece("Mt_Vest_Armor_Adult_Goron_Alb", new ColorBand(0, 50, 0.3f, 0.1f) { Rects = SkirtRects }),
|
||||
new LinklePiece("Mt_Angin_Armor_Adult_Zora_Alb", new ColorBand(0, 50, 0.3f, 0.1f) { Rects = SkirtRects }),
|
||||
},
|
||||
// (her shirt and sleeves: the white panel of the Kokiri outfit's own sheet; the game's Mt_Inner she wears is not it)
|
||||
[("adult", "kokiri_shirt")] = new[] { new LinklePiece("Mt_Vest_Player_Adult_Alb", new ColorBand(0, 360, 0, 0.1f) { Rects = ShirtRects }) },
|
||||
[("adult", "goron")] = new[] { new LinklePiece("Mt_Vest_Armor_Adult_Goron_Alb", new ColorBand(335, 22, 0.3f) { Rects = TunicRects }) },
|
||||
[("adult", "zora")] = new[] { new LinklePiece("Mt_Angin_Armor_Adult_Zora_Alb", new ColorBand(185, 250, 0.15f) { Rects = TunicRects }) },
|
||||
[("adult", "kokiri_belt")] = new[] { new LinklePiece("Mt_Leater_Upper_Player_Adult_Alb", new ColorBand(20, 50, 0.2f, 0.04f, 0.45f)) },
|
||||
[("adult", "boots")] = new[] { new LinklePiece("Mt_Boots_Player_Adult_Alb", Brown) },
|
||||
[("adult", "gloves")] = new[] { new LinklePiece("Mt_Glove_Player_Adult_Alb", Brown) },
|
||||
[("child", "navi")] = new[] { new LinklePiece("Npc_Liri_Wings_Alb.00", new ColorBand(48, 88, 0.12f)) },
|
||||
[("adult", "navi")] = new[] { new LinklePiece("Npc_Liri_Wings_Alb.00", new ColorBand(48, 88, 0.12f)) },
|
||||
// (adult hair: the game's own Mt_Hairs_Player_Adult_Alb, dyed by the colour tool: LinkColors)
|
||||
};
|
||||
|
||||
/// <summary>Her copies: the copy's name to (the model that points at it, the texture it is a copy of).</summary>
|
||||
public static readonly Dictionary<string, (string Model, string Original)> Copies = Pieces.Values.SelectMany(v => v)
|
||||
.Where(p => p.Copy != null && p.Model != null).DistinctBy(p => p.Copy).ToDictionary(p => p.Copy!, p => (p.Model!, p.Texture), StringComparer.Ordinal);
|
||||
|
||||
/// <summary>For the preview's scene: per model, the texture names her models will point at once dyed (original to copy).</summary>
|
||||
public static IReadOnlyDictionary<string, IReadOnlyDictionary<string, string>> SceneRenames { get; } = Copies
|
||||
.GroupBy(kv => kv.Value.Model).ToDictionary(g => g.Key, g => (IReadOnlyDictionary<string, string>)g.ToDictionary(kv => kv.Value.Original, kv => kv.Key, StringComparer.Ordinal), StringComparer.Ordinal);
|
||||
|
||||
/// <summary>The texture to read for a name (a copy reads its original).</summary>
|
||||
public static string Original(string name) => Copies.TryGetValue(name, out var c) ? c.Original : name;
|
||||
|
||||
/// <summary>The Linkle mod in this game's mods folder (on or off), or null.</summary>
|
||||
public static Mod? Find(ModManager mods, string game)
|
||||
{
|
||||
try
|
||||
{
|
||||
return mods.ListGame(game, true).FirstOrDefault(m => m.Info?.GameBananaId == GameBananaId || m.Files.Contains(Signature));
|
||||
}
|
||||
catch (Exception) { return null; }
|
||||
}
|
||||
|
||||
/// <summary>Her files over the game's: what the game shows when the mod is on.</summary>
|
||||
public static OverlaySource Source(Mod mod, string game) =>
|
||||
new(new FolderSource(Path.Combine(mod.Path, "romfs")), new FolderSource(Path.Combine(game, "romfs")));
|
||||
|
||||
/// <summary>Her textures dyed for one age's colours: texture name (as her models name it) to (the name it is written under,
|
||||
/// the dyed BNTX, its level 0 for the preview). A texture none of the colours touch is left out.</summary>
|
||||
public static Dictionary<string, (string WriteName, byte[] Bntx, (int W, int H, byte[] Rgba) Preview)> Dye(IGameSource src, Zs zs, string age, IReadOnlyDictionary<string, string> colors)
|
||||
{
|
||||
var byTex = new Dictionary<string, (LinklePiece Piece, List<(ColorBand, string)> Bands)>(StringComparer.Ordinal);
|
||||
foreach (var (part, hex) in colors)
|
||||
{
|
||||
if (!Pieces.TryGetValue((age, part), out var pieces)) continue;
|
||||
foreach (var p in pieces)
|
||||
{
|
||||
if (!byTex.TryGetValue(p.Texture, out var e)) byTex[p.Texture] = e = (p, new List<(ColorBand, string)>());
|
||||
e.Bands.Add((p.Band, hex));
|
||||
}
|
||||
}
|
||||
var outp = new Dictionary<string, (string, byte[], (int, int, byte[]))>(StringComparer.Ordinal);
|
||||
foreach (var (tex, (piece, bands)) in byTex)
|
||||
{
|
||||
var path = "Tex/" + tex + ".bntx.zs";
|
||||
if (!src.Exists(path)) continue;
|
||||
try
|
||||
{
|
||||
var (bntx, prev, _) = TextureRecolor.Recolor(zs.Unpack(path), tex, bands, piece.Copy);
|
||||
outp[piece.Copy ?? tex] = (piece.Copy ?? tex, bntx, prev);
|
||||
}
|
||||
catch (NotSupportedException) { }
|
||||
}
|
||||
return outp;
|
||||
}
|
||||
|
||||
/// <summary>Her models pointed at her copies (only for the copies written): model path to its new packed bytes.</summary>
|
||||
public static Dictionary<string, byte[]> PatchModels(IGameSource src, Zs zs, IEnumerable<LinklePiece> written)
|
||||
{
|
||||
var outp = new Dictionary<string, byte[]>(StringComparer.Ordinal);
|
||||
foreach (var g in written.Where(p => p.Copy != null && p.Model != null).GroupBy(p => p.Model!))
|
||||
{
|
||||
if (!src.Exists(g.Key)) continue;
|
||||
var data = zs.Unpack(g.Key);
|
||||
var n = 0;
|
||||
foreach (var p in g.DistinctBy(p => p.Texture)) n += TextureRecolor.ReplaceAll(data, p.Texture, p.Copy!);
|
||||
if (n > 0) outp[g.Key] = Pack(zs, g.Key, data);
|
||||
}
|
||||
return outp;
|
||||
}
|
||||
|
||||
/// <summary>A romfs file packed again with the game's dictionary for it.</summary>
|
||||
public static byte[] Pack(Zs zs, string romfsPath, byte[] data)
|
||||
{
|
||||
zs.Dictionaries.TryGetValue(Zs.DictionaryFor(romfsPath), out var dict);
|
||||
using var c = new Compressor(9);
|
||||
if (dict != null) c.LoadDictionary(dict);
|
||||
return c.Wrap(data).ToArray();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user