Files
Triforce-Source/launcher/Logic/Randomizer/RandoSchema.cs
ruckus7382sfgsgdf b527e29adb 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.
2026-11-28 10:54:41 -06:00

302 lines
18 KiB
C#
Raw Blame History

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