Triforce v0.2.0

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ruckus7382sfgsgdf
2026-11-10 19:32:48 -06:00
commit 34b3683441
1730 changed files with 554853 additions and 0 deletions

216
setup/Art.cs Normal file
View File

@@ -0,0 +1,216 @@
// The crest taken apart, so its stones can light one by one: the painted crest (assets/triforce.png) is the only picture in
// Setup, and these layers are cut from it at start-up rather than drawn. A stone is found by its colour inside its own corner of
// the crest (the gold and the dark ground have other hues), its mask closed, filled, grown a little and feathered.
// Dim the crest with the three stones drained of colour and darkened (unlit)
// Stones[i] the stone's own pixels (over Dim at full opacity they give the painting back): 0 emerald, 1 sapphire, 2 ruby
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace TriforceSetup;
static class Art
{
public const int Emerald = 0, Sapphire = 1, Ruby = 2;
public static BitmapSource Crest = null!, Dim = null!, Shine = null!;
public static readonly BitmapSource[] Stones = new BitmapSource[3];
/// Where each stone sits in the crest (0..1 of its box), and the light it throws
public static readonly Point[] Centre = new Point[3];
public static readonly uint[] Glow = { 0x7CFF9A, 0x8FC0FF, 0xFF7A84 };
// (hue window in degrees, least saturation, least value, and the stone's corner of the picture as fractions of it)
static readonly (double h0, double h1, double sat, double val, Rect box)[] Find =
{
(75, 175, 0.30, 0.10, new Rect(0.371, 0.171, 0.293, 0.310)),
(190, 265, 0.30, 0.10, new Rect(0.518, 0.481, 0.381, 0.395)),
(332, 18, 0.40, 0.12, new Rect(0.156, 0.481, 0.283, 0.310)),
};
public static void Load()
{
var source = new FormatConvertedBitmap(Program.Image("triforce.png"), PixelFormats.Bgra32, null, 0);
int w = source.PixelWidth, h = source.PixelHeight, stride = w * 4;
var px = new byte[stride * h];
source.CopyPixels(px, stride, 0);
Crest = Make(px, w, h);
var dim = (byte[])px.Clone();
var gems = new float[w * h]; // (how much of each pixel is stone, any of the three)
for (var s = 0; s < 3; s++)
{
var mask = Mask(px, w, h, Find[s]);
var lit = (byte[])px.Clone();
double sx = 0, sy = 0, sum = 0;
for (int y = 0, i = 0; y < h; y++)
for (var x = 0; x < w; x++, i++)
{
var m = mask[i];
var o = i * 4;
lit[o + 3] = (byte)(px[o + 3] * m + 0.5f);
if (m <= 0) continue;
gems[i] = Math.Max(gems[i], m);
sx += x * m; sy += y * m; sum += m;
// (unlit: the stone's own light and dark, as cold dark glass)
var lum = (0.114f * px[o] + 0.587f * px[o + 1] + 0.299f * px[o + 2]) / 255f;
dim[o] = (byte)(dim[o] * (1 - m) + (lum * 0.26f + 0.016f) * 255f * m + 0.5f);
dim[o + 1] = (byte)(dim[o + 1] * (1 - m) + (lum * 0.28f + 0.018f) * 255f * m + 0.5f);
dim[o + 2] = (byte)(dim[o + 2] * (1 - m) + (lum * 0.30f + 0.020f) * 255f * m + 0.5f);
}
Stones[s] = Make(lit, w, h);
Centre[s] = sum > 0 ? new Point(sx / sum / w, sy / sum / h) : new Point(0.5, 0.5);
}
Dim = Make(dim, w, h);
// (where the gleam may show: the crest's own pixels and no others, and of those the bright gold most. Light glances
// off polished metal; over the dark ground between it would be a grey wash, and over the stones it would bleach
// their colour, so both get little of it)
var shine = new byte[px.Length];
for (var i = 0; i < w * h; i++)
{
var o = i * 4;
var lum = (0.114f * px[o] + 0.587f * px[o + 1] + 0.299f * px[o + 2]) / 255f;
var bright = Math.Max(0f, Math.Min(1f, (lum - 0.30f) / 0.50f));
shine[o] = shine[o + 1] = shine[o + 2] = 255;
shine[o + 3] = (byte)(px[o + 3] * (0.04f + 0.96f * bright * bright) * (1 - 0.8f * gems[i]) + 0.5f);
}
Shine = Make(shine, w, h);
}
static BitmapSource Make(byte[] bgra, int w, int h)
{
var b = BitmapSource.Create(w, h, 96, 96, PixelFormats.Bgra32, null, bgra, w * 4);
b.Freeze();
return b;
}
static float[] Mask(byte[] px, int w, int h, (double h0, double h1, double sat, double val, Rect box) f)
{
var on = new bool[w * h];
int x0 = (int)(f.box.X * w), y0 = (int)(f.box.Y * h), x1 = (int)(f.box.Right * w), y1 = (int)(f.box.Bottom * h);
for (var y = y0; y < y1; y++)
for (var x = x0; x < x1; x++)
{
var o = (y * w + x) * 4;
if (px[o + 3] < 128) continue;
double b = px[o] / 255.0, g = px[o + 1] / 255.0, r = px[o + 2] / 255.0;
double max = Math.Max(r, Math.Max(g, b)), min = Math.Min(r, Math.Min(g, b)), d = max - min;
if (max < f.val || d < 1e-6 || d / max < f.sat) continue;
var hue = (max == r ? ((g - b) / d + 6) % 6 : max == g ? (b - r) / d + 2 : (r - g) / d + 4) * 60;
on[y * w + x] = f.h0 < f.h1 ? hue > f.h0 && hue < f.h1 : hue > f.h0 || hue < f.h1;
}
on = Grow(on, w, h, 2, true);
on = Grow(on, w, h, 2, false);
// (holes: the white sparkles inside a stone have no hue. Whatever the outside cannot reach belongs to the stone)
var outside = new bool[w * h];
var stack = new Stack<int>();
stack.Push(0);
outside[0] = true;
while (stack.Count > 0)
{
var i = stack.Pop();
int x = i % w, y = i / w;
if (x > 0 && !outside[i - 1] && !on[i - 1]) { outside[i - 1] = true; stack.Push(i - 1); }
if (x < w - 1 && !outside[i + 1] && !on[i + 1]) { outside[i + 1] = true; stack.Push(i + 1); }
if (y > 0 && !outside[i - w] && !on[i - w]) { outside[i - w] = true; stack.Push(i - w); }
if (y < h - 1 && !outside[i + w] && !on[i + w]) { outside[i + w] = true; stack.Push(i + w); }
}
for (var i = 0; i < on.Length; i++) on[i] = !outside[i];
on = Grow(on, w, h, 1, true);
var m = new float[w * h];
for (var i = 0; i < m.Length; i++) m[i] = on[i] ? 1 : 0;
for (var pass = 0; pass < 2; pass++) m = Soften(m, w, h);
return m;
}
/// The mask grown (or shrunk) by r pixels
static bool[] Grow(bool[] a, int w, int h, int r, bool grow)
{
var o = new bool[a.Length];
for (var y = 0; y < h; y++)
for (var x = 0; x < w; x++)
{
var hit = !grow;
for (var dy = -r; dy <= r && hit != grow; dy++)
for (var dx = -r; dx <= r; dx++)
{
int xx = x + dx, yy = y + dy;
var v = xx >= 0 && yy >= 0 && xx < w && yy < h && a[yy * w + xx];
if (v == grow) { hit = grow; break; }
}
o[y * w + x] = hit;
}
return o;
}
/// A 1-2-1 blur, across then down
static float[] Soften(float[] a, int w, int h)
{
var t = new float[a.Length];
var o = new float[a.Length];
for (var y = 0; y < h; y++)
for (var x = 0; x < w; x++)
{
var i = y * w + x;
t[i] = (a[i] * 2 + a[x > 0 ? i - 1 : i] + a[x < w - 1 ? i + 1 : i]) / 4;
}
for (var y = 0; y < h; y++)
for (var x = 0; x < w; x++)
{
var i = y * w + x;
o[i] = (t[i] * 2 + t[y > 0 ? i - w : i] + t[y < h - 1 ? i + w : i]) / 4;
}
return o;
}
/// Film grain for the hall: fine light and dark specks, tiled, at a few percent. It keeps the soft gradients from banding.
public static ImageBrush Grain()
{
const int n = 160;
var px = new byte[n * n * 4];
var r = new Random(11);
for (var i = 0; i < n * n; i++)
{
var v = r.NextDouble();
var light = r.Next(2) == 0;
var a = (byte)(v * v * 26);
// (premultiplied: white or black at a small alpha)
px[i * 4] = px[i * 4 + 1] = px[i * 4 + 2] = light ? a : (byte)0;
px[i * 4 + 3] = a;
}
var b = BitmapSource.Create(n, n, 96, 96, PixelFormats.Pbgra32, null, px, n * 4);
b.Freeze();
var brush = new ImageBrush(b) { TileMode = TileMode.Tile, Viewport = new Rect(0, 0, n, n), ViewportUnits = BrushMappingMode.Absolute, Stretch = Stretch.None };
brush.Freeze();
return brush;
}
/// The lattice in the light behind the crest: equilateral triangles, hairlines of gold
public static DrawingBrush Lattice(double side, Color line)
{
var rise = side * Math.Sqrt(3) / 2;
var g = new StreamGeometry();
using (var c = g.Open())
{
void L(double ax, double ay, double bx, double by) { c.BeginFigure(new Point(ax, ay), false, false); c.LineTo(new Point(bx, by), true, false); }
L(0, 0, side, 0);
L(0, rise, side, rise);
L(0, 0, side / 2, rise); L(side / 2, rise, side, 0);
L(0, rise * 2, side / 2, rise); L(side / 2, rise, side, rise * 2);
}
g.Freeze();
var pen = new Pen(new SolidColorBrush(line), 1);
pen.Freeze();
var d = new DrawingGroup();
d.Children.Add(new GeometryDrawing(Brushes.Transparent, null, new RectangleGeometry(new Rect(0, 0, side, rise * 2))));
d.Children.Add(new GeometryDrawing(null, pen, g));
d.ClipGeometry = new RectangleGeometry(new Rect(0, 0, side, rise * 2));
var brush = new DrawingBrush(d) { TileMode = TileMode.Tile, Viewport = new Rect(0, 0, side, rise * 2), ViewportUnits = BrushMappingMode.Absolute, Stretch = Stretch.None };
brush.Freeze();
return brush;
}
}

309
setup/Look.cs Normal file
View File

@@ -0,0 +1,309 @@
// How Triforce Setup looks and moves, in small pieces the window (Main.xaml) and the pages use: letter-spaced capitals, the
// progress line, the motes of light, and the animation helpers. The values are the style tokens (palette, type, motion) that
// the shader screen in the game window follows too.
using System;
using System.Diagnostics;
using System.Globalization;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
namespace TriforceSetup;
public static class Fx
{
/// --snapshot: pictures of the pages, so nothing moves and everything is at its resting value
public static bool Still;
/// The window is minimized: nothing is seen, so the motes and the progress lines stop redrawing
public static bool Paused;
public const int Fast = 120, Base = 220, Slow = 420;
public static readonly IEasingFunction Out = Frozen(new QuinticEase { EasingMode = EasingMode.EaseOut });
public static readonly IEasingFunction InOut = Frozen(new SineEase { EasingMode = EasingMode.EaseInOut });
static T Frozen<T>(T f) where T : Freezable { f.Freeze(); return f; }
public static Color Rgb(uint rgb, double a = 1) => Color.FromArgb((byte)Math.Round(a * 255), (byte)(rgb >> 16), (byte)(rgb >> 8), (byte)rgb);
public static SolidColorBrush Paint(uint rgb, double a = 1) => Frozen(new SolidColorBrush(Rgb(rgb, a)));
// (the palette: style_tokens.md section 2)
public const uint Ink900 = 0x0A0908, Ink800 = 0x12100C, Ink700 = 0x1B1711, Ink600 = 0x262017, Line = 0x2C2518,
TextHi = 0xF3EAD5, Text = 0xCDC2A8, TextDim = 0x948A70, TextFaint = 0x5F5744,
Gold100 = 0xFFF4CC, Gold300 = 0xF7DC8C, Gold500 = 0xE0B23E, Gold600 = 0xC4912A, Gold700 = 0x9A6A18, Gold900 = 0x3D2A08,
Good = 0x6BE07F, Bad = 0xFF6B76;
/// A value eased to its new place (or put there at once for a still picture)
public static void To(UIElement e, DependencyProperty p, double to, int ms, int delay = 0, IEasingFunction? ease = null)
{
if (Still || ms <= 0) { e.BeginAnimation(p, null); e.SetValue(p, to); return; }
e.BeginAnimation(p, new DoubleAnimation(to, TimeSpan.FromMilliseconds(ms)) { EasingFunction = ease ?? Out, BeginTime = TimeSpan.FromMilliseconds(delay) });
}
public static void To(Animatable e, DependencyProperty p, double to, int ms, int delay = 0, IEasingFunction? ease = null)
{
if (Still || ms <= 0) { e.BeginAnimation(p, null); e.SetValue(p, to); return; }
e.BeginAnimation(p, new DoubleAnimation(to, TimeSpan.FromMilliseconds(ms)) { EasingFunction = ease ?? Out, BeginTime = TimeSpan.FromMilliseconds(delay) });
}
/// From one value to another, once (a bloom, a gleam)
public static void Once(UIElement e, DependencyProperty p, double from, double to, int ms, int delay = 0, IEasingFunction? ease = null)
{
if (Still) { e.BeginAnimation(p, null); e.SetValue(p, to); return; }
e.BeginAnimation(p, new DoubleAnimation(from, to, TimeSpan.FromMilliseconds(ms)) { EasingFunction = ease ?? Out, BeginTime = TimeSpan.FromMilliseconds(delay) });
}
public static void Once(Animatable e, DependencyProperty p, double from, double to, int ms, int delay = 0, IEasingFunction? ease = null)
{
if (Still) { e.BeginAnimation(p, null); e.SetValue(p, to); return; }
e.BeginAnimation(p, new DoubleAnimation(from, to, TimeSpan.FromMilliseconds(ms)) { EasingFunction = ease ?? Out, BeginTime = TimeSpan.FromMilliseconds(delay) });
}
/// Breathing between two values for as long as the window lives (a still picture rests at the higher one)
public static void Breathe(UIElement e, DependencyProperty p, double low, double high, int cycleMs, int offsetMs = 0)
{
if (Still) { e.BeginAnimation(p, null); e.SetValue(p, high); return; }
var a = new DoubleAnimation(low, high, TimeSpan.FromMilliseconds(cycleMs / 2.0)) { EasingFunction = InOut, AutoReverse = true, RepeatBehavior = RepeatBehavior.Forever };
var clock = a.CreateClock();
e.ApplyAnimationClock(p, clock);
if (offsetMs > 0) clock.Controller?.Seek(TimeSpan.FromMilliseconds(offsetMs), TimeSeekOrigin.BeginTime);
}
/// Letter-spacing, which WPF's text has none of: hair spaces between the letters (whole text elements, so accents stay put)
public static string Track(string s, int gaps)
{
if (gaps <= 0 || s.Length < 2) return s;
var gap = new string(' ', gaps);
var sb = new StringBuilder(s.Length * (gaps + 1));
var e = StringInfo.GetTextElementEnumerator(s);
var first = true;
while (e.MoveNext())
{
if (!first) sb.Append(gap);
sb.Append(e.GetTextElement());
first = false;
}
return sb.ToString();
}
/// A page arriving: it fades in while it rises, its blocks a moment apart
public static void Arrive(Panel page)
{
var n = 0;
foreach (UIElement child in page.Children)
{
if (child.Visibility != Visibility.Visible && !Still) { child.BeginAnimation(UIElement.OpacityProperty, null); child.Opacity = 1; continue; }
var move = child.RenderTransform as TranslateTransform;
if (move == null || move.IsFrozen) child.RenderTransform = move = new TranslateTransform();
var delay = Math.Min(n++, 6) * 45;
Once(child, UIElement.OpacityProperty, 0, 1, 320, delay);
Once(move, TranslateTransform.YProperty, 12, 0, Slow, delay);
}
}
}
/// A label in capitals with letter-spacing: Label is the plain text, Gaps the hair spaces between letters
public sealed class Caps : TextBlock
{
public static readonly DependencyProperty LabelProperty = DependencyProperty.Register(nameof(Label), typeof(string), typeof(Caps),
new PropertyMetadata("", (d, _) => ((Caps)d).Apply()));
public static readonly DependencyProperty GapsProperty = DependencyProperty.Register(nameof(Gaps), typeof(int), typeof(Caps),
new PropertyMetadata(2, (d, _) => ((Caps)d).Apply()));
public string Label { get => (string)GetValue(LabelProperty); set => SetValue(LabelProperty, value); }
public int Gaps { get => (int)GetValue(GapsProperty); set => SetValue(GapsProperty, value); }
void Apply() => Text = Fx.Track((Label ?? "").ToUpper(CultureInfo.CurrentUICulture), Gaps);
}
/// The progress line: a fine gold line with a spark at its head and a glint that runs along it. Value 0..1 eases to its new
/// place; IsIndeterminate sweeps a piece of light along the track while the length of the work is unknown.
public sealed class ProgressLine : FrameworkElement
{
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register(nameof(Value), typeof(double), typeof(ProgressLine),
new FrameworkPropertyMetadata(0.0, (d, _) => ((ProgressLine)d).Wake()));
public static readonly DependencyProperty IsIndeterminateProperty = DependencyProperty.Register(nameof(IsIndeterminate), typeof(bool), typeof(ProgressLine),
new FrameworkPropertyMetadata(false, (d, _) => ((ProgressLine)d).Wake()));
public double Value { get => (double)GetValue(ValueProperty); set => SetValue(ValueProperty, value); }
public bool IsIndeterminate { get => (bool)GetValue(IsIndeterminateProperty); set => SetValue(IsIndeterminateProperty, value); }
static readonly Brush Track = Fx.Paint(0x2E2719);
static readonly Brush Spark = Fx.Paint(Fx.Gold100);
static readonly Brush Fill = Gradient(0, (Fx.Rgb(Fx.Gold600), 0), (Fx.Rgb(Fx.Gold500), 0.6), (Fx.Rgb(Fx.Gold300), 1));
static readonly Brush Glow = Gradient(90, (Fx.Rgb(Fx.Gold500, 0), 0), (Fx.Rgb(Fx.Gold500, 0.30), 0.5), (Fx.Rgb(Fx.Gold500, 0), 1));
static readonly Brush Glint = Gradient(0, (Fx.Rgb(Fx.Gold100, 0), 0), (Fx.Rgb(Fx.Gold100, 0.95), 0.5), (Fx.Rgb(Fx.Gold100, 0), 1));
static readonly Brush Sweep = Gradient(0, (Fx.Rgb(Fx.Gold500, 0), 0), (Fx.Rgb(Fx.Gold300), 0.5), (Fx.Rgb(Fx.Gold500, 0), 1));
static readonly Brush Halo = Radial((Fx.Rgb(Fx.Gold300, 0.60), 0), (Fx.Rgb(Fx.Gold500, 0.18), 0.5), (Fx.Rgb(Fx.Gold500, 0), 1));
static Brush Gradient(double angle, params (Color c, double at)[] stops)
{
var b = new LinearGradientBrush { StartPoint = new Point(0, 0), EndPoint = angle == 0 ? new Point(1, 0) : new Point(0, 1) };
foreach (var (c, at) in stops) b.GradientStops.Add(new GradientStop(c, at));
b.Freeze();
return b;
}
static Brush Radial(params (Color c, double at)[] stops)
{
var b = new RadialGradientBrush();
foreach (var (c, at) in stops) b.GradientStops.Add(new GradientStop(c, at));
b.Freeze();
return b;
}
readonly Stopwatch clock = Stopwatch.StartNew();
double shown, last;
bool ticking;
public ProgressLine()
{
Height = 16;
SnapsToDevicePixels = true;
IsVisibleChanged += (_, _) => Wake();
Unloaded += (_, _) => Sleep();
}
void Wake()
{
if (Fx.Still) { shown = Value; InvalidateVisual(); return; }
if (IsVisible && !ticking) { ticking = true; last = clock.Elapsed.TotalSeconds; CompositionTarget.Rendering += Tick; }
InvalidateVisual();
}
void Sleep()
{
if (ticking) { ticking = false; CompositionTarget.Rendering -= Tick; }
}
void Tick(object? sender, EventArgs e)
{
if (!IsVisible) { Sleep(); return; }
if (Fx.Paused) return;
var now = clock.Elapsed.TotalSeconds;
var dt = Math.Min(0.1, now - last);
last = now;
var target = Math.Max(0, Math.Min(1, Value));
// (eases to a new value in about 300 ms; a drop back to the start is taken at once)
shown = target < shown ? target : shown + (target - shown) * Math.Min(1, dt * 11);
if (Math.Abs(target - shown) < 0.0005) shown = target;
// (nothing left to move: a full or empty line at rest)
if (!IsIndeterminate && shown == target && (target <= 0 || target >= 1)) { Sleep(); }
InvalidateVisual();
}
protected override Size MeasureOverride(Size available) => new(double.IsInfinity(available.Width) ? 240 : available.Width, 16);
protected override void OnRender(DrawingContext dc)
{
var w = ActualWidth;
if (w < 4) return;
const double mid = 8;
var t = Fx.Still ? 1.35 : clock.Elapsed.TotalSeconds;
dc.DrawRectangle(Track, null, new Rect(0, mid - 1, w, 2));
if (IsIndeterminate)
{
var u = Fx.Still ? 0.42 : t / 1.6 % 1.0;
u = 0.5 - 0.5 * Math.Cos(u * Math.PI); // (ease in and out)
var len = w * 0.28;
var x = -len + (w + len) * u;
dc.PushClip(new RectangleGeometry(new Rect(0, 0, w, 16)));
dc.DrawRectangle(Glow, null, new Rect(x, mid - 6, len, 12));
dc.DrawRectangle(Sweep, null, new Rect(x, mid - 1, len, 2));
dc.Pop();
return;
}
var head = w * Math.Max(0, Math.Min(1, shown));
if (head < 0.5) return;
dc.DrawRectangle(Glow, null, new Rect(0, mid - 6, head, 12));
dc.DrawRectangle(Fill, null, new Rect(0, mid - 1, head, 2));
if (shown < 1)
{
// (the glint, along the part that is filled)
const double glint = 70;
var g = -glint + (head + glint) * (t / 2.4 % 1.0);
dc.PushClip(new RectangleGeometry(new Rect(0, 0, head, 16)));
dc.DrawRectangle(Glint, null, new Rect(g, mid - 1.5, glint, 3));
dc.Pop();
// (the spark at the head: a small diamond in its own light)
dc.DrawEllipse(Halo, null, new Point(head, mid), 11, 11);
dc.PushTransform(new RotateTransform(45, head, mid));
dc.DrawRectangle(Spark, null, new Rect(head - 2.6, mid - 2.6, 5.2, 5.2));
dc.Pop();
}
}
}
/// Motes of light drifting up through the hall: a few gold specks, slow, never the same twice. Light, not objects.
public sealed class Motes : FrameworkElement
{
struct Mote { public double X, Y, Rise, Sway, Turn, Size, Alpha, Period, Offset; }
readonly Mote[] motes;
readonly Stopwatch clock = Stopwatch.StartNew();
static readonly Brush Light = MakeLight();
bool ticking;
int frame;
static Brush MakeLight()
{
var b = new RadialGradientBrush();
b.GradientStops.Add(new GradientStop(Fx.Rgb(Fx.Gold100, 1), 0));
b.GradientStops.Add(new GradientStop(Fx.Rgb(Fx.Gold300, 0.55), 0.35));
b.GradientStops.Add(new GradientStop(Fx.Rgb(Fx.Gold500, 0), 1));
b.Freeze();
return b;
}
public Motes(int count = 26, int seed = 7)
{
IsHitTestVisible = false;
var r = new Random(seed);
motes = new Mote[count];
for (var i = 0; i < count; i++)
motes[i] = new Mote
{
X = r.NextDouble(), Y = 0.25 + r.NextDouble() * 0.75, Rise = 0.18 + r.NextDouble() * 0.30, Sway = 6 + r.NextDouble() * 16,
Turn = 0.6 + r.NextDouble() * 1.4, Size = 1.6 + r.NextDouble() * 3.2, Alpha = 0.16 + r.NextDouble() * 0.42,
Period = 11 + r.NextDouble() * 12, Offset = r.NextDouble() * 30,
};
IsVisibleChanged += (_, _) => Wake();
Unloaded += (_, _) => Sleep();
}
void Wake()
{
if (Fx.Still || !IsVisible || ticking) return;
ticking = true;
CompositionTarget.Rendering += Tick;
}
void Sleep()
{
if (ticking) { ticking = false; CompositionTarget.Rendering -= Tick; }
}
void Tick(object? sender, EventArgs e)
{
if (!IsVisible) { Sleep(); return; }
if (!Fx.Paused && (frame++ & 1) == 0) InvalidateVisual(); // (every other frame: they are slow)
}
protected override void OnRender(DrawingContext dc)
{
double w = ActualWidth, h = ActualHeight;
if (w < 10 || h < 10) return;
var t = Fx.Still ? 20.0 : clock.Elapsed.TotalSeconds;
foreach (var m in motes)
{
var u = (t + m.Offset) / m.Period % 1.0;
var fade = Math.Min(1, u / 0.18) * Math.Min(1, (1 - u) / 0.30); // (born softly, gone softly)
var x = m.X * w + Math.Sin(u * Math.PI * 2 * m.Turn + m.Offset) * m.Sway;
var y = (m.Y - u * m.Rise) * h;
dc.PushOpacity(m.Alpha * fade);
dc.DrawEllipse(Light, null, new Point(x, y), m.Size, m.Size);
dc.Pop();
}
}
}

838
setup/Main.xaml Normal file
View File

@@ -0,0 +1,838 @@
<!-- Triforce Setup's window. Loaded at run time (XamlReader): no x:Class, the code finds the named parts and wires them.
The look: a relic in a dark hall. Near-black, one warm light, the painted crest on the right with its three stones lit or
unlit as the work goes (Stage.cs builds that side into StageHost), the page's words and controls on the left. Gold is an
accent (labels, hairlines, the one main button), titles are parchment white. Tokens: Look.cs (Fx) and the lab's style_tokens.md.
One composed size, 1060 x 640: Shell scales the whole picture down on a screen too small for it. -->
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:shell="clr-namespace:System.Windows.Shell;assembly=PresentationFramework"
xmlns:t="clr-namespace:TriforceSetup;assembly=TriforceSetup"
Title="Triforce Setup" Width="1060" Height="640"
WindowStartupLocation="CenterScreen" AllowDrop="True" ResizeMode="CanMinimize"
UseLayoutRounding="True" SnapsToDevicePixels="True" TextOptions.TextFormattingMode="Display"
Background="#0A0908" Foreground="#CDC2A8" FontFamily="Segoe UI" FontSize="14">
<shell:WindowChrome.WindowChrome>
<shell:WindowChrome CaptionHeight="44" ResizeBorderThickness="0" GlassFrameThickness="0" CornerRadius="0" UseAeroCaptionButtons="False"/>
</shell:WindowChrome.WindowChrome>
<Window.Resources>
<!-- the hall -->
<SolidColorBrush x:Key="Ink900" Color="#0A0908"/>
<SolidColorBrush x:Key="Ink800" Color="#12100C"/>
<SolidColorBrush x:Key="Ink700" Color="#1B1711"/>
<SolidColorBrush x:Key="Ink600" Color="#262017"/>
<SolidColorBrush x:Key="Line" Color="#2C2518"/>
<SolidColorBrush x:Key="LineStrong" Color="#40361F"/>
<SolidColorBrush x:Key="LineGold" Color="#47E0B23E"/>
<SolidColorBrush x:Key="LineGoldHi" Color="#99E0B23E"/>
<!-- parchment -->
<SolidColorBrush x:Key="TextHi" Color="#F3EAD5"/>
<SolidColorBrush x:Key="Text" Color="#CDC2A8"/>
<SolidColorBrush x:Key="TextDim" Color="#948A70"/>
<SolidColorBrush x:Key="TextFaint" Color="#5F5744"/>
<!-- gold, and the two colours of news -->
<SolidColorBrush x:Key="Gold100" Color="#FFF4CC"/>
<SolidColorBrush x:Key="Gold300" Color="#F7DC8C"/>
<SolidColorBrush x:Key="Gold" Color="#E0B23E"/>
<SolidColorBrush x:Key="Gold900" Color="#3D2A08"/>
<SolidColorBrush x:Key="Good" Color="#6BE07F"/>
<SolidColorBrush x:Key="Bad" Color="#FF6B76"/>
<LinearGradientBrush x:Key="GoldBar" StartPoint="0,0" EndPoint="0,1">
<GradientStop Offset="0" Color="#FFF4CC"/><GradientStop Offset="0.12" Color="#F7DC8C"/><GradientStop Offset="0.48" Color="#E0B23E"/><GradientStop Offset="1" Color="#9A6A18"/>
</LinearGradientBrush>
<LinearGradientBrush x:Key="GoldBarHot" StartPoint="0,0" EndPoint="0,1">
<GradientStop Offset="0" Color="#FFFBEA"/><GradientStop Offset="0.14" Color="#FBE7A6"/><GradientStop Offset="0.5" Color="#ECC251"/><GradientStop Offset="1" Color="#A9761C"/>
</LinearGradientBrush>
<LinearGradientBrush x:Key="Fading" StartPoint="0,0" EndPoint="1,0">
<GradientStop Offset="0" Color="#47E0B23E"/><GradientStop Offset="0.7" Color="#2CE0B23E"/><GradientStop Offset="1" Color="#00E0B23E"/>
</LinearGradientBrush>
<LinearGradientBrush x:Key="Sheen" StartPoint="0,1" EndPoint="1,0">
<GradientStop Offset="0.3" Color="#00FFFFFF"/><GradientStop Offset="0.5" Color="#8CFFFFFF"/><GradientStop Offset="0.7" Color="#00FFFFFF"/>
</LinearGradientBrush>
<FontFamily x:Key="Serif">Palatino Linotype, Book Antiqua, Georgia</FontFamily>
<FontFamily x:Key="Mono">Cascadia Mono, Consolas</FontFamily>
<!-- words -->
<Style x:Key="Eyebrow" TargetType="t:Caps">
<Setter Property="Gaps" Value="1"/>
<Setter Property="FontSize" Value="10.5"/>
<Setter Property="FontWeight" Value="SemiBold"/>
<Setter Property="Foreground" Value="{StaticResource Gold}"/>
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>
<Style x:Key="FieldLabel" TargetType="t:Caps" BasedOn="{StaticResource Eyebrow}">
<Setter Property="Foreground" Value="{StaticResource TextDim}"/>
</Style>
<Style x:Key="Title" TargetType="TextBlock">
<Setter Property="FontFamily" Value="{StaticResource Serif}"/>
<Setter Property="FontSize" Value="32"/>
<Setter Property="Foreground" Value="{StaticResource TextHi}"/>
<Setter Property="TextOptions.TextFormattingMode" Value="Ideal"/>
<Setter Property="TextWrapping" Value="Wrap"/>
<Setter Property="LineHeight" Value="38"/>
<Setter Property="LineStackingStrategy" Value="BlockLineHeight"/>
<Setter Property="Margin" Value="-1,14,0,0"/>
</Style>
<Style x:Key="Body" TargetType="TextBlock">
<Setter Property="Foreground" Value="{StaticResource Text}"/>
<Setter Property="TextWrapping" Value="Wrap"/>
<Setter Property="LineHeight" Value="22"/>
<Setter Property="MaxWidth" Value="540"/>
<Setter Property="HorizontalAlignment" Value="Left"/>
</Style>
<Style x:Key="Small" TargetType="TextBlock">
<Setter Property="Foreground" Value="{StaticResource TextDim}"/>
<Setter Property="FontSize" Value="12.5"/>
<Setter Property="TextWrapping" Value="Wrap"/>
<Setter Property="LineHeight" Value="19"/>
</Style>
<Style x:Key="Value" TargetType="TextBlock">
<Setter Property="Foreground" Value="{StaticResource TextHi}"/>
<Setter Property="TextWrapping" Value="Wrap"/>
<Setter Property="LineHeight" Value="21"/>
</Style>
<Style x:Key="Diamond" TargetType="Rectangle">
<Setter Property="Width" Value="7"/>
<Setter Property="Height" Value="7"/>
<Setter Property="Fill" Value="{StaticResource Gold}"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="RenderTransformOrigin" Value="0.5,0.5"/>
<Setter Property="RenderTransform"><Setter.Value><RotateTransform Angle="45"/></Setter.Value></Setter>
</Style>
<Style x:Key="Hair" TargetType="Rectangle">
<Setter Property="Height" Value="1"/>
<Setter Property="Fill" Value="{StaticResource Line}"/>
</Style>
<!-- the one main button of a page: a bar of gold -->
<Style x:Key="Primary" TargetType="Button">
<Setter Property="Height" Value="44"/>
<Setter Property="MinWidth" Value="176"/>
<Setter Property="Cursor" Value="Hand"/>
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid>
<Border x:Name="Glow" CornerRadius="3" Background="#E0B23E" Opacity="0.16" Margin="-1">
<Border.Effect><BlurEffect Radius="16"/></Border.Effect>
</Border>
<Border x:Name="Ring" CornerRadius="4" BorderBrush="#B3FFF4CC" BorderThickness="1" Margin="-4" Opacity="0"/>
<Border x:Name="Face" CornerRadius="2" Background="{StaticResource GoldBar}" ClipToBounds="True">
<Grid>
<Rectangle x:Name="Top" Height="1" VerticalAlignment="Top" Fill="#A6FFFFFF"/>
<Rectangle x:Name="Foot" Height="1" VerticalAlignment="Bottom" Fill="#663D2A08"/>
<Rectangle x:Name="Sheen" Width="110" HorizontalAlignment="Left" Fill="{StaticResource Sheen}" Opacity="0">
<Rectangle.RenderTransform><TranslateTransform X="-120"/></Rectangle.RenderTransform>
</Rectangle>
<t:Caps x:Name="Words" Label="{Binding Content, RelativeSource={RelativeSource TemplatedParent}}" Gaps="2"
FontFamily="{StaticResource Serif}" FontWeight="Bold" FontSize="13" Foreground="#2A1C05"
TextOptions.TextFormattingMode="Ideal" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="28,0,28,1">
<t:Caps.Effect><DropShadowEffect Color="#FFF4CC" BlurRadius="0" ShadowDepth="1" Direction="270" Opacity="0.45"/></t:Caps.Effect>
</t:Caps>
</Grid>
</Border>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="Face" Property="Background" Value="{StaticResource GoldBarHot}"/>
<Setter TargetName="Sheen" Property="Opacity" Value="1"/>
<Trigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetName="Glow" Storyboard.TargetProperty="Opacity" To="0.55" Duration="0:0:0.12"/>
<DoubleAnimation Storyboard.TargetName="Sheen" Storyboard.TargetProperty="(UIElement.RenderTransform).(TranslateTransform.X)" From="-120" To="340" Duration="0:0:0.7"/>
</Storyboard>
</BeginStoryboard>
</Trigger.EnterActions>
<Trigger.ExitActions>
<BeginStoryboard>
<Storyboard><DoubleAnimation Storyboard.TargetName="Glow" Storyboard.TargetProperty="Opacity" To="0.16" Duration="0:0:0.22"/></Storyboard>
</BeginStoryboard>
</Trigger.ExitActions>
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter TargetName="Face" Property="Opacity" Value="0.86"/>
</Trigger>
<Trigger Property="IsKeyboardFocused" Value="True">
<Setter TargetName="Ring" Property="Opacity" Value="1"/>
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="Face" Property="Background" Value="{StaticResource Ink600}"/>
<Setter TargetName="Glow" Property="Visibility" Value="Collapsed"/>
<Setter TargetName="Top" Property="Fill" Value="#14FFFFFF"/>
<Setter TargetName="Foot" Property="Visibility" Value="Collapsed"/>
<Setter TargetName="Words" Property="Effect" Value="{x:Null}"/>
<Setter TargetName="Words" Property="Foreground" Value="{StaticResource TextFaint}"/>
<Setter Property="Cursor" Value="Arrow"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- every other button: a hairline frame -->
<Style x:Key="Quiet" TargetType="Button">
<Setter Property="Foreground" Value="{StaticResource Text}"/>
<Setter Property="FontSize" Value="13"/>
<Setter Property="Height" Value="36"/>
<Setter Property="Padding" Value="18,0"/>
<Setter Property="Cursor" Value="Hand"/>
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border x:Name="Face" CornerRadius="2" Background="#00000000" BorderBrush="{StaticResource LineStrong}" BorderThickness="1">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" Margin="{TemplateBinding Padding}"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="Face" Property="BorderBrush" Value="{StaticResource LineGoldHi}"/>
<Setter TargetName="Face" Property="Background" Value="{StaticResource Ink800}"/>
<Setter Property="Foreground" Value="{StaticResource TextHi}"/>
</Trigger>
<Trigger Property="IsKeyboardFocused" Value="True">
<Setter TargetName="Face" Property="BorderBrush" Value="{StaticResource Gold}"/>
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter TargetName="Face" Property="Background" Value="{StaticResource Ink700}"/>
</Trigger>
<Trigger Property="IsEnabled" Value="False"><Setter Property="Opacity" Value="0.4"/></Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- a way to somewhere else: gold words and a small arrow -->
<Style x:Key="Link" TargetType="ButtonBase">
<Setter Property="Foreground" Value="{StaticResource Gold}"/>
<Setter Property="FontSize" Value="12.5"/>
<Setter Property="Cursor" Value="Hand"/>
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ButtonBase">
<StackPanel Orientation="Horizontal" Background="#00000000">
<ContentPresenter Margin="0,5" VerticalAlignment="Center"/>
<Path x:Name="Arrow" Data="M0,0 L3.5,3.5 L0,7" StrokeThickness="1.3" Margin="8,1,0,0" VerticalAlignment="Center"
Stroke="{Binding Foreground, RelativeSource={RelativeSource TemplatedParent}}">
<Path.RenderTransform><TranslateTransform/></Path.RenderTransform>
</Path>
</StackPanel>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Foreground" Value="{StaticResource Gold300}"/>
<Trigger.EnterActions>
<BeginStoryboard><Storyboard><DoubleAnimation Storyboard.TargetName="Arrow" Storyboard.TargetProperty="(UIElement.RenderTransform).(TranslateTransform.X)" To="3" Duration="0:0:0.12"/></Storyboard></BeginStoryboard>
</Trigger.EnterActions>
<Trigger.ExitActions>
<BeginStoryboard><Storyboard><DoubleAnimation Storyboard.TargetName="Arrow" Storyboard.TargetProperty="(UIElement.RenderTransform).(TranslateTransform.X)" To="0" Duration="0:0:0.22"/></Storyboard></BeginStoryboard>
</Trigger.ExitActions>
</Trigger>
<Trigger Property="IsKeyboardFocused" Value="True"><Setter Property="Foreground" Value="{StaticResource Gold100}"/></Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="Caption" TargetType="Button">
<Setter Property="Foreground" Value="{StaticResource TextDim}"/>
<Setter Property="Width" Value="46"/>
<Setter Property="Height" Value="44"/>
<Setter Property="Focusable" Value="False"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border x:Name="Face" Background="#00000000">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="Face" Property="Background" Value="{StaticResource Ink700}"/>
<Setter Property="Foreground" Value="{StaticResource TextHi}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="CaptionClose" TargetType="Button" BasedOn="{StaticResource Caption}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border x:Name="Face" Background="#00000000">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="Face" Property="Background" Value="#8E1622"/>
<Setter Property="Foreground" Value="#FFFFFF"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- wells: where a path is typed, where the build's details scroll -->
<Style x:Key="Path" TargetType="TextBox">
<Setter Property="Foreground" Value="{StaticResource TextHi}"/>
<Setter Property="CaretBrush" Value="{StaticResource Gold300}"/>
<Setter Property="SelectionBrush" Value="#E0B23E"/>
<Setter Property="FontSize" Value="13"/>
<Setter Property="Height" Value="38"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="TextBox">
<Border x:Name="B" CornerRadius="2" Background="#CC12100C" BorderBrush="{StaticResource Line}" BorderThickness="1" Padding="12,0">
<ScrollViewer x:Name="PART_ContentHost" VerticalAlignment="Center"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True"><Setter TargetName="B" Property="BorderBrush" Value="{StaticResource LineStrong}"/></Trigger>
<Trigger Property="IsKeyboardFocused" Value="True"><Setter TargetName="B" Property="BorderBrush" Value="{StaticResource LineGoldHi}"/></Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- one of two ways (a file or folders; into or out of): words with a gold line under the chosen one -->
<Style x:Key="Seg" TargetType="RadioButton">
<Setter Property="Foreground" Value="{StaticResource TextDim}"/>
<Setter Property="FontSize" Value="12.5"/>
<Setter Property="Cursor" Value="Hand"/>
<Setter Property="Margin" Value="22,0,0,0"/>
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="RadioButton">
<Grid Background="#00000000">
<ContentPresenter Margin="0,0,0,8"/>
<Rectangle x:Name="Bar" Height="2" VerticalAlignment="Bottom" Fill="{StaticResource Gold}" Opacity="0"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True"><Setter Property="Foreground" Value="{StaticResource Text}"/></Trigger>
<Trigger Property="IsKeyboardFocused" Value="True"><Setter Property="Foreground" Value="{StaticResource Gold300}"/></Trigger>
<Trigger Property="IsChecked" Value="True">
<Setter Property="Foreground" Value="{StaticResource TextHi}"/>
<Setter TargetName="Bar" Property="Opacity" Value="1"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="Tick" TargetType="CheckBox">
<Setter Property="Foreground" Value="{StaticResource Text}"/>
<Setter Property="Cursor" Value="Hand"/>
<Setter Property="Margin" Value="0,0,0,10"/>
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="CheckBox">
<StackPanel Orientation="Horizontal" Background="#00000000">
<Border x:Name="Box" Width="16" Height="16" CornerRadius="2" Background="#CC12100C" BorderBrush="{StaticResource LineStrong}" BorderThickness="1" VerticalAlignment="Center">
<Path x:Name="Mark" Data="M3,7.6 L6.2,10.8 L11.6,4.2" Stroke="#2A1C05" StrokeThickness="1.9" StrokeStartLineCap="Round" StrokeEndLineCap="Round" Visibility="Collapsed"/>
</Border>
<ContentPresenter Margin="12,0,0,1" VerticalAlignment="Center"/>
</StackPanel>
<ControlTemplate.Triggers>
<Trigger Property="IsChecked" Value="True">
<Setter TargetName="Box" Property="Background" Value="{StaticResource GoldBar}"/>
<Setter TargetName="Box" Property="BorderBrush" Value="{StaticResource Gold300}"/>
<Setter TargetName="Mark" Property="Visibility" Value="Visible"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="Box" Property="BorderBrush" Value="{StaticResource LineGoldHi}"/>
<Setter Property="Foreground" Value="{StaticResource TextHi}"/>
</Trigger>
<Trigger Property="IsKeyboardFocused" Value="True"><Setter TargetName="Box" Property="BorderBrush" Value="{StaticResource Gold}"/></Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="Choice" TargetType="ComboBox">
<Setter Property="Foreground" Value="{StaticResource TextHi}"/>
<Setter Property="FontSize" Value="13"/>
<Setter Property="Height" Value="34"/>
<Setter Property="Cursor" Value="Hand"/>
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ComboBox">
<Grid>
<ToggleButton x:Name="Toggle" Focusable="False" ClickMode="Press"
IsChecked="{Binding IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}">
<ToggleButton.Template>
<ControlTemplate TargetType="ToggleButton">
<Border x:Name="B" CornerRadius="2" Background="#CC12100C" BorderBrush="{StaticResource Line}" BorderThickness="1">
<Path HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0,0,13,0" Data="M0,0 L4,4 L8,0" Stroke="{StaticResource Gold}" StrokeThickness="1.3"/>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True"><Setter TargetName="B" Property="BorderBrush" Value="{StaticResource LineGoldHi}"/></Trigger>
<Trigger Property="IsChecked" Value="True"><Setter TargetName="B" Property="BorderBrush" Value="{StaticResource LineGoldHi}"/></Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</ToggleButton.Template>
</ToggleButton>
<ContentPresenter IsHitTestVisible="False" Margin="12,0,30,1" VerticalAlignment="Center"
Content="{TemplateBinding SelectionBoxItem}" ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}"/>
<Popup x:Name="PART_Popup" Placement="Bottom" AllowsTransparency="True" Focusable="False" PopupAnimation="Fade"
IsOpen="{TemplateBinding IsDropDownOpen}">
<Border Margin="0,4,0,0" MinWidth="{TemplateBinding ActualWidth}" MaxHeight="300" CornerRadius="2"
Background="#12100C" BorderBrush="{StaticResource LineGoldHi}" BorderThickness="1" Padding="3">
<ScrollViewer VerticalScrollBarVisibility="Auto"><ItemsPresenter/></ScrollViewer>
</Border>
</Popup>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="ItemContainerStyle">
<Setter.Value>
<Style TargetType="ComboBoxItem">
<Setter Property="Foreground" Value="{StaticResource Text}"/>
<Setter Property="FontSize" Value="13"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ComboBoxItem">
<Border x:Name="B" CornerRadius="2" Padding="10,6" Background="#00000000"><ContentPresenter/></Border>
<ControlTemplate.Triggers>
<Trigger Property="IsHighlighted" Value="True">
<Setter TargetName="B" Property="Background" Value="{StaticResource Ink600}"/>
<Setter Property="Foreground" Value="{StaticResource TextHi}"/>
</Trigger>
<Trigger Property="IsSelected" Value="True"><Setter Property="Foreground" Value="{StaticResource Gold300}"/></Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Setter.Value>
</Setter>
</Style>
<!-- scroll bars: a thin thumb, nothing else (Windows' own grey ones have no place in the hall) -->
<Style x:Key="ScrollThumb" TargetType="Thumb">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Thumb">
<Border x:Name="T" CornerRadius="2" Background="#4A3F28" Margin="2"/>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True"><Setter TargetName="T" Property="Background" Value="#8A6A22"/></Trigger>
<Trigger Property="IsDragging" Value="True"><Setter TargetName="T" Property="Background" Value="#E0B23E"/></Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="ScrollPage" TargetType="RepeatButton">
<Setter Property="Focusable" Value="False"/>
<Setter Property="Template">
<Setter.Value><ControlTemplate TargetType="RepeatButton"><Border Background="#00000000"/></ControlTemplate></Setter.Value>
</Setter>
</Style>
<Style TargetType="ScrollBar">
<Setter Property="Width" Value="9"/>
<Setter Property="MinWidth" Value="9"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ScrollBar">
<Track x:Name="PART_Track" IsDirectionReversed="True">
<Track.DecreaseRepeatButton><RepeatButton Style="{StaticResource ScrollPage}" Command="ScrollBar.PageUpCommand"/></Track.DecreaseRepeatButton>
<Track.Thumb><Thumb Style="{StaticResource ScrollThumb}"/></Track.Thumb>
<Track.IncreaseRepeatButton><RepeatButton Style="{StaticResource ScrollPage}" Command="ScrollBar.PageDownCommand"/></Track.IncreaseRepeatButton>
</Track>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="Orientation" Value="Horizontal">
<Setter Property="Width" Value="Auto"/>
<Setter Property="MinWidth" Value="0"/>
<Setter Property="Height" Value="9"/>
<Setter Property="MinHeight" Value="9"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ScrollBar">
<Track x:Name="PART_Track">
<Track.DecreaseRepeatButton><RepeatButton Style="{StaticResource ScrollPage}" Command="ScrollBar.PageLeftCommand"/></Track.DecreaseRepeatButton>
<Track.Thumb><Thumb Style="{StaticResource ScrollThumb}"/></Track.Thumb>
<Track.IncreaseRepeatButton><RepeatButton Style="{StaticResource ScrollPage}" Command="ScrollBar.PageRightCommand"/></Track.IncreaseRepeatButton>
</Track>
</ControlTemplate>
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
<Style TargetType="ToolTip">
<Setter Property="Foreground" Value="{StaticResource Text}"/>
<Setter Property="FontSize" Value="12"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ToolTip">
<Border Background="#12100C" BorderBrush="{StaticResource LineStrong}" BorderThickness="1" CornerRadius="2" Padding="9,5">
<ContentPresenter/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<!-- Host is the window's inside as Windows gives it; Root is the picture, always 1060 x 640 (Shell.FitToScreen keeps the two
the same size; Root is not indented a level deeper to keep the pages readable) -->
<Grid x:Name="Host">
<Grid x:Name="Root" Width="1060" Height="640" HorizontalAlignment="Left" VerticalAlignment="Top">
<!-- the hall and the relic (Stage.cs) -->
<Grid x:Name="StageHost"/>
<Grid>
<Grid.ColumnDefinitions><ColumnDefinition Width="630"/><ColumnDefinition Width="430"/></Grid.ColumnDefinitions>
<Grid.RowDefinitions><RowDefinition Height="44"/><RowDefinition Height="*"/></Grid.RowDefinitions>
<!-- caption -->
<StackPanel Orientation="Horizontal" Margin="24,0,0,0" VerticalAlignment="Center">
<t:Caps Label="Triforce Setup" Style="{StaticResource Eyebrow}" FontSize="9.5" Foreground="{StaticResource TextFaint}"/>
<TextBlock x:Name="VersionText" Margin="14,0,0,1" VerticalAlignment="Center" FontSize="10.5" Foreground="{StaticResource TextFaint}"/>
</StackPanel>
<StackPanel Grid.Column="1" Orientation="Horizontal" HorizontalAlignment="Right" shell:WindowChrome.IsHitTestVisibleInChrome="True">
<Button x:Name="MinButton" Style="{StaticResource Caption}" ToolTip="Minimize">
<Rectangle Width="10" Height="1" Fill="{Binding Foreground, RelativeSource={RelativeSource AncestorType=Button}}"/>
</Button>
<Button x:Name="CloseButton" Style="{StaticResource CaptionClose}" ToolTip="Close">
<Path Data="M0,0 L10,10 M10,0 L0,10" StrokeThickness="1.1" Stroke="{Binding Foreground, RelativeSource={RelativeSource AncestorType=Button}}"/>
</Button>
</StackPanel>
<!-- page: install -->
<Grid x:Name="InstallPage" Grid.Row="1" Margin="56,22,34,36" Visibility="Collapsed">
<Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="*"/><RowDefinition Height="Auto"/></Grid.RowDefinitions>
<StackPanel>
<StackPanel Orientation="Horizontal">
<Rectangle Width="20" Height="1" Fill="{StaticResource LineGoldHi}" VerticalAlignment="Center" Margin="0,0,10,0"/>
<t:Caps Label="I · Install" Style="{StaticResource Eyebrow}"/>
</StackPanel>
<TextBlock Text="Welcome, hero." Style="{StaticResource Title}"/>
<TextBlock Style="{StaticResource Body}" Margin="0,12,0,0"
Text="Triforce turns your own copy of Ocarina of Time into a native PC game. Setup installs itself, fetches the Triforce tools, and keeps everything up to date for you."/>
</StackPanel>
<StackPanel Grid.Row="1" Margin="0,34,0,0">
<t:Caps Label="Install Triforce to" Style="{StaticResource FieldLabel}" Margin="0,0,0,10"/>
<Grid>
<Grid.ColumnDefinitions><ColumnDefinition/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions>
<TextBox x:Name="InstallPath" Style="{StaticResource Path}"/>
<Button x:Name="BrowseInstall" Grid.Column="1" Style="{StaticResource Quiet}" Height="38" Margin="8,0,0,0" Content="Browse"/>
</Grid>
<TextBlock x:Name="InstallSpace" Style="{StaticResource Small}" Margin="0,10,0,26"/>
<CheckBox x:Name="DesktopIcon" Style="{StaticResource Tick}" IsChecked="True" Content="Put Triforce on the desktop"/>
<CheckBox x:Name="StartIcon" Style="{StaticResource Tick}" IsChecked="True" Content="Add Triforce to the Start menu"/>
</StackPanel>
<Grid Grid.Row="2">
<Grid.ColumnDefinitions><ColumnDefinition/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource Small}" VerticalAlignment="Center" Margin="0,0,20,0"
Text="No game data is downloaded: you bring your own copy."/>
<Button x:Name="InstallButton" Grid.Column="1" Style="{StaticResource Primary}" Content="Install"/>
</Grid>
</Grid>
<!-- page: gathering (the update check, downloads) -->
<Grid x:Name="FetchPage" Grid.Row="1" Margin="56,22,34,36" Visibility="Collapsed">
<Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="*"/><RowDefinition Height="Auto"/></Grid.RowDefinitions>
<StackPanel>
<StackPanel Orientation="Horizontal">
<Rectangle Width="20" Height="1" Fill="{StaticResource LineGoldHi}" VerticalAlignment="Center" Margin="0,0,10,0"/>
<t:Caps Label="II · Gather" Style="{StaticResource Eyebrow}"/>
</StackPanel>
<TextBlock x:Name="FetchTitle" Style="{StaticResource Title}" Text="Gathering the stones"/>
<TextBlock x:Name="FetchNote" Style="{StaticResource Body}" Margin="0,12,0,0"/>
</StackPanel>
<StackPanel Grid.Row="1" VerticalAlignment="Center" Margin="0,10,0,0">
<StackPanel x:Name="FetchNumberRow" Orientation="Horizontal" Height="70" Visibility="Hidden">
<TextBlock x:Name="FetchNumber" FontFamily="{StaticResource Serif}" FontSize="64" Foreground="{StaticResource TextHi}"
TextOptions.TextFormattingMode="Ideal" VerticalAlignment="Bottom" Margin="-3,0,0,-8"/>
<TextBlock Text="%" FontFamily="{StaticResource Serif}" FontSize="24" Foreground="{StaticResource Gold}"
TextOptions.TextFormattingMode="Ideal" VerticalAlignment="Bottom" Margin="6,0,0,4"/>
</StackPanel>
<t:ProgressLine x:Name="FetchBar" Margin="0,14,0,0"/>
<Grid Margin="0,8,0,0">
<TextBlock x:Name="FetchStep" Style="{StaticResource Small}" Foreground="{StaticResource Text}"/>
<TextBlock x:Name="FetchPercent" Style="{StaticResource Small}" HorizontalAlignment="Right"/>
</Grid>
</StackPanel>
<StackPanel Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Right" Height="44">
<Button x:Name="FetchSkip" Style="{StaticResource Quiet}" Height="44" Content="Continue offline" Visibility="Collapsed" Margin="0,0,12,0"/>
<Button x:Name="FetchCancel" Style="{StaticResource Quiet}" Height="44" Content="Cancel"/>
<Button x:Name="FetchRetry" Style="{StaticResource Primary}" Content="Try again" Visibility="Collapsed" Margin="12,0,0,0"/>
</StackPanel>
</Grid>
<!-- page: welcome back (every start once there is something to play or to build with): play, or the update first -->
<Grid x:Name="HomePage" Grid.Row="1" Margin="56,22,34,36" Visibility="Collapsed">
<Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="*"/><RowDefinition Height="Auto"/></Grid.RowDefinitions>
<StackPanel>
<StackPanel Orientation="Horizontal">
<Rectangle Width="20" Height="1" Fill="{StaticResource LineGoldHi}" VerticalAlignment="Center" Margin="0,0,10,0"/>
<t:Caps x:Name="HomeEyebrow" Label="IV · Play" Style="{StaticResource Eyebrow}"/>
</StackPanel>
<TextBlock x:Name="HomeTitle" Style="{StaticResource Title}" FontSize="40" LineHeight="46" Text="Welcome back, hero."/>
<TextBlock x:Name="HomeNote" Style="{StaticResource Body}" Margin="0,12,0,0"/>
</StackPanel>
<StackPanel Grid.Row="1" Margin="0,30,0,0">
<Rectangle Style="{StaticResource Hair}" Fill="{StaticResource Fading}"/>
<Grid Margin="0,13,0,13">
<Grid.ColumnDefinitions><ColumnDefinition Width="172"/><ColumnDefinition/></Grid.ColumnDefinitions>
<StackPanel Orientation="Horizontal" VerticalAlignment="Top" Margin="1,5,0,0">
<Rectangle x:Name="GameMark" Style="{StaticResource Diamond}"/>
<t:Caps Label="Your game" Style="{StaticResource FieldLabel}" Margin="12,0,0,0"/>
</StackPanel>
<StackPanel Grid.Column="1">
<TextBlock x:Name="GameLine" Style="{StaticResource Value}"/>
<TextBlock x:Name="GamePath" Style="{StaticResource Small}" TextWrapping="NoWrap" TextTrimming="CharacterEllipsis" Margin="0,1,0,0"/>
</StackPanel>
</Grid>
<Rectangle Style="{StaticResource Hair}" Fill="{StaticResource Fading}"/>
<Grid Margin="0,13,0,13">
<Grid.ColumnDefinitions><ColumnDefinition Width="172"/><ColumnDefinition/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions>
<StackPanel Orientation="Horizontal" VerticalAlignment="Top" Margin="1,5,0,0">
<Rectangle x:Name="SavesMark" Style="{StaticResource Diamond}"/>
<t:Caps Label="Your saves" Style="{StaticResource FieldLabel}" Margin="12,0,0,0"/>
</StackPanel>
<StackPanel Grid.Column="1" Margin="0,0,16,0">
<TextBlock x:Name="SavesLine" Style="{StaticResource Value}"/>
<TextBlock x:Name="SavesDetail" Style="{StaticResource Small}" Margin="0,1,0,0"/>
</StackPanel>
<Button x:Name="ConvertSavesButton" Grid.Column="2" Style="{StaticResource Link}" Content="Convert saves" VerticalAlignment="Top" Margin="0,-3,0,-5"/>
</Grid>
<Rectangle Style="{StaticResource Hair}" Fill="{StaticResource Fading}"/>
<Grid Margin="0,13,0,13">
<Grid.ColumnDefinitions><ColumnDefinition Width="172"/><ColumnDefinition/></Grid.ColumnDefinitions>
<StackPanel Orientation="Horizontal" VerticalAlignment="Top" Margin="1,5,0,0">
<Rectangle x:Name="NewsMark" Style="{StaticResource Diamond}"/>
<t:Caps Label="Newest Triforce" Style="{StaticResource FieldLabel}" Margin="12,0,0,0"/>
</StackPanel>
<StackPanel Grid.Column="1">
<TextBlock x:Name="NewsLine" Style="{StaticResource Value}"/>
<TextBlock x:Name="NewsDetail" Style="{StaticResource Small}" Margin="0,1,0,0"/>
</StackPanel>
</Grid>
<Rectangle Style="{StaticResource Hair}" Fill="{StaticResource Fading}"/>
<TextBlock x:Name="MergeNote" Style="{StaticResource Small}" Margin="0,14,0,0"/>
</StackPanel>
<Grid Grid.Row="2">
<Grid.ColumnDefinitions><ColumnDefinition/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions>
<ToggleButton x:Name="NewFolderLink" Style="{StaticResource Link}" VerticalAlignment="Center" HorizontalAlignment="Left" Content="Build a game folder"/>
<StackPanel Grid.Column="1" Orientation="Horizontal">
<Button x:Name="NotNowButton" Style="{StaticResource Quiet}" Height="48" Content="Not now" Margin="0,0,12,0"/>
<Button x:Name="HomeGoButton" Style="{StaticResource Primary}" Height="48" MinWidth="208" Content="Play"/>
</StackPanel>
</Grid>
</Grid>
<!-- page: convert saves (Triforce, EvilOOT, Eden, yuzu, Ryujinx ... keep the same save files for this game) -->
<Grid x:Name="SavesPage" Grid.Row="1" Margin="56,22,34,36" Visibility="Collapsed">
<Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/><RowDefinition Height="*"/><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/></Grid.RowDefinitions>
<StackPanel>
<StackPanel Orientation="Horizontal">
<Rectangle Width="20" Height="1" Fill="{StaticResource LineGoldHi}" VerticalAlignment="Center" Margin="0,0,10,0"/>
<t:Caps Label="Saves" Style="{StaticResource Eyebrow}"/>
</StackPanel>
<TextBlock Text="Convert saves" Style="{StaticResource Title}"/>
<TextBlock Style="{StaticResource Body}" Margin="0,12,0,0"
Text="Bring your saves from an emulator into Triforce, or take Triforce's back out. Whatever gets replaced is backed up first."/>
</StackPanel>
<Grid Grid.Row="1" Margin="0,24,0,0">
<StackPanel Orientation="Horizontal" Margin="-22,0,0,0">
<RadioButton x:Name="SavesIn" Style="{StaticResource Seg}" GroupName="SaveWay" IsChecked="True" Content="Into Triforce"/>
<RadioButton x:Name="SavesOut" Style="{StaticResource Seg}" GroupName="SaveWay" Content="Out of Triforce"/>
</StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0,-5,0,0">
<Button x:Name="SavesRescan" Style="{StaticResource Link}" Content="Look again" Margin="0,0,22,0"/>
<Button x:Name="SavesBrowse" Style="{StaticResource Link}" Content="Choose a folder"/>
</StackPanel>
<Rectangle Style="{StaticResource Hair}" VerticalAlignment="Bottom"/>
</Grid>
<Grid Grid.Row="2" Margin="0,14,0,0">
<Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="*"/></Grid.RowDefinitions>
<t:Caps x:Name="SavesListLabel" Style="{StaticResource FieldLabel}" Label="Take the saves from" Margin="0,0,0,6"/>
<ListBox x:Name="SaveList" Grid.Row="1" Background="#00000000" BorderThickness="0" Padding="0" Margin="-1,0,0,0"
ScrollViewer.HorizontalScrollBarVisibility="Disabled" FocusVisualStyle="{x:Null}">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Cursor" Value="Hand"/>
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Grid Background="#00000000">
<Border x:Name="B" Background="#00000000" Padding="16,10,12,10">
<ContentPresenter/>
</Border>
<Rectangle x:Name="Bar" Width="2" HorizontalAlignment="Left" Fill="{StaticResource Gold}" Opacity="0" Margin="0,8"/>
<Rectangle Style="{StaticResource Hair}" VerticalAlignment="Bottom"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True"><Setter TargetName="B" Property="Background" Value="#8012100C"/></Trigger>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="B" Property="Background" Value="#D912100C"/>
<Setter TargetName="Bar" Property="Opacity" Value="1"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
</Grid>
<TextBlock x:Name="SavesInfo" Grid.Row="3" Style="{StaticResource Small}" Foreground="{StaticResource Text}" Margin="0,12,0,16" MinHeight="38"/>
<Grid Grid.Row="4">
<Grid.ColumnDefinitions><ColumnDefinition/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions>
<TextBlock x:Name="SavesTarget" Style="{StaticResource Small}" VerticalAlignment="Center" Margin="0,0,20,0" TextWrapping="NoWrap" TextTrimming="CharacterEllipsis"/>
<StackPanel Grid.Column="1" Orientation="Horizontal">
<Button x:Name="SavesBack" Style="{StaticResource Quiet}" Height="44" Content="Back" Margin="0,0,12,0"/>
<Button x:Name="SavesGo" Style="{StaticResource Primary}" Content="Convert" IsEnabled="False"/>
</StackPanel>
</Grid>
</Grid>
<!-- page: the forge (choose the game) -->
<Grid x:Name="SetupPage" Grid.Row="1" Margin="56,22,34,36" Visibility="Collapsed">
<Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/><RowDefinition Height="*"/><RowDefinition Height="Auto"/></Grid.RowDefinitions>
<Grid>
<StackPanel>
<StackPanel Orientation="Horizontal">
<Rectangle Width="20" Height="1" Fill="{StaticResource LineGoldHi}" VerticalAlignment="Center" Margin="0,0,10,0"/>
<t:Caps Label="III · Forge" Style="{StaticResource Eyebrow}"/>
</StackPanel>
<TextBlock x:Name="SetupTitle" Style="{StaticResource Title}" Text="Forge your game"/>
<TextBlock x:Name="Subtitle" Style="{StaticResource Body}" Margin="0,12,0,0"/>
</StackPanel>
<StackPanel HorizontalAlignment="Right" VerticalAlignment="Top" Width="178" Margin="0,-6,0,0">
<t:Caps x:Name="LanguageLabel" Style="{StaticResource FieldLabel}" HorizontalAlignment="Right" Margin="0,0,0,7"/>
<ComboBox x:Name="LanguageBox" Style="{StaticResource Choice}"/>
</StackPanel>
</Grid>
<!-- the game built before: out of date (update it) or ready (play). A quiet button: this page's one gold button is Build -->
<Border x:Name="UpdateBanner" Grid.Row="1" Margin="0,20,0,0" CornerRadius="2" Padding="16,11,11,11" Visibility="Collapsed"
Background="#B312100C" BorderBrush="{StaticResource LineGold}" BorderThickness="1">
<Grid>
<Grid.ColumnDefinitions><ColumnDefinition Width="Auto"/><ColumnDefinition/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions>
<Rectangle Style="{StaticResource Diamond}" Fill="{StaticResource Gold300}"/>
<TextBlock x:Name="UpdateText" Grid.Column="1" Style="{StaticResource Small}" Foreground="{StaticResource TextHi}" Margin="14,0,16,0" VerticalAlignment="Center"/>
<Button x:Name="UpdateGameButton" Grid.Column="2" Style="{StaticResource Quiet}" MinWidth="112" Height="34" Content="Update game"/>
</Grid>
</Border>
<StackPanel Grid.Row="2" Margin="0,24,0,0">
<Grid>
<t:Caps x:Name="GameFilesLabel" Style="{StaticResource FieldLabel}" VerticalAlignment="Top" Margin="0,2,0,0"/>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<RadioButton x:Name="UseNup" Style="{StaticResource Seg}" GroupName="Source" IsChecked="True"/>
<RadioButton x:Name="UseFolders" Style="{StaticResource Seg}" GroupName="Source"/>
</StackPanel>
</Grid>
<Grid x:Name="NupRow" Margin="0,8,0,0">
<Grid.ColumnDefinitions><ColumnDefinition/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions>
<TextBox x:Name="NupPath" Style="{StaticResource Path}"/>
<Button x:Name="BrowseA" Grid.Column="1" Style="{StaticResource Quiet}" Height="38" Margin="8,0,0,0"/>
</Grid>
<StackPanel x:Name="FolderRows" Visibility="Collapsed" Margin="0,8,0,0">
<Grid Margin="0,0,0,8">
<Grid.ColumnDefinitions><ColumnDefinition Width="52"/><ColumnDefinition/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions>
<TextBlock Text="romfs" Style="{StaticResource Small}" VerticalAlignment="Center"/>
<TextBox x:Name="RomfsPath" Grid.Column="1" Style="{StaticResource Path}"/>
<Button x:Name="BrowseB" Grid.Column="2" Style="{StaticResource Quiet}" Height="38" Margin="8,0,0,0"/>
</Grid>
<Grid>
<Grid.ColumnDefinitions><ColumnDefinition Width="52"/><ColumnDefinition/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions>
<TextBlock Text="exefs" Style="{StaticResource Small}" VerticalAlignment="Center"/>
<TextBox x:Name="ExefsPath" Grid.Column="1" Style="{StaticResource Path}"/>
<Button x:Name="BrowseC" Grid.Column="2" Style="{StaticResource Quiet}" Height="38" Margin="8,0,0,0"/>
</Grid>
</StackPanel>
<Grid Margin="1,10,0,0" MinHeight="20">
<Grid.ColumnDefinitions><ColumnDefinition Width="Auto"/><ColumnDefinition/></Grid.ColumnDefinitions>
<Rectangle x:Name="CheckMark" Style="{StaticResource Diamond}" VerticalAlignment="Top" Margin="0,6,12,0"/>
<TextBlock x:Name="CheckText" Grid.Column="1" Style="{StaticResource Small}"/>
</Grid>
<t:Caps x:Name="SaveToLabel" Style="{StaticResource FieldLabel}" Margin="0,22,0,10"/>
<Grid>
<Grid.ColumnDefinitions><ColumnDefinition/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions>
<TextBox x:Name="OutPath" Style="{StaticResource Path}"/>
<Button x:Name="BrowseD" Grid.Column="1" Style="{StaticResource Quiet}" Height="38" Margin="8,0,0,0"/>
</Grid>
</StackPanel>
<Grid Grid.Row="3">
<Grid.ColumnDefinitions><ColumnDefinition/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions>
<TextBlock x:Name="SpaceText" Style="{StaticResource Small}" VerticalAlignment="Center" Margin="0,0,20,0"/>
<Button x:Name="BuildButton" Grid.Column="1" Style="{StaticResource Primary}" IsEnabled="False"/>
</Grid>
</Grid>
<!-- page: building (its details take the whole width when shown: Shell lets the page span both columns) -->
<Grid x:Name="BuildPage" Grid.Row="1" Margin="56,22,34,36" Visibility="Collapsed">
<Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="*"/><RowDefinition Height="Auto"/></Grid.RowDefinitions>
<StackPanel>
<StackPanel Orientation="Horizontal">
<Rectangle Width="20" Height="1" Fill="{StaticResource LineGoldHi}" VerticalAlignment="Center" Margin="0,0,10,0"/>
<t:Caps x:Name="BuildEyebrow" Label="III · Forge" Style="{StaticResource Eyebrow}"/>
</StackPanel>
<TextBlock x:Name="BuildTitle" Style="{StaticResource Title}"/>
<TextBlock x:Name="BuildNote" Style="{StaticResource Body}" Margin="0,12,0,0" MaxWidth="900"/>
</StackPanel>
<Grid Grid.Row="1" Margin="0,30,0,16">
<Grid.ColumnDefinitions><ColumnDefinition x:Name="StageColumn" Width="540"/><ColumnDefinition/></Grid.ColumnDefinitions>
<StackPanel x:Name="StageList" VerticalAlignment="Top"/>
<TextBox x:Name="Log" Grid.Column="1" Margin="26,0,0,0" Visibility="Collapsed" IsReadOnly="True" BorderThickness="1"
BorderBrush="{StaticResource Line}" Background="#E60C0B09" Foreground="{StaticResource TextDim}"
FontFamily="{StaticResource Mono}" FontSize="11.5" Padding="12,10" VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Auto" TextWrapping="NoWrap" FocusVisualStyle="{x:Null}"/>
</Grid>
<Grid Grid.Row="2" Height="44">
<Grid.ColumnDefinitions><ColumnDefinition/><ColumnDefinition Width="Auto"/></Grid.ColumnDefinitions>
<ToggleButton x:Name="ShowLog" Style="{StaticResource Link}" VerticalAlignment="Center" HorizontalAlignment="Left"/>
<StackPanel Grid.Column="1" Orientation="Horizontal">
<Button x:Name="OpenButton" Style="{StaticResource Quiet}" Height="44" Visibility="Collapsed" Margin="0,0,12,0"/>
<Button x:Name="BackButton" Style="{StaticResource Quiet}" Height="44" Visibility="Collapsed"/>
<Button x:Name="CancelButton" Style="{StaticResource Quiet}" Height="44"/>
<Button x:Name="PlayButton" Style="{StaticResource Primary}" Visibility="Collapsed"/>
</StackPanel>
</Grid>
</Grid>
</Grid>
<!-- a question that must be answered before anything else (closing while a build runs) -->
<Grid x:Name="AskLayer" Visibility="Collapsed" Background="#D9060504">
<Border Width="440" HorizontalAlignment="Center" VerticalAlignment="Center" CornerRadius="2" Padding="34,30,34,28"
Background="#0E0C0A" BorderBrush="{StaticResource LineGold}" BorderThickness="1">
<StackPanel>
<Rectangle Style="{StaticResource Diamond}" HorizontalAlignment="Left" Fill="{StaticResource Gold300}" Margin="1,0,0,16"/>
<TextBlock x:Name="AskText" Style="{StaticResource Title}" FontSize="24" LineHeight="30" Margin="0"/>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,30,0,0">
<Button x:Name="AskNo" Style="{StaticResource Quiet}" Height="40" Margin="0,0,12,0"/>
<Button x:Name="AskYes" Style="{StaticResource Primary}" Height="40" MinWidth="150"/>
</StackPanel>
</StackPanel>
</Border>
</Grid>
<!-- the window's edge, where Windows draws none of its own (Shell hides it when Windows 11 colours the frame) -->
<Border x:Name="WindowEdge" BorderThickness="1" BorderBrush="#40361F" IsHitTestVisible="False"/>
</Grid>
</Grid>
</Window>

206
setup/Saves.cs Normal file
View File

@@ -0,0 +1,206 @@
// Saves of this game (Ocarina of Time, 0400486024DEC000), wherever they are: Triforce keeps them in <game>\user\save\<uid>, emulators
// in their NAND (Eden, yuzu, suyu, sudachi, citron, torzu, EvilOOT: nand\user\save\0000000000000000\<user>\0400486024DEC000) or
// Ryujinx's bis\user\save\<index>\0. The files are the same everywhere (account.sav, option.sav, slot_00..05\caption.sav +
// progress.sav), so converting is a copy, with what gets replaced backed up first.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
namespace TriforceSetup;
sealed class SaveSet
{
public string Name = "", Folder = "";
public int Slots;
public DateTime Last;
public bool Empty; // (a place with no save yet: only a destination)
public override string ToString() => Name;
}
static class Saves
{
public const string TitleId = "0400486024DEC000";
/// Triforce's save folder (host/nn_applet.c user_uid, host/nn_fs.c: save\<uid hi><uid lo>)
public const string TriforceUid = "5a3c9e1f0b7d24680000000000000001";
static readonly string[] Emulators = { "eden", "EvilOOT", "yuzu", "suyu", "sudachi", "citron", "torzu", "Ryujinx" };
public static string TriforceFolder(string game) => Path.Combine(game, "user", "save", TriforceUid);
/// A folder holding this game's saves
public static bool IsSaveSet(string dir) =>
Directory.Exists(dir) && (File.Exists(Path.Combine(dir, "option.sav")) || File.Exists(Path.Combine(dir, "slot_00", "progress.sav"))
|| File.Exists(Path.Combine(dir, "account.sav")));
public static SaveSet Describe(string name, string dir)
{
var s = new SaveSet { Name = name, Folder = dir };
if (!Directory.Exists(dir)) { s.Empty = true; return s; }
s.Slots = Directory.GetDirectories(dir, "slot_*").Count(d => File.Exists(Path.Combine(d, "progress.sav")));
var files = Directory.GetFiles(dir, "*.sav", SearchOption.AllDirectories);
s.Empty = files.Length == 0;
s.Last = files.Length > 0 ? files.Max(f => File.GetLastWriteTime(f)) : DateTime.MinValue;
return s;
}
/// Every save of this game found on the PC: the emulators' usual folders, the folders of programs the desktop and Start menu start
/// (portable emulators keep a "user" folder beside them), and Ryujinx's numbered saves that hold this game's files
public static List<SaveSet> FindEmulatorSaves()
{
var found = new List<SaveSet>();
var seen = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
void Add(string name, string dir)
{
try
{
if (!IsSaveSet(dir)) return;
var full = Path.GetFullPath(dir).TrimEnd('\\');
if (seen.Add(full)) found.Add(Describe(name, full));
}
catch (Exception) { }
}
void Nand(string name, string root) // (root\nand\user\save\0000000000000000\<user>\<title>)
{
var users = Path.Combine(root, "nand", "user", "save", "0000000000000000");
if (!Directory.Exists(users)) return;
foreach (var u in SafeDirs(users)) Add(name, Path.Combine(u, TitleId));
}
void Ryujinx(string name, string root) // (root\bis\user\save\<index>\0)
{
var saves = Path.Combine(root, "bis", "user", "save");
if (!Directory.Exists(saves)) return;
foreach (var s in SafeDirs(saves)) Add(name, Path.Combine(s, "0"));
}
var appData = Install.TestRoot != null ? Path.Combine(Install.TestRoot, "Roaming") : Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
foreach (var e in Emulators)
{
var root = Path.Combine(appData, e);
if (e == "Ryujinx") Ryujinx("Ryujinx", root); else Nand(Pretty(e), root);
}
// (portable copies: the programs the shortcuts start)
foreach (var exe in Install.TestRoot != null ? Enumerable.Empty<string>() : ShortcutTargets())
{
var dir = Path.GetDirectoryName(exe);
if (dir == null) continue;
var name = Path.GetFileNameWithoutExtension(exe) + " (" + dir + ")";
Nand(name, Path.Combine(dir, "user"));
Ryujinx(name, Path.Combine(dir, "portable"));
}
return found.OrderByDescending(s => s.Last).ToList();
}
static string Pretty(string e) => e switch
{
"eden" => "Eden", "yuzu" => "yuzu", "suyu" => "suyu", "sudachi" => "Sudachi", "citron" => "Citron", "torzu" => "torzu", _ => e,
};
static IEnumerable<string> SafeDirs(string d)
{
try { return Directory.GetDirectories(d); } catch (Exception) { return Array.Empty<string>(); }
}
/// The .exe files the desktop and Start menu shortcuts start
static IEnumerable<string> ShortcutTargets()
{
var places = new[]
{
Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory),
Environment.GetFolderPath(Environment.SpecialFolder.Programs), Environment.GetFolderPath(Environment.SpecialFolder.CommonPrograms),
};
var exes = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
Type? type = Type.GetTypeFromProgID("WScript.Shell");
if (type == null) return exes;
object? shell = null;
try
{
shell = Activator.CreateInstance(type);
foreach (var p in places.Where(Directory.Exists))
{
IEnumerable<string> links;
try { links = Directory.GetFiles(p, "*.lnk", p.EndsWith("Programs", StringComparison.OrdinalIgnoreCase) ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly); }
catch (Exception) { continue; }
foreach (var l in links.Take(400))
{
try
{
var lnk = type.InvokeMember("CreateShortcut", System.Reflection.BindingFlags.InvokeMethod, null, shell, new object[] { l })!;
var target = lnk.GetType().InvokeMember("TargetPath", System.Reflection.BindingFlags.GetProperty, null, lnk, null) as string;
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(lnk);
if (target != null && target.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) && File.Exists(target)) exes.Add(target);
}
catch (Exception) { }
}
}
}
catch (Exception) { }
finally { if (shell != null) System.Runtime.InteropServices.Marshal.FinalReleaseComObject(shell); }
return exes;
}
/// A chosen folder: the save set it is, or the first one inside it (a few levels down)
public static string? FindIn(string dir)
{
if (IsSaveSet(dir)) return dir;
var queue = new Queue<(string, int)>();
queue.Enqueue((dir, 0));
var looked = 0;
while (queue.Count > 0 && looked++ < 4000)
{
var (d, depth) = queue.Dequeue();
foreach (var s in SafeDirs(d))
{
if (IsSaveSet(s)) return s;
if (depth < 7) queue.Enqueue((s, depth + 1));
}
}
return null;
}
/// A game or emulator that has these saves open: it would write over the copy when it closes
public static string? RunningGame()
{
foreach (var n in new[] { "Triforce", "hookshot", "EvilOOT", "eden", "yuzu", "suyu", "sudachi", "citron", "torzu", "Ryujinx" })
foreach (var p in Process.GetProcessesByName(n))
if (Install.TestRoot == null || InTestRoot(p)) return n;
return null;
}
/// (testing, TRIFORCE_TEST_ROOT: only a game started from inside the test folder counts. The PC's own games have their own
/// saves, which a test neither reads nor touches)
static bool InTestRoot(Process p)
{
try { return p.MainModule!.FileName.StartsWith(Install.TestRoot!, StringComparison.OrdinalIgnoreCase); }
catch (Exception) { return false; }
}
/// Copies one save set over another: the destination's old files are moved to the backup folder first (nothing is merged slot by
/// slot: the copy is exactly the source). Returns the backup folder, or null when there was nothing to back up.
public static string? Copy(string from, string to, string backupRoot, string label)
{
var src = Path.GetFullPath(from).TrimEnd('\\');
var dst = Path.GetFullPath(to).TrimEnd('\\');
if (!Install.Allowed(dst)) throw new InvalidOperationException(Install.TestOnly);
if (string.Equals(src, dst, StringComparison.OrdinalIgnoreCase)) throw new InvalidOperationException("That is the same save folder.");
string? backup = null;
if (Directory.Exists(dst) && Directory.EnumerateFileSystemEntries(dst).Any())
{
var safe = string.Concat(label.Select(c => Path.GetInvalidFileNameChars().Contains(c) || c == ' ' ? '-' : c));
backup = Path.Combine(backupRoot, DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + "_" + safe);
Directory.CreateDirectory(backup);
CopyTree(dst, backup);
Directory.Delete(dst, true);
}
Directory.CreateDirectory(dst);
CopyTree(src, dst);
return backup;
}
static void CopyTree(string from, string to)
{
Directory.CreateDirectory(to);
foreach (var f in Directory.GetFiles(from)) File.Copy(f, Path.Combine(to, Path.GetFileName(f)), true);
foreach (var d in Directory.GetDirectories(from)) CopyTree(d, Path.Combine(to, Path.GetFileName(d)));
}
}

624
setup/Setup.cs Normal file
View File

@@ -0,0 +1,624 @@
// Triforce Setup: the one file players download. It installs itself (per user, no admin), keeps itself and the Triforce tools up to
// date from the GitHub releases of ruckus7382sfgsgdf/CBeta0.2, turns the player's own game files into a game folder (nx2/make_game.py from
// the tools) and starts the game. The game's own update offer (host/hos_update.c) starts it again with --update <folder>.
//
// Built for .NET Framework 4.8 (part of Windows 10 and 11): nothing to install, one small exe. setup/build.ps1 compiles it.
// Release assets it looks for: TriforceSetup.exe (this app) and Triforce-Tools.zip (a "tools" folder: nx2, host, gpu, python, ...).
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Microsoft.Win32;
namespace TriforceSetup;
static class Program
{
public const string Repo = "ruckus7382sfgsgdf/CBeta0.2";
public const string SetupAsset = "TriforceSetup.exe";
public const string ToolsAsset = "Triforce-Tools.zip";
public const string AppName = "Triforce";
[STAThread]
static int Main(string[] args)
{
try { ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12; } catch (Exception) { }
Install.NoWrites = args.Contains("--snapshot");
if (args.Contains("--uninstall")) return Install.Uninstall(args.Contains("--quiet")) ? 0 : 1;
// (silent install: --install-to <folder> [--no-desktop] [--no-startmenu]; the installed Setup then starts as usual)
var to = Array.IndexOf(args, "--install-to");
if (to >= 0 && to + 1 < args.Length)
{
var exe = Install.Run(Path.GetFullPath(args[to + 1]), !args.Contains("--no-desktop"), !args.Contains("--no-startmenu"));
Log("installed " + Version + " to " + Path.GetDirectoryName(exe) + " (silent)");
Process.Start(new ProcessStartInfo(exe) { UseShellExecute = false, WorkingDirectory = Path.GetDirectoryName(exe)! });
return 0;
}
if (args.Contains("--where")) { Log(Shell.Where()); return 0; }
// (testing: --release-test asks GitHub (or TRIFORCE_RELEASE_API) what Setup would, and writes what it found to setup.log)
if (args.Contains("--release-test"))
{
try
{
using var http = new HttpClient();
http.DefaultRequestHeaders.UserAgent.ParseAdd("TriforceSetup/" + Version);
var rel = Release.Latest(http, CancellationToken.None).Result;
Log("release-test: tag " + rel.Tag + ", setup " + (rel.SetupUrl ?? "MISSING") + " (" + rel.SetupSize + "), tools " + (rel.ToolsUrl ?? "MISSING") + " (" + rel.ToolsSize + ")");
return rel.SetupUrl != null && rel.ToolsUrl != null ? 0 : 1;
}
catch (Exception e) { Log("release-test failed: " + (e.InnerException ?? e).Message); return 2; }
}
// (testing: --convert-saves <from> <to> copies one save folder over another as the Convert saves page does)
var cv = Array.IndexOf(args, "--convert-saves");
if (cv >= 0 && cv + 2 < args.Length)
{
var b = Saves.Copy(args[cv + 1], args[cv + 2], Path.Combine(Install.SelfDir, "save-backups"), "test");
Log("convert-saves " + args[cv + 1] + " -> " + args[cv + 2] + ", backup " + (b ?? "none"));
return 0;
}
// (testing: --check-game <.nup | exefs folder> writes the version check's answer to setup.log)
var cg = Array.IndexOf(args, "--check-game");
if (cg >= 0 && cg + 1 < args.Length)
{
var tools = Tools.Find();
if (tools == null) { Log("check-game: no tools"); return 2; }
var path = args[cg + 1];
var (ok, text) = Runner.Check(tools, new[] { "--check", path.EndsWith(".nup", StringComparison.OrdinalIgnoreCase) ? "--nup" : "--exefs", path }).Result;
Log("check-game " + path + ": " + (ok ? "OK " : "BAD ") + text + " (tools " + tools.Root + ", python " + tools.Python + ")");
return ok ? 0 : 1;
}
// (testing without a screen, --snapshot or TRIFORCE_UI_SCRIPT: a failure is written down, never shown in a message box)
var shots = Array.IndexOf(args, "--snapshot");
var unattended = shots >= 0 && shots + 1 < args.Length ? args[shots + 1]
: Environment.GetEnvironmentVariable("TRIFORCE_UI_SCRIPT") is { Length: > 0 } ? Environment.GetEnvironmentVariable("TRIFORCE_UI_SHOTS") ?? Install.SelfDir : null;
void Report(Exception e)
{
try { Directory.CreateDirectory(unattended!); File.AppendAllText(Path.Combine(unattended!, "error.txt"), e + Environment.NewLine); } catch (Exception) { }
}
var app = new Application { ShutdownMode = ShutdownMode.OnMainWindowClose };
app.DispatcherUnhandledException += (_, e) =>
{
e.Handled = true;
if (unattended != null) { Report(e.Exception); Environment.Exit(3); }
MessageBox.Show("Triforce Setup ran into a problem:\n\n" + e.Exception.Message, "Triforce Setup", MessageBoxButton.OK, MessageBoxImage.Error);
};
Shell w;
try { w = new Shell(args); }
catch (Exception e) when (unattended != null) { Report(e); return 3; }
return app.Run(w.Window);
}
/// This build's release tag (setup/build.ps1 -Version), "dev" for a local build
public static string Version =>
typeof(Program).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion ?? "dev";
/// setup.log beside the installed Setup: what it checked, downloaded and ran (for bug reports)
public static void Log(string line)
{
if (Install.NoWrites) return;
try
{
var file = Path.Combine(Install.InstalledDir ?? Install.SelfDir, "setup.log");
if (File.Exists(file) && new FileInfo(file).Length > (2 << 20)) File.Delete(file);
File.AppendAllText(file, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " + line + Environment.NewLine);
}
catch (Exception) { }
}
public static Stream Resource(string name) => typeof(Program).Assembly.GetManifestResourceStream(name)
?? throw new FileNotFoundException("missing resource " + name);
public static BitmapImage Image(string name)
{
var b = new BitmapImage();
b.BeginInit();
b.StreamSource = Resource(name);
b.CacheOption = BitmapCacheOption.OnLoad;
b.EndInit();
b.Freeze();
return b;
}
}
/// Where Triforce lives on this PC, and the pieces of a per-user install (shortcuts, the Apps list entry).
static class Install
{
const string UninstallKey = @"Software\Microsoft\Windows\CurrentVersion\Uninstall\Triforce";
const string SettingsKey = @"Software\Triforce";
/// (testing: TRIFORCE_TEST_ROOT=<folder> keeps a whole install inside that folder. What would go to the registry is a text
/// file there, the shortcuts go to its Desktop and Start Menu folders, the build's work folder is its build folder and emulator
/// saves are looked for in its Roaming folder. The PC's real install is neither read nor touched.)
public static readonly string? TestRoot = Environment.GetEnvironmentVariable("TRIFORCE_TEST_ROOT") is { Length: > 0 } t ? Path.GetFullPath(t) : null;
static string TestStore => Path.Combine(TestRoot!, "registry.txt");
static string? Read(string key, string name)
{
if (TestRoot == null)
{
using var k = Registry.CurrentUser.OpenSubKey(key);
return k?.GetValue(name) as string;
}
var start = key + "\\" + name + "=";
return File.Exists(TestStore) ? File.ReadAllLines(TestStore).LastOrDefault(l => l.StartsWith(start))?.Substring(start.Length) : null;
}
static void Write(string key, string name, object value)
{
if (NoWrites) return;
if (TestRoot == null)
{
using var k = Registry.CurrentUser.CreateSubKey(key);
if (value is int n) k.SetValue(name, n, RegistryValueKind.DWord); else k.SetValue(name, value);
return;
}
Directory.CreateDirectory(TestRoot);
var start = key + "\\" + name + "=";
var lines = File.Exists(TestStore) ? File.ReadAllLines(TestStore).Where(l => !l.StartsWith(start)).ToList() : new List<string>();
lines.Add(start + value);
File.WriteAllLines(TestStore, lines);
}
static void Remove(string key)
{
if (TestRoot == null) { try { Registry.CurrentUser.DeleteSubKeyTree(key, false); } catch (Exception) { } return; }
if (File.Exists(TestStore)) File.WriteAllLines(TestStore, File.ReadAllLines(TestStore).Where(l => !l.StartsWith(key + "\\")).ToList());
}
/// May this run write there? Always, except in a test run (TRIFORCE_TEST_ROOT), which installs, builds, copies saves and
/// starts games only inside its own folder, whatever folder is typed or picked: so a look at Setup cannot change the PC's
/// real install, real game or real saves
public static bool Allowed(string path)
{
if (TestRoot == null) return true;
try { return (Path.GetFullPath(path).TrimEnd('\\') + "\\").StartsWith(TestRoot.TrimEnd('\\') + "\\", StringComparison.OrdinalIgnoreCase); }
catch (Exception) { return false; }
}
public static string TestOnly => "This is a test run of Setup: it only writes inside its own folder, " + TestRoot + ".";
static string LocalData => TestRoot ?? Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
public static string DefaultDir => Path.Combine(LocalData, "Programs", "Triforce");
public static string Self => Assembly.GetExecutingAssembly().Location;
public static string SelfDir => Path.GetDirectoryName(Self)!;
/// The install folder from the Apps list entry, when Triforce is installed
public static string? InstalledDir
{
get
{
var d = Read(UninstallKey, "InstallLocation");
return d != null && File.Exists(Path.Combine(d, Program.SetupAsset)) ? d : null;
}
}
public static bool RunningInstalled =>
InstalledDir is { } d && string.Equals(Path.GetFullPath(d).TrimEnd('\\'), Path.GetFullPath(SelfDir).TrimEnd('\\'), StringComparison.OrdinalIgnoreCase);
// ---- small settings (HKCU\Software\Triforce) ----
public static string? Get(string name) => Read(SettingsKey, name);
/// (--snapshot: pictures of the pages only; nothing is written to the registry or to setup.log)
public static bool NoWrites;
public static void Set(string name, string value) => Write(SettingsKey, name, value);
/// Copies this exe into the folder, registers it in the Apps list and makes the shortcuts. Returns the installed exe.
public static string Run(string dir, bool desktop, bool startMenu)
{
if (!Allowed(dir)) throw new InvalidOperationException(TestOnly);
Directory.CreateDirectory(dir);
var exe = Path.Combine(dir, Program.SetupAsset);
if (!string.Equals(Path.GetFullPath(exe), Path.GetFullPath(Self), StringComparison.OrdinalIgnoreCase))
File.Copy(Self, exe, true);
Write(UninstallKey, "DisplayName", Program.AppName);
Write(UninstallKey, "DisplayIcon", exe + ",0");
Write(UninstallKey, "DisplayVersion", Program.Version);
Write(UninstallKey, "Publisher", "Triforce");
Write(UninstallKey, "InstallLocation", dir);
Write(UninstallKey, "UninstallString", "\"" + exe + "\" --uninstall");
Write(UninstallKey, "QuietUninstallString", "\"" + exe + "\" --uninstall --quiet");
Write(UninstallKey, "URLInfoAbout", "https://github.com/" + Program.Repo);
Write(UninstallKey, "NoModify", 1);
Write(UninstallKey, "NoRepair", 1);
Set("Desktop", desktop ? "1" : "0");
Set("StartMenu", startMenu ? "1" : "0");
// ("Triforce" opens Setup, not the game: every start goes through the update question first, then Play starts the game)
try
{
if (startMenu) Shortcut(Path.Combine(StartFolder, "Triforce.lnk"), exe, "", dir, exe, "Play Triforce");
if (desktop) Shortcut(DesktopLink, exe, "", dir, exe, "Play Triforce");
}
catch (Exception e) { Program.Log("shortcuts: " + e.Message); }
return exe;
}
static string StartFolder => Path.Combine(TestRoot != null ? Path.Combine(TestRoot, "Start Menu") : Environment.GetFolderPath(Environment.SpecialFolder.Programs), "Triforce");
static string DesktopLink => Path.Combine(TestRoot != null ? Path.Combine(TestRoot, "Desktop") : Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "Triforce.lnk");
static void Shortcut(string link, string target, string args, string workDir, string icon, string description)
{
Directory.CreateDirectory(Path.GetDirectoryName(link)!);
var type = Type.GetTypeFromProgID("WScript.Shell")!;
var shell = Activator.CreateInstance(type)!;
try
{
var lnk = type.InvokeMember("CreateShortcut", BindingFlags.InvokeMethod, null, shell, new object[] { link })!;
var t = lnk.GetType();
t.InvokeMember("TargetPath", BindingFlags.SetProperty, null, lnk, new object[] { target });
t.InvokeMember("Arguments", BindingFlags.SetProperty, null, lnk, new object[] { args });
t.InvokeMember("WorkingDirectory", BindingFlags.SetProperty, null, lnk, new object[] { workDir });
t.InvokeMember("IconLocation", BindingFlags.SetProperty, null, lnk, new object[] { icon + ",0" });
t.InvokeMember("Description", BindingFlags.SetProperty, null, lnk, new object[] { description });
t.InvokeMember("Save", BindingFlags.InvokeMethod, null, lnk, null);
Marshal.FinalReleaseComObject(lnk);
}
finally { Marshal.FinalReleaseComObject(shell); }
}
/// Removes Setup, its tools and the shortcuts. Game folders and saves are the player's and stay.
public static bool Uninstall(bool quiet)
{
var dir = InstalledDir ?? SelfDir;
if (!quiet && MessageBox.Show("Remove Triforce Setup and its tools from this PC?\n\nYour game folders and saves are not touched.",
"Uninstall Triforce", MessageBoxButton.YesNo, MessageBoxImage.Question) != MessageBoxResult.Yes) return false;
foreach (var f in new[] { DesktopLink })
try { if (File.Exists(f)) File.Delete(f); } catch (Exception) { }
try { if (Directory.Exists(StartFolder)) Directory.Delete(StartFolder, true); } catch (Exception) { }
// (the build's work folder and compile cache, nx2/make_game.py --work: several GB, made again by a build)
var work = TestRoot != null ? Path.Combine(TestRoot, "build") : Path.Combine(LocalData, "Triforce", "build");
try { if (Directory.Exists(work)) Directory.Delete(work, true); } catch (Exception) { }
Remove(UninstallKey);
Remove(SettingsKey);
// (this exe is running from the folder: a short-lived cmd removes it once we are gone)
if (File.Exists(Path.Combine(dir, Program.SetupAsset)))
Process.Start(new ProcessStartInfo("cmd.exe", "/c timeout /t 2 /nobreak >nul & rmdir /s /q \"" + dir + "\"")
{ CreateNoWindow = true, UseShellExecute = false, WorkingDirectory = Path.GetTempPath() });
if (!quiet) MessageBox.Show("Triforce has been removed.", "Uninstall Triforce", MessageBoxButton.OK, MessageBoxImage.Information);
return true;
}
}
/// What a GitHub release offers
sealed class Release
{
public string Tag = "";
public string? SetupUrl, ToolsUrl;
public long SetupSize, ToolsSize;
/// The latest release (TRIFORCE_RELEASE_API overrides the address, for testing against a local copy)
public static async Task<Release> Latest(HttpClient http, CancellationToken token)
{
var url = Environment.GetEnvironmentVariable("TRIFORCE_RELEASE_API") is { Length: > 0 } o ? o
: "https://api.github.com/repos/" + Program.Repo + "/releases?per_page=1"; // (the newest, pre-releases too: /latest skips them)
using var ask = new CancellationTokenSource(TimeSpan.FromSeconds(20));
using var both = CancellationTokenSource.CreateLinkedTokenSource(token, ask.Token);
using var response = await http.GetAsync(url, both.Token);
if (response.StatusCode == HttpStatusCode.NotFound) throw new InvalidOperationException("There is no Triforce release yet.");
response.EnsureSuccessStatusCode();
var r = Parse(await response.Content.ReadAsStringAsync());
if (r.Tag.Length == 0) throw new InvalidOperationException("There is no Triforce release yet."); // (an empty list: nothing published)
return r;
}
/// GitHub's answer, read with a real JSON parser: a list of releases (the newest first) or one release. Each asset's
/// object holds a nested "uploader" object, so nothing simpler than a parser reads it right (v0.1.0 found no assets)
public static Release Parse(string json)
{
var parsed = new System.Web.Script.Serialization.JavaScriptSerializer { MaxJsonLength = int.MaxValue }.DeserializeObject(json);
var release = parsed is object[] list ? (list.Length > 0 ? list[0] as Dictionary<string, object> : null) : parsed as Dictionary<string, object>;
var r = new Release();
if (release == null) return r;
r.Tag = release.TryGetValue("tag_name", out var tag) ? tag as string ?? "" : "";
if (release.TryGetValue("assets", out var assets) && assets is object[] files)
foreach (var f in files.OfType<Dictionary<string, object>>())
{
var name = f.TryGetValue("name", out var n) ? n as string : null;
var link = f.TryGetValue("browser_download_url", out var l) ? l as string : null;
var size = f.TryGetValue("size", out var s) && s != null ? Convert.ToInt64(s) : 0;
if (string.Equals(name, Program.SetupAsset, StringComparison.OrdinalIgnoreCase)) { r.SetupUrl = link; r.SetupSize = size; }
if (string.Equals(name, Program.ToolsAsset, StringComparison.OrdinalIgnoreCase)) { r.ToolsUrl = link; r.ToolsSize = size; }
}
return r;
}
/// A file downloaded with progress (0..1) into place (a .part file until complete)
public static async Task Download(HttpClient http, string url, string file, long size, Action<double, long> progress, CancellationToken token)
{
var part = file + ".part";
using (var response = await http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead, token))
{
response.EnsureSuccessStatusCode();
var total = response.Content.Headers.ContentLength ?? size;
using var from = await response.Content.ReadAsStreamAsync();
using var to = File.Create(part);
var buffer = new byte[1 << 20];
long have = 0;
var shown = DateTime.MinValue;
for (int n; (n = await from.ReadAsync(buffer, 0, buffer.Length, token)) > 0;)
{
await to.WriteAsync(buffer, 0, n, token);
have += n;
if (DateTime.UtcNow - shown > TimeSpan.FromMilliseconds(150))
{
shown = DateTime.UtcNow;
progress(total > 0 ? Math.Min(1.0, (double)have / total) : 0, have);
}
}
if (total > 0 && have != total) throw new IOException("The download ended early (" + (have >> 20) + " of " + (total >> 20) + " MB).");
progress(1, have);
}
if (File.Exists(file)) File.Delete(file);
File.Move(part, file);
}
}
/// The Triforce tools beside the installed Setup: nx2/make_game.py and its own Python.
sealed class Tools
{
public readonly string Root, Python;
Tools(string root, string python) { Root = root; Python = python; }
public static string Folder => Path.Combine(Install.InstalledDir ?? Install.SelfDir, "tools");
/// The release these tools came from (tools/version.txt), null when there are none
public static string? InstalledVersion
{
get
{
var v = Path.Combine(Folder, "version.txt");
return File.Exists(v) && File.Exists(Path.Combine(Folder, "nx2", "make_game.py")) ? File.ReadAllText(v).Trim() : null;
}
}
public static Tools? Find()
{
var bundled = Folder;
if (File.Exists(Path.Combine(bundled, "nx2", "make_game.py")))
{
var py = Path.Combine(bundled, "python", "python.exe");
return new Tools(bundled, File.Exists(py) ? py : "python");
}
// (a development copy: Setup run from inside a checkout uses its sources and the PC's Python. Never in a test run,
// which has its own tools or none)
if (Install.TestRoot != null) return null;
for (var d = new DirectoryInfo(Install.SelfDir); d != null; d = d.Parent)
if (File.Exists(Path.Combine(d.FullName, "nx2", "make_game.py")))
return new Tools(d.FullName, Environment.GetEnvironmentVariable("TRIFORCE_PYTHON") ?? "python");
return null;
}
/// Unpacks Triforce-Tools.zip as the tools folder (the old one replaced only once the new one is complete)
public static void Unpack(string zip, string tag, Action<double> progress)
{
var target = Folder;
var part = target + ".part";
if (Directory.Exists(part)) Directory.Delete(part, true);
Directory.CreateDirectory(part);
using (var z = ZipFile.OpenRead(zip))
{
// (the zip holds tools/... or the tools' contents at its root)
// (and zips packed on Windows may say tools\... instead)
var prefix = z.Entries.All(e => e.FullName.Replace('\\', '/').StartsWith("tools/", StringComparison.OrdinalIgnoreCase)) ? "tools/" : "";
var full = Path.GetFullPath(part) + Path.DirectorySeparatorChar;
for (var i = 0; i < z.Entries.Count; i++)
{
var e = z.Entries[i];
var name = e.FullName.Replace('\\', '/').Substring(prefix.Length);
if (name.Length == 0) continue;
var dest = Path.GetFullPath(Path.Combine(part, name));
if (!dest.StartsWith(full, StringComparison.OrdinalIgnoreCase)) continue; // (no paths out of the folder)
if (name.EndsWith("/")) { Directory.CreateDirectory(dest); continue; }
Directory.CreateDirectory(Path.GetDirectoryName(dest)!);
e.ExtractToFile(dest, true);
if ((i & 15) == 0) progress((double)i / z.Entries.Count);
}
}
File.WriteAllText(Path.Combine(part, "version.txt"), tag + "\n");
var old = target + ".old";
if (Directory.Exists(old)) Directory.Delete(old, true);
if (Directory.Exists(target)) Directory.Move(target, old);
Directory.Move(part, target);
try { if (Directory.Exists(old)) Directory.Delete(old, true); } catch (Exception) { }
progress(1);
}
}
/// nx2/make_game.py as a child process: its lines as they come, and how it ended.
sealed class Runner
{
readonly Tools tools;
readonly List<string> args;
Process? process;
string? error;
bool cancelled;
public event Action<string>? Line;
public event Action<string?>? Finished;
public Runner(Tools tools, List<string> args) { this.tools = tools; this.args = args; }
static string Quote(string a)
{
if (a.Length > 0 && a.IndexOfAny(new[] { ' ', '\t', '"' }) < 0) return a;
var sb = new StringBuilder("\"");
for (var i = 0; i < a.Length; i++)
{
var slashes = 0;
while (i < a.Length && a[i] == '\\') { slashes++; i++; }
if (i == a.Length) { sb.Append('\\', slashes * 2); break; }
if (a[i] == '"') sb.Append('\\', slashes * 2 + 1).Append('"');
else sb.Append('\\', slashes).Append(a[i]);
}
return sb.Append('"').ToString();
}
static ProcessStartInfo Info(Tools tools, IEnumerable<string> args)
{
var all = new List<string> { "-I", Path.Combine(tools.Root, "nx2", "make_game.py") };
all.AddRange(args);
var si = new ProcessStartInfo(tools.Python, string.Join(" ", all.Select(Quote)))
{
WorkingDirectory = tools.Root,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
StandardOutputEncoding = Encoding.UTF8,
StandardErrorEncoding = Encoding.UTF8,
};
si.EnvironmentVariables["PYTHONIOENCODING"] = "utf-8";
// (written into the game folder: the game starts Setup again from here to update, host/hos_update.c)
var installed = Install.InstalledDir is { } d ? Path.Combine(d, Program.SetupAsset) : Install.Self;
si.EnvironmentVariables["HOOKSHOT_BUILDER_EXE"] = installed;
foreach (var (name, folder) in new[] { ("EMSDK", "emsdk"), ("RX_CPM", "cpm"), ("WGPU_NATIVE", "wgpu-native"), ("HOOKSHOT_MINGW", "llvm-mingw") })
{
var path = Path.Combine(tools.Root, folder);
if (Directory.Exists(path)) si.EnvironmentVariables[name] = path;
}
return si;
}
public void Start()
{
Task.Run(() =>
{
try
{
// (a test run builds and updates game folders only inside its own folder)
foreach (var name in new[] { "--out", "--update" })
{
var i = args.IndexOf(name);
if (i >= 0 && i + 1 < args.Count && !Install.Allowed(args[i + 1])) { Finished?.Invoke(Install.TestOnly); return; }
}
using var p = Process.Start(Info(tools, args))!;
process = p;
p.ErrorDataReceived += (_, e) => { if (e.Data != null) Line?.Invoke(e.Data); };
p.BeginErrorReadLine();
try { p.PriorityClass = ProcessPriorityClass.BelowNormal; } catch (Exception) { }
for (string? line; (line = p.StandardOutput.ReadLine()) != null;)
{
if (line.StartsWith("@@error ")) error = line.Substring(8);
Line?.Invoke(line);
}
p.WaitForExit();
Finished?.Invoke(cancelled ? "cancelled" : p.ExitCode == 0 ? null : error ?? "The build tools stopped without saying why. See the details.");
}
catch (Exception e)
{
Finished?.Invoke("The build tools could not start: " + e.Message);
}
});
}
public void Cancel()
{
cancelled = true;
try
{
if (process != null && !process.HasExited)
Process.Start(new ProcessStartInfo("taskkill", "/PID " + process.Id + " /T /F") { CreateNoWindow = true, UseShellExecute = false })?.WaitForExit(5000);
}
catch (Exception) { }
}
/// Is this the supported game and version? The answer in plain words.
public static Task<(bool Ok, string Text)> Check(Tools tools, IEnumerable<string> args) => Task.Run(() =>
{
try
{
using var p = Process.Start(Info(tools, args))!;
p.ErrorDataReceived += (_, _) => { };
p.BeginErrorReadLine();
var result = (false, "The game files could not be read.");
for (string? line; (line = p.StandardOutput.ReadLine()) != null;)
{
if (line.StartsWith("@@check ok ")) result = (true, line.Substring(11));
else if (line.StartsWith("@@check bad ")) result = (false, line.Substring(12));
else if (line.StartsWith("@@error ")) result = (false, line.Substring(8));
}
p.WaitForExit();
return result;
}
catch (Exception)
{
if (Directory.Exists(Path.Combine(tools.Root, "python")) && !File.Exists(Path.Combine(tools.Root, "python", "python.exe")))
return (false, "Triforce's own Python (tools\\python\\python.exe) is missing. Your antivirus probably removed it: restore it from " +
"quarantine, or start Triforce Setup again to download the tools once more.");
return (false, "Python was not found. Start Triforce Setup again to download the Triforce tools.");
}
});
}
/// Folder picker (the modern Explorer one, via IFileOpenDialog)
static class FolderPicker
{
[ComImport, Guid("DC1C5A9C-E88A-4dde-A5A1-60F82A20AEF7")] class FileOpenDialogRCW { }
[ComImport, Guid("42f85136-db7e-439c-85f1-e4075d135fc8"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IFileOpenDialog
{
[PreserveSig] int Show(IntPtr parent);
void SetFileTypes(); void SetFileTypeIndex(); void GetFileTypeIndex(); void Advise(); void Unadvise();
void SetOptions(uint fos); void GetOptions(out uint fos);
void SetDefaultFolder(IShellItem psi); void SetFolder(IShellItem psi);
void GetFolder(); void GetCurrentSelection();
void SetFileName([MarshalAs(UnmanagedType.LPWStr)] string name); void GetFileName();
void SetTitle([MarshalAs(UnmanagedType.LPWStr)] string title);
void SetOkButtonLabel(); void SetFileNameLabel();
void GetResult(out IShellItem item);
}
[ComImport, Guid("43826D1E-E718-42EE-BC55-A1E261C37BFE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
interface IShellItem
{
void BindToHandler(); void GetParent();
void GetDisplayName(uint sigdn, [MarshalAs(UnmanagedType.LPWStr)] out string name);
}
[DllImport("shell32.dll", CharSet = CharSet.Unicode, PreserveSig = false)]
static extern void SHCreateItemFromParsingName(string path, IntPtr bc, [MarshalAs(UnmanagedType.LPStruct)] Guid riid, out IShellItem item);
/// (testing, TRIFORCE_UI_SCRIPT: the folders the next picks answer with, no dialog shown)
public static readonly Queue<string> Answers = new();
public static string? Pick(Window owner, string title, string? start)
{
if (Answers.Count > 0) return Answers.Dequeue();
var d = (IFileOpenDialog)new FileOpenDialogRCW();
try
{
d.SetOptions(0x20 | 0x40 | 0x800); // (PICKFOLDERS | FORCEFILESYSTEM | PATHMUSTEXIST)
d.SetTitle(title);
if (start != null)
{
var s = start;
while (s.Length > 3 && !Directory.Exists(s)) s = Path.GetDirectoryName(s) ?? "";
if (Directory.Exists(s))
try { SHCreateItemFromParsingName(s, IntPtr.Zero, typeof(IShellItem).GUID, out var item); d.SetFolder(item); } catch (Exception) { }
}
if (d.Show(new System.Windows.Interop.WindowInteropHelper(owner).Handle) != 0) return null;
d.GetResult(out var result);
result.GetDisplayName(0x80058000, out var path); // (SIGDN_FILESYSPATH)
return path;
}
finally { Marshal.FinalReleaseComObject(d); }
}
}

128
setup/Shell.Home.cs Normal file
View File

@@ -0,0 +1,128 @@
// The welcome-back page (every start: play, or the update first, merged into the game).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Shapes;
namespace TriforceSetup;
sealed partial class Shell
{
Grid HomePage = null!;
TextBlock HomeTitle = null!, HomeNote = null!, GameLine = null!, GamePath = null!, NewsLine = null!, NewsDetail = null!, MergeNote = null!;
Caps HomeEyebrow = null!;
Rectangle GameMark = null!, SavesMark = null!, NewsMark = null!;
Button NotNowButton = null!, HomeGoButton = null!;
ToggleButton NewFolderLink = null!;
Action? homeGo;
void InitHome()
{
HomePage = Part<Grid>("HomePage");
HomeTitle = Part<TextBlock>("HomeTitle"); HomeNote = Part<TextBlock>("HomeNote"); GameLine = Part<TextBlock>("GameLine");
GamePath = Part<TextBlock>("GamePath"); NewsLine = Part<TextBlock>("NewsLine"); NewsDetail = Part<TextBlock>("NewsDetail");
MergeNote = Part<TextBlock>("MergeNote");
HomeEyebrow = Part<Caps>("HomeEyebrow");
GameMark = Part<Rectangle>("GameMark"); SavesMark = Part<Rectangle>("SavesMark"); NewsMark = Part<Rectangle>("NewsMark");
NotNowButton = Part<Button>("NotNowButton"); HomeGoButton = Part<Button>("HomeGoButton");
NewFolderLink = Part<ToggleButton>("NewFolderLink");
NotNowButton.Click += (_, _) => { Program.Log("update: not now"); AfterHome(); };
HomeGoButton.Click += (_, _) => homeGo?.Invoke();
NewFolderLink.Click += (_, _) => { NewFolderLink.IsChecked = false; ShowSetup(); };
InitSaves();
}
// ---- welcome back ----
Exception? homeOffline;
/// The game folder, the saves and the newest release, and the choice: Play, or Update & merge first
void ShowHome(Exception? offline)
{
homeOffline = offline;
var folder = Install.Get("GameFolder");
var hasGame = folder != null && GameExe(folder) != null;
var tools = Tools.InstalledVersion;
var built = hasGame ? BuiltVersion(folder!) : null;
Program.Log("home: GameFolder=[" + (folder ?? "null") + "] exe=[" + (folder != null ? GameExe(folder) ?? "null" : "-") + "] built=[" + (built ?? "null") + "] tools=[" + (tools ?? "null") + "] latest=[" + (latest?.Tag ?? "null") + "]");
var setupNewer = latest != null && Program.Version != "dev" && latest.Tag != Program.Version && latest.SetupUrl != null;
var toolsNewer = latest != null && latest.Tag != tools;
var gameBehind = hasGame && built != null && tools != null && built != tools; // (new tools already here, game not rebuilt yet)
var update = setupNewer || toolsNewer || gameBehind;
var target = latest?.Tag ?? tools ?? "";
HomeFill(hasGame, hasGame ? "Triforce " + (built ?? tools ?? "?") : null, folder, built, target, update, offline);
ShowSavesLine();
Show(HomePage);
if (!update) stage.Gleam(450);
if (update)
homeGo = () =>
{
Program.Log("update: merge " + target);
if (latest != null && (setupNewer || toolsNewer)) { merge = true; _ = Merge(); }
else if (hasGame && Tools.Find() is { } t) { OutPath.Text = folder!; BeginUpdate(); Run(t, new List<string> { "--update", folder! }, keepRows: true); }
};
else homeGo = AfterHome;
}
/// The page's words for one state of things (also what --snapshot shows, with sample values)
void HomeFill(bool hasGame, string? game, string? folder, string? built, string target, bool update, Exception? offline)
{
GameMark.Fill = Brush(hasGame ? "Gold" : "TextFaint");
GameLine.Text = hasGame ? game : "No game built yet";
GamePath.Text = hasGame ? folder : "Build one from your own copy of the game.";
if (offline != null)
{
var none = offline.Message.Contains("no Triforce release");
NewsMark.Fill = Brush("TextFaint");
NewsLine.Text = none ? "No release is published yet" : "Couldn't check for updates";
NewsDetail.Text = (none ? "" : "GitHub could not be reached. ") + (hasGame ? "You can play what you have." : "You can build with the tools you have.");
NewsDetail.Foreground = Brush("TextDim");
}
else if (update)
{
NewsMark.Fill = Brush("Gold300");
NewsLine.Text = "Triforce " + target + " is ready";
NewsDetail.Text = hasGame && built != null ? "Your game is " + built + "." : "Newer than the tools you have.";
NewsDetail.Foreground = Brush("Gold300");
}
else
{
NewsMark.Fill = Brush("Good");
NewsLine.Text = "Triforce " + target;
NewsDetail.Text = "You're up to date.";
NewsDetail.Foreground = Brush("Good");
}
HomeEyebrow.Label = update ? "A new version" : hasGame ? "IV · Play" : "III · Forge";
HomeEyebrow.Foreground = Brush(update ? "Gold300" : "Gold");
HomeTitle.Text = update ? "A new Triforce awaits" : "Welcome back, hero.";
HomeNote.Text = update ? "Merge the new version into your game now, or keep playing the one you have."
: !hasGame ? "The tools are ready. Build your game from your own copy and it will be waiting here."
: offline != null ? "Ready when you are."
: "Everything is in order. Settings and controls now live in the game's own menu.";
if (update)
{
MergeNote.Text = hasGame
? "Update & merge downloads Triforce " + target + " and builds your game folder again with it, from the game files it keeps. Only what changed is compiled again, so it usually takes a few minutes. Your saves and settings stay."
: "Update downloads Triforce " + target + "'s tools. Not now keeps the ones you have.";
HomeGoButton.Content = hasGame ? "Update & merge" : "Update";
NotNowButton.Content = hasGame ? "Play as it is" : "Not now";
NotNowButton.Visibility = Visibility.Visible;
}
else
{
MergeNote.Text = "";
HomeGoButton.Content = hasGame ? "Play" : "Build my game";
NotNowButton.Visibility = Visibility.Collapsed;
}
NewFolderLink.Visibility = hasGame ? Visibility.Visible : Visibility.Collapsed;
}
}

227
setup/Shell.Saves.cs Normal file
View File

@@ -0,0 +1,227 @@
// The Convert saves page: an emulator's saves into Triforce, or Triforce's out to an emulator (Saves.cs).
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
namespace TriforceSetup;
sealed partial class Shell
{
Grid SavesPage = null!;
RadioButton SavesIn = null!, SavesOut = null!;
Caps SavesListLabel = null!;
TextBlock SavesInfo = null!, SavesTarget = null!, SavesLine = null!, SavesDetail = null!;
Button SavesRescan = null!, SavesBrowse = null!, SavesBack = null!, SavesGo = null!, ConvertSavesButton = null!;
ListBox SaveList = null!;
List<SaveSet> found = new();
SaveSet? chosenFolder; // (one picked with Choose a folder)
bool savesBusy;
void InitSaves()
{
SavesPage = Part<Grid>("SavesPage");
SavesIn = Part<RadioButton>("SavesIn"); SavesOut = Part<RadioButton>("SavesOut");
SavesListLabel = Part<Caps>("SavesListLabel"); SavesInfo = Part<TextBlock>("SavesInfo"); SavesTarget = Part<TextBlock>("SavesTarget");
SavesLine = Part<TextBlock>("SavesLine"); SavesDetail = Part<TextBlock>("SavesDetail");
SavesRescan = Part<Button>("SavesRescan"); SavesBrowse = Part<Button>("SavesBrowse"); SavesBack = Part<Button>("SavesBack");
SavesGo = Part<Button>("SavesGo"); ConvertSavesButton = Part<Button>("ConvertSavesButton");
SaveList = Part<ListBox>("SaveList");
ConvertSavesButton.Click += (_, _) => ShowSaves();
SavesIn.Checked += (_, _) => SavesWayChanged();
SavesOut.Checked += (_, _) => SavesWayChanged();
SavesRescan.Click += (_, _) => { chosenFolder = null; _ = ScanSaves(); };
SavesBrowse.Click += (_, _) => BrowseSaves();
SavesBack.Click += (_, _) => ShowHome(homeOffline);
SavesGo.Click += (_, _) => ConvertNow();
SaveList.SelectionChanged += (_, _) => SavesRefresh();
}
static string? GameFolder() => Install.Get("GameFolder") is { } g && Directory.Exists(g) ? g : null;
/// The line on the welcome-back page
void ShowSavesLine()
{
var game = GameFolder();
if (game == null) { SavesLineFill(null, "None yet", "They can come in from an emulator once your game is built."); return; }
var t = Saves.Describe("Triforce", Saves.TriforceFolder(game));
if (t.Empty) SavesLineFill(false, "No saves yet", "Bring them in, or start a new game.");
else SavesLineFill(true, t.Slots + " save slot" + (t.Slots == 1 ? "" : "s"), "Last played " + t.Last.ToString("d MMM yyyy, HH:mm"));
}
void SavesLineFill(bool? have, string text, string detail)
{
SavesLine.Text = text;
SavesDetail.Text = detail;
SavesLine.Foreground = Brush(have == true ? "TextHi" : "Text");
SavesMark.Fill = Brush(have == true ? "Gold" : "TextFaint");
ConvertSavesButton.Visibility = have == null ? Visibility.Collapsed : Visibility.Visible;
}
void ShowSaves()
{
Show(SavesPage);
chosenFolder = null;
SavesWayChanged();
}
void SavesWayChanged()
{
if (SavesPage.Visibility != Visibility.Visible) return;
chosenFolder = null;
SavesListLabel.Label = SavesIn.IsChecked == true ? "Take the saves from" : "Put Triforce's saves into";
_ = ScanSaves();
}
async Task ScanSaves()
{
SaveList.ItemsSource = null;
SavesInfo.Text = "Looking for saves of Ocarina of Time on this PC...";
SavesInfo.Foreground = Brush("Text");
SavesGo.IsEnabled = false;
found = await Task.Run(() => Saves.FindEmulatorSaves());
ShowSaveList();
}
void ShowSaveList()
{
var items = new List<SaveSet>(found);
if (chosenFolder != null && items.All(s => !string.Equals(s.Folder, chosenFolder.Folder, StringComparison.OrdinalIgnoreCase))) items.Insert(0, chosenFolder);
SaveList.ItemsSource = items.Select(Item).ToList();
if (items.Count > 0) SaveList.SelectedIndex = 0;
SavesRefresh();
}
/// One place saves were found: its name, what it holds on the right, its folder under it
FrameworkElement Item(SaveSet s)
{
var g = new Grid { Tag = s };
g.ColumnDefinitions.Add(new ColumnDefinition());
g.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
g.RowDefinitions.Add(new RowDefinition());
g.RowDefinitions.Add(new RowDefinition());
var name = new TextBlock { Text = s.Name, Foreground = Brush("TextHi"), FontSize = 14, TextTrimming = TextTrimming.CharacterEllipsis, Margin = new Thickness(0, 0, 16, 0) };
var what = new TextBlock
{
Text = s.Empty ? "No saves here yet" : s.Slots + " slot" + (s.Slots == 1 ? "" : "s") + " · last played " + s.Last.ToString("d MMM yyyy, HH:mm"),
Foreground = Brush(s.Empty ? "TextDim" : "Gold"), FontSize = 12, VerticalAlignment = VerticalAlignment.Center,
};
var where = new TextBlock { Text = s.Folder, Foreground = Brush("TextFaint"), FontSize = 11.5, TextTrimming = TextTrimming.CharacterEllipsis, Margin = new Thickness(0, 3, 0, 0) };
Grid.SetColumn(what, 1);
Grid.SetRow(where, 1);
Grid.SetColumnSpan(where, 2);
g.Children.Add(name);
g.Children.Add(what);
g.Children.Add(where);
return g;
}
SaveSet? Picked => (SaveList.SelectedItem as FrameworkElement)?.Tag as SaveSet;
/// What Convert will do, said before it is done
void SavesRefresh()
{
if (savesBusy) return;
var game = GameFolder();
var into = SavesIn.IsChecked == true;
var pick = Picked;
SavesGo.IsEnabled = false;
SavesInfo.Foreground = Brush("Text");
SavesTarget.Text = "";
if (game == null)
{
SavesInfo.Text = "Build your game first: Triforce's saves live in its game folder.";
return;
}
var tri = Saves.Describe("Triforce", Saves.TriforceFolder(game));
if (!into && tri.Empty)
{
SavesInfo.Text = "Triforce has no saves yet to take out.";
return;
}
if (pick == null)
{
SavesInfo.Text = (found.Count == 0 ? "No emulator saves of this game were found. " : "") +
(into ? "Use Choose a folder to point at the saves (the folder with option.sav and slot_00 to slot_05)."
: "Use Choose a folder to point at the emulator's save folder for this game (0400486024DEC000).");
return;
}
if (into)
{
if (pick.Empty) { SavesInfo.Text = "That folder has no saves to bring in."; return; }
SavesInfo.Text = "Triforce's saves become " + pick.Name + "'s (" + pick.Slots + " slots, last played " + pick.Last.ToString("d MMM yyyy") + ")." +
(tri.Empty ? "" : " Triforce's current saves (" + tri.Slots + " slots, last played " + tri.Last.ToString("d MMM yyyy") + ") are backed up first.");
SavesTarget.Text = "Into " + tri.Folder;
}
else
{
SavesInfo.Text = pick.Name + "'s saves become Triforce's (" + tri.Slots + " slots, last played " + tri.Last.ToString("d MMM yyyy") + ")." +
(pick.Empty ? "" : " Its current saves (" + pick.Slots + " slots, last played " + pick.Last.ToString("d MMM yyyy") + ") are backed up first.");
SavesTarget.Text = "Into " + pick.Folder;
}
SavesGo.IsEnabled = true;
}
void BrowseSaves()
{
var into = SavesIn.IsChecked == true;
var dir = FolderPicker.Pick(Window, into ? "Choose the folder with the saves" : "Choose the emulator's save folder for Ocarina of Time", null);
if (dir == null) return;
var set = Saves.FindIn(dir);
if (set == null && into)
{
SavesInfo.Text = "No saves of this game were found in " + dir + ". Choose the folder that holds option.sav and slot_00 to slot_05.";
SavesInfo.Foreground = Brush("Bad");
return;
}
// (out of Triforce: a folder with no saves yet is fine, the saves go straight into it)
chosenFolder = Saves.Describe(System.IO.Path.GetFileName(dir.TrimEnd('\\')) + " (chosen)", set ?? dir);
ShowSaveList();
}
async void ConvertNow()
{
var game = GameFolder();
var pick = Picked;
if (game == null || pick == null) return;
if (Saves.RunningGame() is { } running)
{
SavesInfo.Text = "Close " + running + " first: it would write its own saves back over the copy when it closes.";
SavesInfo.Foreground = Brush("Bad");
return;
}
var into = SavesIn.IsChecked == true;
var tri = Saves.TriforceFolder(game);
var backups = System.IO.Path.Combine(Install.InstalledDir ?? Install.SelfDir, "save-backups");
savesBusy = true;
SavesGo.IsEnabled = false;
SavesInfo.Text = "Copying...";
try
{
var from = into ? pick.Folder : tri;
var to = into ? tri : pick.Folder;
var label = into ? "Triforce before " + pick.Name : pick.Name + " before Triforce";
var backup = await Task.Run(() => Saves.Copy(from, to, backups, label));
var now = Saves.Describe("", to);
Program.Log("saves: " + from + " -> " + to + (backup != null ? " (backup " + backup + ")" : ""));
savesBusy = false;
await ScanSaves();
SavesInfo.Text = "Done: " + now.Slots + " slot" + (now.Slots == 1 ? "" : "s") + " copied " + (into ? "into Triforce" : "into " + pick.Name) + "." +
(backup != null ? " The saves that were there are kept in " + backup + "." : "");
SavesInfo.Foreground = Brush("Good");
SavesGo.IsEnabled = false;
}
catch (Exception e)
{
savesBusy = false;
Program.Log("saves failed: " + e.Message);
SavesInfo.Text = "The saves could not be copied: " + e.Message;
SavesInfo.Foreground = Brush("Bad");
}
finally { savesBusy = false; }
}
}

359
setup/Shell.Test.cs Normal file
View File

@@ -0,0 +1,359 @@
// Looking at Setup and driving it without a screen (nothing here runs for a player):
// --snapshot <folder> every page and state drawn to a PNG with sample values, then exit
// TRIFORCE_UI_SCRIPT=<file> a list of steps (wait for a page, click a button, type a path, take a picture or a run of
// pictures to look at motion) run against the
// real flows in an off-screen window; it carries on in the Setup that an install or a self-update
// starts (the place in the list is kept beside the file). Pictures and script.log go to
// TRIFORCE_UI_SHOTS. Used with TRIFORCE_TEST_ROOT (Setup.cs), which keeps the install in one folder.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
namespace TriforceSetup;
sealed partial class Shell
{
/// The window's picture as it is now
RenderTargetBitmap Picture(double scale)
{
var rtb = new RenderTargetBitmap((int)(Root.ActualWidth * scale), (int)(Root.ActualHeight * scale), 96 * scale, 96 * scale, PixelFormats.Pbgra32);
var v = new DrawingVisual();
using (var dc = v.RenderOpen()) dc.DrawRectangle(Window.Background, null, new Rect(0, 0, Root.ActualWidth, Root.ActualHeight));
rtb.Render(v);
rtb.Render(Root);
rtb.Freeze();
return rtb;
}
static void SavePicture(BitmapSource picture, string dir, string name)
{
var enc = new PngBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(picture));
using var f = File.Create(System.IO.Path.Combine(dir, name + ".png"));
enc.Save(f);
}
async Task Shot(string dir, string name, int settle = 150)
{
await Window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
await Task.Delay(settle);
SavePicture(Picture(1.5), dir, name);
}
/// --snapshot <folder>: every page and every state that looks different, with sample values (nothing of this PC in them)
async void Snapshots(string dir)
{
try
{
Directory.CreateDirectory(dir);
Part<Border>("WindowEdge").Visibility = Visibility.Visible;
const string game = @"C:\Users\you\Games\Triforce";
lang = Strings.All[0];
LanguageBox.SelectedItem = lang;
InstallPath.Text = @"C:\Users\you\AppData\Local\Programs\Triforce";
InstallSpace.Text = @"Setup and its tools take about 2 GB. C:\ has 212 GB free.";
Show(InstallPage);
await Shot(dir, "01-install");
Show(FetchPage);
stage.All(false);
FetchUnknown(true);
FetchState("Gathering the stones", "Asking GitHub for the newest Triforce.", "Checking for updates");
FetchCancel.Content = "Cancel";
await Shot(dir, "02-gather-checking");
FetchState("Gathering the stones", "Downloading the Triforce tools (264 MB), once. Updates come the same way.", "Downloading the tools");
stage.Set(Art.Emerald, true); stage.Set(Art.Sapphire, true); stage.Charge(Art.Ruby, 0.62 * 0.7);
FetchProgress(0.62, "164 / 264 MB");
await Shot(dir, "03-gather-download");
stage.All(false);
FetchUnknown(false);
FetchTitle.Text = "GitHub could not be reached";
FetchNote.Text = "Check your internet connection, then try again.";
FetchNote.Foreground = Brush("Bad");
FetchStep.Text = "";
FetchRetry.Visibility = FetchSkip.Visibility = Visibility.Visible;
FetchCancel.Content = "Close";
await Shot(dir, "04-gather-failed");
FetchRetry.Visibility = FetchSkip.Visibility = Visibility.Collapsed;
// welcome back: ready, an update, nothing built yet, no answer from GitHub
HomeFill(true, "Triforce v1.1.0", game, "v1.1.0", "v1.1.0", false, null);
SavesLineFill(true, "6 save slots", "Last played 8 Nov 2026, 02:46");
Show(HomePage);
await Shot(dir, "05-home-ready");
// (the gleam held at seven places on its way across, in gleam\: the same page, so each differs from 05-home-ready
// only by the band, which must lie on the crest's own pixels and nowhere else)
Directory.CreateDirectory(System.IO.Path.Combine(dir, "gleam"));
foreach (var at in new[] { 5, 20, 35, 50, 65, 80, 95 })
{
stage.GleamAt(at / 100.0);
await Shot(System.IO.Path.Combine(dir, "gleam"), "home-gleam-" + at.ToString("00"));
}
stage.GleamAt(-1);
// (and the ring of marks an eighth of a turn on: the fine ring inside it must not change at all)
stage.TurnMarks(45);
await Shot(System.IO.Path.Combine(dir, "gleam"), "arc-marks-turned-45");
stage.TurnMarks(0);
HomeFill(true, "Triforce v1.0.0", game, "v1.0.0", "v1.1.0", true, null);
await Shot(dir, "06-home-update");
HomeFill(false, null, null, null, "v1.1.0", false, null);
SavesLineFill(null, "None yet", "They can come in from an emulator once your game is built.");
await Shot(dir, "07-home-no-game");
HomeFill(true, "Triforce v1.1.0", game, "v1.1.0", "v1.1.0", false, new System.Net.Http.HttpRequestException("offline"));
SavesLineFill(false, "No saves yet", "Bring them in, or start a new game.");
await Shot(dir, "08-home-offline");
// the forge: nothing chosen yet, a checked file with a game to update, folders with the wrong version
OutPath.Text = game;
Show(SetupPage);
checkDelay.Stop();
Say(T(S.DropHint), "TextDim", null);
SpaceText.Text = T(S.Needs) + " " + string.Format(T(S.Free), @"C:\", 212);
await Shot(dir, "09-forge");
UpdateBanner.Visibility = Visibility.Visible;
UpdateText.Text = "Your game in " + game + " is Triforce v1.0.0. Version v1.1.0 is ready: updating keeps your saves and settings.";
NupPath.Text = @"D:\Games\OcarinaOfTime.nup";
checkDelay.Stop();
Say(T(S.VersionOk), "Good", "Good");
BuildButton.IsEnabled = true;
SpaceText.Text = T(S.Needs) + " " + string.Format(T(S.Free), @"C:\", 212);
await Shot(dir, "10-forge-checked");
UpdateBanner.Visibility = Visibility.Collapsed;
UseFolders.IsChecked = true;
RomfsPath.Text = @"D:\Games\OcarinaOfTime\romfs"; ExefsPath.Text = @"D:\Games\OcarinaOfTime\exefs";
checkDelay.Stop();
Say(T(S.VersionBad), "Bad", "Bad");
BuildButton.IsEnabled = false;
SpaceText.Text = T(S.Needs) + " " + string.Format(T(S.Free), @"C:\", 212);
await Shot(dir, "11-forge-folders");
foreach (var code in new[] { "de", "ja" })
{
lang = Strings.All.First(l => l.Code == code);
LanguageBox.SelectedItem = lang;
checkDelay.Stop();
Say(T(S.VersionBad), "Bad", "Bad");
SpaceText.Text = T(S.Needs) + " " + string.Format(T(S.Free), @"C:\", 212);
await Shot(dir, "12-forge-" + code);
}
lang = Strings.All[0];
LanguageBox.SelectedItem = lang;
checkDelay.Stop();
UseNup.IsChecked = true;
checkDelay.Stop();
// building: a step running, its details, done, stopped, and the question when closing
Show(BuildPage);
stage.All(false);
BuildTitle.Text = T(S.Building);
BuildNote.Text = T(S.Patience) + " " + T(S.Elapsed) + ": 14 min";
rows["read"].Done(); rows["lift"].Done(); rows["compile"].Begin(); rows["compile"].Progress(0.41);
SetButtons(cancel: true);
await Shot(dir, "13-build");
Log.Text = string.Join("\n", new[]
{
"@@stage read", "reading D:\\Games\\OcarinaOfTime.nup", "program 0400486024DEC000, update v131072, build e0f3ccfa", "romfs: 18,412 files, 11.6 GB",
"@@stage lift", "lifting 14,134 functions in 96 pieces", "lift done in 222 s", "@@stage compile",
"[ 312/ 760] clang -O2 -c sa/gen/code_038.c -o sa/build/code_038.o", "[ 313/ 760] clang -O2 -c sa/gen/code_039.c -o sa/build/code_039.o",
"[ 314/ 760] clang -O2 -c sa/gen/code_040.c -o sa/build/code_040.o", "[ 315/ 760] clang -O2 -c sa/gen/code_041.c -o sa/build/code_041.o",
});
ShowLog.IsChecked = true;
await Shot(dir, "14-build-details");
ShowLog.IsChecked = false;
Ask(T(S.CloseQuestion), T(S.StopClose), T(S.KeepBuilding), () => { });
await Shot(dir, "15-build-ask-close");
HideAsk();
foreach (var r in rows.Values) r.Done();
stage.All(true);
BuildEyebrow.Label = "IV · Play";
BuildTitle.Text = T(S.Ready);
BuildNote.Text = game + " · " + T(S.BuiltIn) + " 38 min";
SetButtons(done: true);
await Shot(dir, "16-build-done");
foreach (var r in rows.Values) r.Reset();
stage.All(false);
BuildEyebrow.Label = "III · Forge";
rows["read"].Done(); rows["lift"].Done(); rows["compile"].Begin(); rows["compile"].Stopped();
BuildTitle.Text = T(S.Stopped);
BuildNote.Text = "The compiler stopped at sa/gen/code_041.c (exit code 1). See the details.";
BuildNote.Foreground = Brush("Bad");
SetButtons(back: true);
await Shot(dir, "17-build-stopped");
BuildNote.Foreground = Brush("Text");
// convert saves: what was found, and nothing found
Show(SavesPage);
found = new List<SaveSet>
{
new() { Name = "Eden", Folder = @"C:\Users\you\AppData\Roaming\eden\nand\user\save\0000000000000000\1401D3E59D96EFFB99D2488BA99C6EBE\" + Saves.TitleId, Slots = 6, Last = new DateTime(2026, 11, 9, 6, 19, 0) },
new() { Name = "Ryujinx", Folder = @"C:\Users\you\AppData\Roaming\Ryujinx\bis\user\save\0000000000000003\0", Slots = 3, Last = new DateTime(2026, 10, 30, 21, 20, 0) },
new() { Name = @"yuzu (D:\Emulators\yuzu)", Folder = @"D:\Emulators\yuzu\user\nand\user\save\0000000000000000\8A1C0F6E27B94D13A5E07C2B9F3D6E41\" + Saves.TitleId, Slots = 1, Last = new DateTime(2026, 6, 2, 18, 5, 0) },
};
SavesListLabel.Label = "Take the saves from";
ShowSaveList();
SavesInfo.Text = "Triforce's saves become Eden's (6 slots, last played 9 Nov 2026). Triforce's current saves (6 slots, last played 8 Nov 2026) are backed up first.";
SavesInfo.Foreground = Brush("Text");
SavesTarget.Text = @"Into " + game + @"\user\save\" + Saves.TriforceUid;
SavesGo.IsEnabled = true;
await Shot(dir, "18-saves");
found = new List<SaveSet>();
ShowSaveList();
SavesOut.IsChecked = true;
await Window.Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ApplicationIdle);
SaveList.ItemsSource = null;
SavesListLabel.Label = "Put Triforce's saves into";
SavesInfo.Text = "No emulator saves of this game were found. Use Choose a folder to point at the emulator's save folder for this game (0400486024DEC000).";
SavesInfo.Foreground = Brush("Text");
SavesTarget.Text = "";
SavesGo.IsEnabled = false;
await Shot(dir, "19-saves-none");
}
catch (Exception e)
{
File.WriteAllText(System.IO.Path.Combine(dir, "error.txt"), e.ToString());
}
Window.Close();
}
// ---- TRIFORCE_UI_SCRIPT ----
string? scriptFile, scriptShots;
/// A script to follow (testing)? Then the window stays off the screen and the steps start once it is up
bool Scripted()
{
scriptFile = Environment.GetEnvironmentVariable("TRIFORCE_UI_SCRIPT");
if (string.IsNullOrEmpty(scriptFile) || !File.Exists(scriptFile)) return false;
scriptShots = Environment.GetEnvironmentVariable("TRIFORCE_UI_SHOTS") is { Length: > 0 } s ? s : System.IO.Path.GetDirectoryName(scriptFile)!;
Directory.CreateDirectory(scriptShots);
Window.WindowStartupLocation = WindowStartupLocation.Manual;
Window.Left = -20000;
Window.ShowActivated = false;
Window.ShowInTaskbar = false;
return true;
}
void ScriptLog(string line)
{
try { File.AppendAllText(System.IO.Path.Combine(scriptShots!, "script.log"), DateTime.Now.ToString("HH:mm:ss.fff") + " " + line + Environment.NewLine); } catch (Exception) { }
}
async void RunScript()
{
var steps = File.ReadAllLines(scriptFile!);
var place = scriptFile + ".pos";
var at = File.Exists(place) && int.TryParse(File.ReadAllText(place).Trim(), out var p) ? p : 0;
ScriptLog("-- Setup " + Program.Version + " (" + Install.Self + ") from step " + at + "; window " + Window.ActualWidth + " x " + Window.ActualHeight + ", inside " + Part<Grid>("Host").ActualWidth + " x " + Part<Grid>("Host").ActualHeight + ", picture " + Root.ActualWidth + " x " + Root.ActualHeight + ", Windows' answer about the edge colour 0x" + edgeAnswer.ToString("X8") + " (" + edgeNote + ")");
try
{
for (; at < steps.Length; at++)
{
var line = steps[at].Trim();
var cut = line.Split(new[] { ' ' }, 3);
var waits = cut[0] == "wait" || cut[0] == "enabled" || cut[0] == "gone";
if (!waits) File.WriteAllText(place, (at + 1).ToString());
if (line.Length == 0 || line.StartsWith("#")) continue;
string a = cut.Length > 1 ? cut[1] : "", b = cut.Length > 2 ? cut[2] : "";
switch (cut[0])
{
case "wait": // wait <page> [seconds]
await Until(() => Part<FrameworkElement>(a).Visibility == Visibility.Visible, b, line);
break;
case "enabled": // enabled <control> [seconds]
await Until(() => Part<FrameworkElement>(a) is { IsEnabled: true, IsVisible: true }, b, line);
break;
case "gone": // gone <page> [seconds]
await Until(() => Part<FrameworkElement>(a).Visibility != Visibility.Visible, b, line);
break;
case "click":
var c = Part<FrameworkElement>(a);
if (!c.IsVisible || !c.IsEnabled) throw new InvalidOperationException(a + " cannot be clicked (visible " + c.IsVisible + ", enabled " + c.IsEnabled + ")");
if (c is ToggleButton t && c is not RadioButton) t.IsChecked = t.IsChecked != true;
else if (c is RadioButton r) r.IsChecked = true;
if (c is ButtonBase) c.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
break;
case "text": Part<TextBox>(a).Text = b; break;
case "pick": FolderPicker.Answers.Enqueue(a + (b.Length > 0 ? " " + b : "")); break;
case "select": SaveList.SelectedIndex = int.Parse(a); break;
case "sleep": await Task.Delay(int.Parse(a)); break;
case "shot": await Shot(scriptShots!, a, 700); break;
case "frames": // frames <name> <count> <ms apart>: what is on screen now and at each step after (to look at motion)
case "crest": // crest <name> <count> <ms apart>: the same, but only the crest and its surroundings, at full size
var f = b.Split(' ');
var run = new List<(double at, BitmapSource picture)>();
var watch = System.Diagnostics.Stopwatch.StartNew();
for (var n = 0; n < int.Parse(f[0]); n++)
{
if (n > 0) await Task.Delay(int.Parse(f[1]));
BitmapSource now = cut[0] == "frames" ? Picture(0.75) : new CroppedBitmap(Picture(1.5), new Int32Rect(960, 144, 615, 576));
now.Freeze();
run.Add((watch.Elapsed.TotalMilliseconds, now));
}
// (saved afterwards: writing a picture takes longer than the motion lasts)
for (var n = 0; n < run.Count; n++) SavePicture(run[n].picture, scriptShots!, a + "-" + n.ToString("00") + "-" + (int)run[n].at + "ms");
break;
case "sheen": // sheen <main button> <x>: the light that crosses a gold button under the mouse, held at x (no mouse here)
var gold = Part<Button>(a);
gold.ApplyTemplate();
if (gold.Template.FindName("Sheen", gold) is not FrameworkElement light) throw new InvalidOperationException(a + " has no sheen");
light.Opacity = 1;
light.RenderTransform = new TranslateTransform(double.Parse(b, System.Globalization.CultureInfo.InvariantCulture), 0);
break;
case "expect": // expect <part> <words it must contain>
var words = Words(Part<FrameworkElement>(a));
if (words.IndexOf(b, StringComparison.OrdinalIgnoreCase) < 0) throw new InvalidOperationException(a + " says \"" + words + "\", not \"" + b + "\"");
break;
case "exit":
ScriptLog("PASS exit");
closing = true;
Window.Close();
return;
default: throw new InvalidOperationException("unknown step");
}
if (waits) File.WriteAllText(place, (at + 1).ToString());
ScriptLog("ok " + line);
}
ScriptLog("PASS end of script");
}
catch (Exception e)
{
ScriptLog("FAIL " + (at < steps.Length ? steps[at] : "") + ": " + e.Message + " [page " + (shown?.Name ?? "none") + "]");
try { await Shot(scriptShots!, "FAIL-step-" + at, 100); } catch (Exception) { }
File.WriteAllText(place, steps.Length.ToString());
runner?.Cancel();
Environment.Exit(4);
}
}
async Task Until(Func<bool> done, string seconds, string line)
{
var limit = DateTime.UtcNow.AddSeconds(double.TryParse(seconds, out var s) ? s : 30);
while (!done())
{
if (DateTime.UtcNow > limit) throw new TimeoutException("waited too long");
await Task.Delay(100);
}
}
static string Words(FrameworkElement e) => e switch
{
TextBlock t => t.Text.Replace("\u200A", ""),
TextBox t => t.Text,
ContentControl c => c.Content as string ?? "",
_ => "",
};
}

969
setup/Shell.cs Normal file
View File

@@ -0,0 +1,969 @@
// Triforce Setup's window: install -> gather (update check, downloads) -> forge (choose the game, build) -> play.
// The pages are on the left; on the right the crest (Stage.cs), whose stones go out when work starts and light as it is done.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Interop;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Threading;
using Microsoft.Win32;
namespace TriforceSetup;
sealed partial class Shell
{
public readonly Window Window;
const long NeededBytes = 60L << 30;
// (the build's steps, and the stone each one lights when it is done; the last one makes the whole crest gleam)
static readonly (string Id, S Text, int Stone)[] Stages =
{ ("read", S.Read, Art.Emerald), ("lift", S.Lift, Art.Sapphire), ("compile", S.Compile, Art.Ruby), ("finish", S.Finish, -1) };
// parts of Main.xaml
readonly Grid Root, InstallPage, FetchPage, SetupPage, BuildPage, NupRow, AskLayer;
readonly TextBox InstallPath, NupPath, RomfsPath, ExefsPath, OutPath, Log;
readonly TextBlock InstallSpace, FetchTitle, FetchNote, FetchStep, FetchPercent, FetchNumber, Subtitle, UpdateText, CheckText,
SpaceText, BuildTitle, BuildNote, VersionText, AskText;
readonly Caps LanguageLabel, GameFilesLabel, SaveToLabel, BuildEyebrow;
readonly CheckBox DesktopIcon, StartIcon;
readonly Button InstallButton, BrowseInstall, FetchSkip, FetchCancel, FetchRetry, UpdateGameButton, BrowseA, BrowseB, BrowseC, BrowseD, BuildButton,
OpenButton, BackButton, CancelButton, PlayButton, AskYes, AskNo;
readonly Rectangle CheckMark;
readonly ProgressLine FetchBar;
readonly Border UpdateBanner;
readonly StackPanel FolderRows, StageList, FetchNumberRow;
readonly ColumnDefinition StageColumn;
readonly RadioButton UseNup, UseFolders;
readonly ComboBox LanguageBox;
readonly ToggleButton ShowLog;
readonly Stage stage;
readonly string? updateFolder;
readonly bool relaunched;
bool merge;
Release? latest;
readonly string[]? autoBuild; // (testing: --auto-build <exefs> <romfs> <out> builds with the installed tools, as the Build button does)
Language lang;
readonly Dictionary<string, StageRow> rows = new();
readonly DispatcherTimer clock = new() { Interval = TimeSpan.FromSeconds(1) };
readonly DispatcherTimer checkDelay = new() { Interval = TimeSpan.FromMilliseconds(500) };
readonly Stopwatch elapsed = new();
Runner? runner;
string? current;
string finished = "";
int checkSerial;
bool sourceOk;
CancellationTokenSource? fetch;
Action? bannerAction, askYes;
bool closing;
Grid? shown;
readonly string? snapshot;
string T(S s) => (int)s < lang.Text.Length ? lang.Text[(int)s] : Strings.All[0].Text[(int)s];
T Part<T>(string name) where T : class => (Window.FindName(name) as T) ?? throw new InvalidOperationException("Main.xaml has no " + name);
Brush Brush(string key) => (Brush)Window.Resources[key];
public Shell(string[] args)
{
for (var i = 0; i < args.Length; i++)
{
if (args[i] == "--update" && i + 1 < args.Length) { updateFolder = args[++i]; merge = true; }
else if (args[i] == "--merge") merge = true;
else if (args[i] == "--relaunched") relaunched = true;
else if (args[i] == "--snapshot" && i + 1 < args.Length) snapshot = args[++i];
else if (args[i] == "--auto-build" && i + 3 < args.Length) autoBuild = new[] { args[++i], args[++i], args[++i] };
}
Fx.Still = snapshot != null;
Art.Load();
using (var s = Program.Resource("Main.xaml")) Window = (Window)XamlReader.Load(s);
Root = Part<Grid>("Root"); AskLayer = Part<Grid>("AskLayer");
InstallPage = Part<Grid>("InstallPage"); FetchPage = Part<Grid>("FetchPage"); SetupPage = Part<Grid>("SetupPage"); BuildPage = Part<Grid>("BuildPage");
NupRow = Part<Grid>("NupRow");
InstallPath = Part<TextBox>("InstallPath"); NupPath = Part<TextBox>("NupPath"); RomfsPath = Part<TextBox>("RomfsPath");
ExefsPath = Part<TextBox>("ExefsPath"); OutPath = Part<TextBox>("OutPath"); Log = Part<TextBox>("Log");
InstallSpace = Part<TextBlock>("InstallSpace"); FetchTitle = Part<TextBlock>("FetchTitle"); FetchNote = Part<TextBlock>("FetchNote");
FetchStep = Part<TextBlock>("FetchStep"); FetchPercent = Part<TextBlock>("FetchPercent"); FetchNumber = Part<TextBlock>("FetchNumber");
Subtitle = Part<TextBlock>("Subtitle"); UpdateText = Part<TextBlock>("UpdateText");
CheckText = Part<TextBlock>("CheckText"); SpaceText = Part<TextBlock>("SpaceText");
BuildTitle = Part<TextBlock>("BuildTitle"); BuildNote = Part<TextBlock>("BuildNote"); VersionText = Part<TextBlock>("VersionText");
AskText = Part<TextBlock>("AskText");
LanguageLabel = Part<Caps>("LanguageLabel"); GameFilesLabel = Part<Caps>("GameFilesLabel"); SaveToLabel = Part<Caps>("SaveToLabel");
BuildEyebrow = Part<Caps>("BuildEyebrow");
DesktopIcon = Part<CheckBox>("DesktopIcon"); StartIcon = Part<CheckBox>("StartIcon");
InstallButton = Part<Button>("InstallButton"); BrowseInstall = Part<Button>("BrowseInstall"); FetchSkip = Part<Button>("FetchSkip");
FetchCancel = Part<Button>("FetchCancel"); FetchRetry = Part<Button>("FetchRetry"); UpdateGameButton = Part<Button>("UpdateGameButton");
BrowseA = Part<Button>("BrowseA"); BrowseB = Part<Button>("BrowseB"); BrowseC = Part<Button>("BrowseC"); BrowseD = Part<Button>("BrowseD");
BuildButton = Part<Button>("BuildButton"); OpenButton = Part<Button>("OpenButton"); BackButton = Part<Button>("BackButton");
CancelButton = Part<Button>("CancelButton"); PlayButton = Part<Button>("PlayButton");
AskYes = Part<Button>("AskYes"); AskNo = Part<Button>("AskNo");
CheckMark = Part<Rectangle>("CheckMark");
FetchBar = Part<ProgressLine>("FetchBar"); UpdateBanner = Part<Border>("UpdateBanner");
FolderRows = Part<StackPanel>("FolderRows"); StageList = Part<StackPanel>("StageList"); FetchNumberRow = Part<StackPanel>("FetchNumberRow");
StageColumn = Part<ColumnDefinition>("StageColumn");
UseNup = Part<RadioButton>("UseNup"); UseFolders = Part<RadioButton>("UseFolders");
LanguageBox = Part<ComboBox>("LanguageBox"); ShowLog = Part<ToggleButton>("ShowLog");
stage = new Stage();
Part<Grid>("StageHost").Children.Add(stage.Root);
InitHome();
Window.Icon = Program.Image("icon.png");
VersionText.Text = Program.Version;
var saved = Install.Get("Language");
lang = Strings.All.FirstOrDefault(l => l.Code == saved) ?? Strings.Default();
Wire();
for (var i = 0; i < Stages.Length; i++)
{
rows[Stages[i].Id] = new StageRow(this, T(Stages[i].Text), Stages[i].Stone, i == Stages.Length - 1);
StageList.Children.Add(rows[Stages[i].Id].Root);
}
LanguageBox.ItemsSource = Strings.All;
LanguageBox.SelectedItem = lang;
ApplyLanguage();
FitToScreen();
// (asked once the window is up: an off-screen run showed a SourceInitialized handler added here is never called)
Window.Loaded += (_, _) => Frame();
if (snapshot != null)
{
Window.WindowStartupLocation = WindowStartupLocation.Manual;
Window.Left = -20000;
Window.ShowActivated = false;
Window.ShowInTaskbar = false;
Window.Loaded += (_, _) => Snapshots(snapshot);
}
else
{
var scripted = Scripted();
Window.Loaded += (_, _) => { Begin(); if (scripted) RunScript(); };
}
}
/// One composed picture, 1060 x 640: on a screen too small for it (a small laptop at a large text size) the whole of it is
/// scaled down to fit rather than cut off
void FitToScreen()
{
var area = SystemParameters.WorkArea;
var k = Math.Min(1, Math.Min((area.Width - 24) / Stage.WindowWidth, (area.Height - 24) / Stage.WindowHeight));
if (k < 1 && k > 0.4) Root.LayoutTransform = new ScaleTransform(k, k); else k = 1;
Window.Width = Stage.WindowWidth * k;
Window.Height = Stage.WindowHeight * k;
// (should Windows give the window's inside another size than asked for, the window takes up the difference once)
Window.Loaded += (_, _) =>
{
var host = Part<Grid>("Host");
double dw = Stage.WindowWidth * k - host.ActualWidth, dh = Stage.WindowHeight * k - host.ActualHeight;
if (Math.Abs(dw) > 0.5 && Math.Abs(dw) < 60) Window.Width += dw;
if (Math.Abs(dh) > 0.5 && Math.Abs(dh) < 60) Window.Height += dh;
};
}
[DllImport("dwmapi.dll")]
static extern int DwmSetWindowAttribute(IntPtr window, int attribute, ref int value, int size);
int edgeAnswer = -1; // (0: Windows draws the window's edge in our colour)
string edgeNote = "not asked";
/// The window's frame as the game's own (host/display.c): dark, with an edge of old gold. Windows 11 draws that edge itself
/// (round corners and all); where it cannot (Windows 10), the window keeps the fine edge it draws itself
void Frame()
{
try
{
var handle = new WindowInteropHelper(Window).Handle;
edgeNote = "asked, window " + handle;
var dark = 1;
DwmSetWindowAttribute(handle, 20, ref dark, 4);
var edge = 0x001E546E; // (COLORREF 0x00BBGGRR: RGB 110, 84, 30)
edgeAnswer = DwmSetWindowAttribute(handle, 34, ref edge, 4);
if (edgeAnswer == 0) Part<Border>("WindowEdge").Visibility = Visibility.Collapsed;
}
catch (Exception e) { edgeNote = e.GetType().Name + ": " + e.Message; }
}
void Wire()
{
Part<Button>("MinButton").Click += (_, _) => Window.WindowState = WindowState.Minimized;
Window.StateChanged += (_, _) => Fx.Paused = Window.WindowState == WindowState.Minimized;
Part<Button>("CloseButton").Click += (_, _) => CloseWindow();
Window.Closing += (_, e) =>
{
// (a build is running: asked first, in the window's own words)
if (runner != null && !closing)
{
e.Cancel = true;
Ask(T(S.CloseQuestion), T(S.StopClose), T(S.KeepBuilding), () => { closing = true; Window.Close(); });
return;
}
runner?.Cancel();
fetch?.Cancel();
};
AskYes.Click += (_, _) => { var yes = askYes; HideAsk(); yes?.Invoke(); };
AskNo.Click += (_, _) => HideAsk();
Window.PreviewKeyDown += (_, e) => { if (e.Key == System.Windows.Input.Key.Escape && AskLayer.Visibility == Visibility.Visible) { HideAsk(); e.Handled = true; } };
InstallButton.Click += (_, _) => DoInstall();
BrowseInstall.Click += (_, _) => { var p = FolderPicker.Pick(Window, "Choose where to install Triforce", InstallPath.Text); if (p != null) InstallPath.Text = System.IO.Path.Combine(p, "Triforce"); };
InstallPath.TextChanged += (_, _) => InstallSpaceText();
FetchCancel.Click += (_, _) => { if (fetch != null) fetch.Cancel(); else Window.Close(); };
FetchRetry.Click += (_, _) => Gather();
FetchSkip.Click += (_, _) => { if (HasGame) ShowHome(latest == null ? fetchFailure : null); else ShowSetup(); };
UpdateGameButton.Click += (_, _) => bannerAction?.Invoke();
UseNup.Checked += (_, _) => SourceKindChanged();
UseFolders.Checked += (_, _) => SourceKindChanged();
foreach (var t in new[] { NupPath, RomfsPath, ExefsPath, OutPath }) t.TextChanged += (_, _) => PathsChanged();
BrowseA.Click += (_, _) => BrowseNup();
BrowseB.Click += (_, _) => RomfsPath.Text = FolderPicker.Pick(Window, "Choose the romfs folder", RomfsPath.Text) ?? RomfsPath.Text;
BrowseC.Click += (_, _) => ExefsPath.Text = FolderPicker.Pick(Window, "Choose the exefs folder", ExefsPath.Text) ?? ExefsPath.Text;
BrowseD.Click += (_, _) => OutPath.Text = FolderPicker.Pick(Window, "Choose where to save the game", OutPath.Text) ?? OutPath.Text;
BuildButton.Click += (_, _) => StartBuild();
CancelButton.Click += (_, _) => { fetch?.Cancel(); runner?.Cancel(); };
BackButton.Click += (_, _) => ShowSetup();
OpenButton.Click += (_, _) => Process.Start(new ProcessStartInfo("explorer.exe", "\"" + finished + "\"") { UseShellExecute = true });
PlayButton.Click += (_, _) => Play(finished);
ShowLog.Checked += (_, _) => LogToggled();
ShowLog.Unchecked += (_, _) => LogToggled();
LanguageBox.SelectionChanged += (_, _) =>
{
if (LanguageBox.SelectedItem is Language l) { lang = l; Install.Set("Language", l.Code); ApplyLanguage(); }
};
Window.Drop += Dropped;
clock.Tick += (_, _) => ShowClock();
checkDelay.Tick += (_, _) => { checkDelay.Stop(); CheckSource(); };
}
void CloseWindow() => Window.Close();
/// A question over the whole window: the gold button does it, the other one (or Esc) leaves things as they are
void Ask(string question, string yes, string no, Action onYes)
{
AskText.Text = question;
AskYes.Content = yes;
AskNo.Content = no;
askYes = onYes;
AskLayer.Visibility = Visibility.Visible;
Fx.Once(AskLayer, UIElement.OpacityProperty, 0, 1, Fx.Base);
AskNo.Focus();
}
void HideAsk()
{
askYes = null;
AskLayer.Visibility = Visibility.Collapsed;
}
void Show(Grid page)
{
foreach (var p in new[] { InstallPage, FetchPage, HomePage, SavesPage, SetupPage, BuildPage }) p.Visibility = p == page ? Visibility.Visible : Visibility.Collapsed;
if (page != BuildPage && ShowLog.IsChecked == true) ShowLog.IsChecked = false;
// (nothing to wait for on these pages: the crest whole, every stone alight)
if (page == InstallPage || page == HomePage || page == SavesPage || page == SetupPage) stage.All(true);
if (shown == page) return;
shown = page;
Fx.Arrive(page);
}
// ---- start: install first, or straight to gathering ----
void Begin()
{
var dir = Install.InstalledDir;
try { var old = System.IO.Path.Combine(dir ?? Install.SelfDir, "TriforceSetup.old.exe"); if (File.Exists(old)) File.Delete(old); } catch (Exception) { }
if (autoBuild != null && Tools.Find() is { } auto)
{
Program.Log("auto-build (test) " + string.Join(" | ", autoBuild));
Run(auto, new List<string> { "--romfs", autoBuild[1], "--exefs", autoBuild[0], "--out", autoBuild[2], "--language", lang.Code });
return;
}
// (TRIFORCE_DEV=1: run in place, without installing, for testing)
if (Install.RunningInstalled || Environment.GetEnvironmentVariable("TRIFORCE_DEV") == "1")
{
Gather();
return;
}
if (dir != null)
{
// (installed already: this download becomes the installed Setup, which then carries on)
try
{
var exe = Install.Run(dir, Install.Get("Desktop") != "0", Install.Get("StartMenu") != "0");
Relaunch(exe, false);
return;
}
catch (Exception) { Gather(); return; }
}
InstallPath.Text = Install.DefaultDir;
Show(InstallPage);
InstallSpaceText();
stage.Gleam(500);
}
void InstallSpaceText()
{
try
{
var root = System.IO.Path.GetPathRoot(System.IO.Path.GetFullPath(InstallPath.Text))!;
var free = new DriveInfo(root).AvailableFreeSpace;
InstallSpace.Text = "Setup and its tools take about 2 GB. " + root + " has " + (free >> 30) + " GB free.";
InstallSpace.Foreground = Brush(free > (3L << 30) ? "TextDim" : "Bad");
}
catch (Exception) { InstallSpace.Text = "Setup and its tools take about 2 GB."; }
}
void DoInstall()
{
try
{
var dir = System.IO.Path.GetFullPath(InstallPath.Text.Trim());
var exe = Install.Run(dir, DesktopIcon.IsChecked == true, StartIcon.IsChecked == true);
Relaunch(exe, false);
}
catch (Exception e)
{
InstallSpace.Text = "Triforce could not be installed there: " + e.Message;
InstallSpace.Foreground = Brush("Bad");
}
}
void Relaunch(string exe, bool afterSelfUpdate)
{
var a = new List<string>();
if (updateFolder != null) { a.Add("--update"); a.Add("\"" + updateFolder + "\""); }
if (afterSelfUpdate) a.Add("--relaunched");
if (merge && updateFolder == null) a.Add("--merge");
Process.Start(new ProcessStartInfo(exe, string.Join(" ", a)) { UseShellExecute = false, WorkingDirectory = System.IO.Path.GetDirectoryName(exe)! });
fetch = null;
Window.Close();
}
// ---- gather: the update check, Setup's own update, the tools ----
void FetchState(string title, string note, string step)
{
FetchTitle.Text = title;
FetchNote.Text = note;
FetchStep.Text = step;
FetchNote.Foreground = Brush("Text");
}
/// The line and the large number: how far a download or an unpacking is (detail: "164 / 264 MB")
void FetchProgress(double f, string detail)
{
FetchBar.IsIndeterminate = false;
FetchBar.Value = f;
FetchNumber.Text = ((int)(f * 100)).ToString();
FetchNumberRow.Visibility = Visibility.Visible;
FetchPercent.Text = detail;
}
/// Work of unknown length (asking GitHub): light sweeps along the line, no number
void FetchUnknown(bool on)
{
FetchBar.IsIndeterminate = on;
if (!on) FetchBar.Value = 0;
FetchNumberRow.Visibility = Visibility.Hidden;
FetchPercent.Text = "";
}
/// Every start: ask GitHub what is newest (nothing downloaded yet), then the welcome-back page decides. The first start, with
/// no tools at all, downloads them straight away; --merge (after Setup replaced itself, or the game's own update offer) carries on.
async void Gather()
{
Show(FetchPage);
FetchRetry.Visibility = FetchSkip.Visibility = Visibility.Collapsed;
FetchCancel.Content = "Cancel";
FetchCancel.IsEnabled = true;
stage.All(false);
FetchUnknown(true);
FetchState("Gathering the stones", "Asking GitHub for the newest Triforce.", "Checking for updates");
fetch = new CancellationTokenSource();
var token = fetch.Token;
try
{
using var http = Http();
latest = await Release.Latest(http, token);
Program.Log("latest release " + latest.Tag + " (setup " + (latest.SetupUrl != null) + ", tools " + (latest.ToolsUrl != null) + "); this Setup " + Program.Version + ", tools " + (Tools.InstalledVersion ?? "none"));
stage.Set(Art.Emerald, true);
fetch = null;
// (the first start, with nothing to play yet: the tools come straight away. With a game here, the start page asks first)
var hasGame = Install.Get("GameFolder") is { } gf && GameExe(gf) != null;
if (Tools.InstalledVersion == null && !hasGame || merge) { await Merge(); return; }
ShowHome(null);
}
catch (Exception e)
{
fetch = null;
Program.Log("update check failed: " + e.GetType().Name + ": " + e.Message);
var cancelled = e is OperationCanceledException && token.IsCancellationRequested;
// (no answer, or no release yet: the start page all the same when there is something to play or tools to build with)
var game = Install.Get("GameFolder");
if (!cancelled && (Tools.InstalledVersion != null || game != null && GameExe(game) != null)) { ShowHome(e); return; }
Failed(e, cancelled);
}
}
static HttpClient Http()
{
var http = new HttpClient { Timeout = Timeout.InfiniteTimeSpan };
http.DefaultRequestHeaders.UserAgent.ParseAdd("TriforceSetup/" + Program.Version);
return http;
}
Exception? fetchFailure;
void Failed(Exception e, bool cancelled)
{
fetchFailure = cancelled ? null : e;
Show(FetchPage);
FetchUnknown(false);
FetchCancel.IsEnabled = true;
var offline = e is HttpRequestException || e is TaskCanceledException && !cancelled;
FetchTitle.Text = cancelled ? "Stopped" : offline ? "GitHub could not be reached" : "Something went wrong";
FetchNote.Text = cancelled ? "Nothing was changed." : offline ? "Check your internet connection, then try again." : e.Message;
FetchNote.Foreground = Brush(cancelled ? "Text" : "Bad");
FetchStep.Text = "";
FetchRetry.Visibility = Visibility.Visible;
FetchSkip.Visibility = Tools.Find() != null ? Visibility.Visible : Visibility.Collapsed;
FetchCancel.Content = "Close";
}
/// Update & merge: Setup itself first (it restarts and carries on), then the new tools, then the game folder built again with
/// them from the game files it keeps (saves and settings stay)
async Task Merge()
{
Show(FetchPage);
FetchRetry.Visibility = FetchSkip.Visibility = Visibility.Collapsed;
FetchCancel.Content = "Cancel";
stage.Set(Art.Sapphire, false);
stage.Set(Art.Ruby, false);
stage.Set(Art.Emerald, true);
fetch = new CancellationTokenSource();
var token = fetch.Token;
var release = latest!;
try
{
using var http = Http();
// 1. Setup itself
if (!relaunched && Program.Version != "dev" && release.Tag != Program.Version && release.SetupUrl != null)
{
FetchState("A new Setup is here", "Triforce Setup " + release.Tag + " replaces " + Program.Version + ". It restarts by itself and carries on.", "Downloading Setup " + release.Tag);
var dir = Install.InstalledDir ?? Install.SelfDir;
var fresh = System.IO.Path.Combine(dir, "TriforceSetup.new.exe");
FetchProgress(0, "");
await Release.Download(http, release.SetupUrl, fresh, release.SetupSize, (f, have) => Ui(() => FetchProgress(f, (have >> 10) + " KB")), token);
var self = System.IO.Path.Combine(dir, Program.SetupAsset);
var old = System.IO.Path.Combine(dir, "TriforceSetup.old.exe");
if (File.Exists(old)) File.Delete(old);
File.Move(self, old);
File.Move(fresh, self);
Program.Log("Setup updated to " + release.Tag + ", restarting");
merge = true;
Relaunch(self, true);
return;
}
stage.Set(Art.Sapphire, true);
// 2. the tools
if (Tools.InstalledVersion != release.Tag)
{
if (release.ToolsUrl == null) throw new InvalidOperationException("The release " + release.Tag + " has no " + Program.ToolsAsset + ".");
var have = Tools.InstalledVersion;
FetchState(have == null ? "Gathering the stones" : "Merging Triforce " + release.Tag,
have == null ? "Downloading the Triforce tools (" + (release.ToolsSize >> 20) + " MB), once. Updates come the same way."
: "Triforce " + release.Tag + " replaces " + have + ". Downloading its tools (" + (release.ToolsSize >> 20) + " MB).",
"Downloading the tools");
var cache = System.IO.Path.Combine(Install.InstalledDir ?? Install.SelfDir, "downloads");
Directory.CreateDirectory(cache);
var zip = System.IO.Path.Combine(cache, "Triforce-Tools-" + string.Concat(release.Tag.Where(c => char.IsLetterOrDigit(c) || c == '.' || c == '-')) + ".zip");
FetchProgress(0, "");
await Release.Download(http, release.ToolsUrl, zip, release.ToolsSize, (f, got) => Ui(() =>
{
FetchProgress(f, (got >> 20) + " / " + (release.ToolsSize >> 20) + " MB");
stage.Charge(Art.Ruby, f * 0.7);
}), token);
FetchStep.Text = "Unpacking the tools";
FetchCancel.IsEnabled = false;
FetchProgress(0, "");
await Task.Run(() => Tools.Unpack(zip, release.Tag, f => Ui(() => { FetchProgress(f, ""); stage.Charge(Art.Ruby, 0.7 + f * 0.3); })));
FetchCancel.IsEnabled = true;
try { File.Delete(zip); } catch (Exception) { }
Program.Log("tools " + release.Tag + " unpacked into " + Tools.Folder);
}
stage.Set(Art.Ruby, true);
fetch = null;
merge = false;
// 3. the game folder, built again (the game's offer names it; else the one Setup built last)
var folder = updateFolder ?? Install.Get("GameFolder");
if (folder != null && GameExe(folder) != null && BuiltVersion(folder) != Tools.InstalledVersion && Tools.Find() is { } tools)
{
OutPath.Text = folder;
BeginUpdate();
Run(tools, new List<string> { "--update", folder }, keepRows: true);
return;
}
// (nothing to build again: the start page, which now says "up to date" and offers Play)
if (folder != null && GameExe(folder) != null) ShowHome(null);
else ShowSetup();
}
catch (Exception e)
{
fetch = null;
Program.Log("update failed: " + e.GetType().Name + ": " + e.Message);
Failed(e, e is OperationCanceledException && token.IsCancellationRequested);
}
}
void Ui(Action a) => Window.Dispatcher.BeginInvoke(a);
static string? BuiltVersion(string folder) =>
ReadValue(System.IO.Path.Combine(folder, "triforce_version.txt"), "version") ?? ReadValue(System.IO.Path.Combine(folder, "hookshot_version.txt"), "version");
static bool HasGame => Install.Get("GameFolder") is { } g && GameExe(g) != null;
/// Play: the game starts when there is one (its settings are in its own options menu), else on to building one
void AfterHome()
{
var folder = Install.Get("GameFolder");
if (folder != null && GameExe(folder) != null) Play(folder);
else ShowSetup();
}
// ---- forge: choose the game ----
void ShowSetup()
{
if (OutPath.Text.Length == 0)
OutPath.Text = Install.Get("GameFolder") ?? System.IO.Path.Combine(Install.TestRoot ?? Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Games", "Triforce");
Show(SetupPage);
Banner();
Refresh();
}
/// The banner over the form: the game built before, out of date (Update) or ready (Play)
void Banner()
{
UpdateBanner.Visibility = Visibility.Collapsed;
var folder = Install.Get("GameFolder");
if (folder == null || GameExe(folder) == null) return;
var built = BuiltVersion(folder);
var tools = Tools.InstalledVersion;
UpdateBanner.Visibility = Visibility.Visible;
if (tools != null && built != null && built != tools)
{
UpdateText.Text = "Your game in " + folder + " is Triforce " + built + ". Version " + tools + " is ready: updating keeps your saves and settings.";
UpdateGameButton.Content = "Update game";
bannerAction = () =>
{
if (Tools.Find() is not { } t) return;
OutPath.Text = folder;
BeginUpdate();
Run(t, new List<string> { "--update", folder }, keepRows: true);
};
}
else
{
UpdateText.Text = "Your game is ready in " + folder + ".";
UpdateGameButton.Content = T(S.Play);
bannerAction = () => Play(folder);
}
}
static string? ReadValue(string file, string name)
{
try
{
foreach (var line in File.ReadAllLines(file))
if (line.StartsWith(name + "=")) return line.Substring(name.Length + 1).Trim();
}
catch (Exception) { }
return null;
}
/// (testing: --where) what Setup knows about the game, and the page a start would show
public static string Where()
{
var folder = Install.Get("GameFolder");
var exe = folder != null ? GameExe(folder) : null;
return "where: GameFolder=[" + (folder ?? "null") + "] exe=[" + (exe ?? "null") + "] built=[" + (folder != null ? BuiltVersion(folder) ?? "null" : "-") +
"] tools=[" + (Tools.InstalledVersion ?? "null") + "] toolsFolder=[" + Tools.Folder + "] installed=[" + (Install.InstalledDir ?? "null") +
"] runningInstalled=" + Install.RunningInstalled + " self=[" + Install.Self + "]";
}
static string? GameExe(string folder)
{
foreach (var n in new[] { "Triforce.exe", "hookshot.exe" })
{
var p = System.IO.Path.Combine(folder, n);
if (File.Exists(p)) return p;
}
return null;
}
void Play(string folder)
{
var exe = GameExe(folder);
if (exe == null) return;
if (!Install.Allowed(exe)) { Program.Log("not started (a test run starts only what is in its own folder): " + exe); return; }
// (Setup just asked about updates: the game's own offer, host/hos_update.c, would ask again)
var si = new ProcessStartInfo(exe) { UseShellExecute = false, WorkingDirectory = folder };
si.EnvironmentVariables["HOOKSHOT_NO_UPDATE_CHECK"] = "1";
Process.Start(si);
Program.Log("started the game: " + exe);
Window.Close();
}
void ApplyLanguage()
{
Subtitle.Text = T(S.Subtitle);
LanguageLabel.Label = T(S.LanguageLabel);
GameFilesLabel.Label = T(S.GameFiles);
UseNup.Content = T(S.Nup);
UseFolders.Content = T(S.Folders);
BrowseA.Content = BrowseB.Content = BrowseC.Content = BrowseD.Content = T(S.Browse);
SaveToLabel.Label = T(S.SaveTo);
BuildButton.Content = T(S.Build);
ShowLog.Content = T(ShowLog.IsChecked == true ? S.HideDetails : S.ShowDetails);
CancelButton.Content = T(S.Cancel);
BackButton.Content = T(S.Back);
OpenButton.Content = T(S.OpenFolder);
PlayButton.Content = T(S.Play);
foreach (var (id, text, _) in Stages) rows[id].SetText(T(text));
if (!sourceOk && !SourceGiven) Say(T(S.DropHint), "TextDim", null);
else CheckSource();
if (SetupPage.Visibility == Visibility.Visible) Banner();
Refresh();
}
void SourceKindChanged()
{
NupRow.Visibility = UseNup.IsChecked == true ? Visibility.Visible : Visibility.Collapsed;
FolderRows.Visibility = UseNup.IsChecked == true ? Visibility.Collapsed : Visibility.Visible;
PathsChanged();
}
void PathsChanged()
{
sourceOk = false;
checkDelay.Stop();
checkDelay.Start();
Refresh();
}
bool SourceGiven => UseNup.IsChecked == true ? File.Exists(NupPath.Text)
: Directory.Exists(RomfsPath.Text) && File.Exists(System.IO.Path.Combine(ExefsPath.Text, "main"));
void Refresh()
{
BuildButton.IsEnabled = sourceOk && OutPath.Text.Length > 2;
try
{
var root = System.IO.Path.GetPathRoot(System.IO.Path.GetFullPath(OutPath.Text))!;
var free = new DriveInfo(root).AvailableFreeSpace;
SpaceText.Text = T(S.Needs) + " " + string.Format(T(S.Free), root, free >> 30);
SpaceText.Foreground = Brush(free >= NeededBytes ? "TextDim" : "Bad");
}
catch (Exception) { SpaceText.Text = T(S.Needs); }
}
async void CheckSource()
{
if (!SourceGiven) { Say(T(S.DropHint), "TextDim", null); return; }
var serial = ++checkSerial;
Say(T(S.Checking), "TextDim", "TextFaint");
var tools = Tools.Find();
if (tools == null) { Say(T(S.ToolsMissing), "Bad", "Bad"); return; }
var args = new List<string> { "--check" };
args.AddRange(UseNup.IsChecked == true ? new[] { "--nup", NupPath.Text } : new[] { "--exefs", ExefsPath.Text });
var (ok, text) = await Runner.Check(tools, args);
if (serial != checkSerial) return;
sourceOk = ok;
Say(ok ? T(S.VersionOk) : text.StartsWith("This is build") ? T(S.VersionBad) : text, ok ? "Good" : "Bad", ok ? "Good" : "Bad");
Refresh();
}
/// The line under the game files: what the check found, with a diamond in its colour (none for the plain hint)
void Say(string text, string brush, string? mark)
{
CheckText.Text = text;
CheckText.Foreground = Brush(brush);
CheckMark.Visibility = mark == null ? Visibility.Collapsed : Visibility.Visible;
if (mark != null) CheckMark.Fill = Brush(mark);
}
void Dropped(object sender, DragEventArgs e)
{
if (SetupPage.Visibility != Visibility.Visible || e.Data.GetData(DataFormats.FileDrop) is not string[] { Length: > 0 } paths) return;
foreach (var p in paths)
{
var name = System.IO.Path.GetFileName(p).ToLowerInvariant();
if (name.EndsWith(".nup")) { UseNup.IsChecked = true; NupPath.Text = p; }
else if (name == "romfs") { UseFolders.IsChecked = true; RomfsPath.Text = p; }
else if (name == "exefs") { UseFolders.IsChecked = true; ExefsPath.Text = p; }
else if (Directory.Exists(System.IO.Path.Combine(p, "romfs")) && Directory.Exists(System.IO.Path.Combine(p, "exefs")))
{
UseFolders.IsChecked = true;
RomfsPath.Text = System.IO.Path.Combine(p, "romfs");
ExefsPath.Text = System.IO.Path.Combine(p, "exefs");
}
}
}
void BrowseNup()
{
var d = new OpenFileDialog { Filter = "Game file (*.nup)|*.nup", Title = "Choose your game file" };
if (d.ShowDialog(Window) == true) NupPath.Text = d.FileName;
}
// ---- the build ----
void StartBuild()
{
var tools = Tools.Find();
if (tools == null) return;
var args = new List<string>();
if (UseNup.IsChecked == true) args.AddRange(new[] { "--nup", NupPath.Text });
else args.AddRange(new[] { "--romfs", RomfsPath.Text, "--exefs", ExefsPath.Text });
args.AddRange(new[] { "--out", OutPath.Text, "--language", lang.Code });
Run(tools, args);
}
void BeginUpdate()
{
foreach (var r in rows.Values) r.Reset();
Log.Clear();
BuildTitle.Text = T(S.Updating);
BuildTitle.Foreground = Brush("TextHi");
BuildNote.Text = "";
Show(BuildPage);
SetButtons(cancel: true);
}
void Run(Tools tools, List<string> args, bool keepRows = false)
{
if (!keepRows) BuildTitle.Text = T(S.Building);
BuildTitle.Foreground = Brush("TextHi");
foreach (var r in rows.Values) r.Reset();
if (!keepRows) Log.Clear();
current = null;
finished = "";
BuildEyebrow.Label = "III · Forge";
BuildNote.Foreground = Brush("Text");
Show(BuildPage);
stage.All(false);
SetButtons(cancel: true);
elapsed.Restart();
clock.Start();
Program.Log("build: make_game.py " + string.Join(" ", args) + " (tools " + tools.Root + ")");
runner = new Runner(tools, args);
ShowClock();
runner.Line += l => Ui(() => Line(l));
runner.Finished += failure => Ui(() => Ended(failure));
runner.Start();
}
void Line(string line)
{
if (line.StartsWith("@@stage "))
{
var id = line.Split(' ')[1];
if (current != null && rows.TryGetValue(current, out var was)) was.Done();
current = id;
if (rows.TryGetValue(id, out var row)) row.Begin();
}
else if (line.StartsWith("@@progress "))
{
if (current != null && rows.TryGetValue(current, out var row) &&
double.TryParse(line.Substring(11), System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var f))
row.Progress(f);
}
else if (line.StartsWith("@@done ")) finished = line.Substring(7);
if (!line.StartsWith("@@progress"))
{
Log.AppendText(line + "\n");
if (Log.LineCount > 4000) Log.Text = Log.Text.Substring(Log.Text.Length / 2);
if (ShowLog.IsChecked == true) Log.ScrollToEnd();
}
}
void Ended(string? failure)
{
clock.Stop();
elapsed.Stop();
runner = null;
Program.Log("build ended: " + (finished.Length > 0 ? "done, " + finished : failure ?? "failed") + " after " + Span(elapsed.Elapsed));
if (AskLayer.Visibility == Visibility.Visible) HideAsk(); // (the question was about a build that is over now)
if (finished.Length > 0)
{
foreach (var r in rows.Values) r.Done();
stage.All(true);
stage.Gleam(500);
BuildEyebrow.Label = "IV · Play";
BuildTitle.Text = T(S.Ready);
BuildNote.Text = finished + " · " + T(S.BuiltIn) + " " + Span(elapsed.Elapsed);
Install.Set("GameFolder", finished);
SetButtons(done: true);
return;
}
BuildTitle.Text = T(failure == "cancelled" ? S.Cancelled : S.Stopped);
BuildNote.Text = failure == "cancelled" ? T(S.CancelledNote) : failure ?? "";
BuildNote.Foreground = Brush(failure == "cancelled" ? "Text" : "Bad");
if (current != null && rows.TryGetValue(current, out var row)) row.Stopped();
SetButtons(back: true);
}
void ShowClock()
{
if (runner != null) BuildNote.Text = T(S.Patience) + " " + T(S.Elapsed) + ": " + Span(elapsed.Elapsed);
}
static string Span(TimeSpan t) => t.TotalHours >= 1 ? (int)t.TotalHours + " h " + t.Minutes + " min" : t.TotalMinutes >= 1 ? t.Minutes + " min" : t.Seconds + " s";
void SetButtons(bool cancel = false, bool done = false, bool back = false)
{
CancelButton.Visibility = cancel ? Visibility.Visible : Visibility.Collapsed;
PlayButton.Visibility = OpenButton.Visibility = done ? Visibility.Visible : Visibility.Collapsed;
BackButton.Visibility = back ? Visibility.Visible : Visibility.Collapsed;
}
/// The build's own words, for those who want them: they take the crest's side of the window while shown
void LogToggled()
{
var show = ShowLog.IsChecked == true;
Log.Visibility = show ? Visibility.Visible : Visibility.Collapsed;
ShowLog.Content = T(show ? S.HideDetails : S.ShowDetails);
Grid.SetColumnSpan(BuildPage, show ? 2 : 1);
StageColumn.Width = new GridLength(show ? 390 : 540);
stage.Away(show);
if (show) Log.ScrollToEnd();
}
/// One step of the build, on a rail down the page: a diamond (hollow until it starts, bright while it runs, gold when done),
/// its name, and the progress line while it has progress. Its stone on the crest fills with light as it runs and lights when done.
sealed class StageRow
{
public readonly Grid Root = new() { MinHeight = 46 };
readonly Shell shell;
readonly int stone;
readonly Rectangle mark = new() { Width = 9, Height = 9, StrokeThickness = 1.2, RenderTransformOrigin = new Point(0.5, 0.5), RenderTransform = new RotateTransform(45) };
readonly Rectangle ring = new() { Width = 9, Height = 9, StrokeThickness = 1, RenderTransformOrigin = new Point(0.5, 0.5), Opacity = 0, IsHitTestVisible = false };
readonly ScaleTransform ringGrow = new(1, 1);
readonly TextBlock name = new() { VerticalAlignment = VerticalAlignment.Top, FontSize = 14.5, Margin = new Thickness(0, 0, 0, 0) };
readonly TextBlock percent = new() { HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Top, FontSize = 12.5, Margin = new Thickness(0, 1, 0, 0) };
readonly ProgressLine bar = new() { Margin = new Thickness(0, 2, 0, 0), Visibility = Visibility.Collapsed, VerticalAlignment = VerticalAlignment.Top };
public StageRow(Shell shell, string text, int stone, bool last)
{
this.shell = shell;
this.stone = stone;
Root.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(30) });
Root.ColumnDefinitions.Add(new ColumnDefinition());
Root.RowDefinitions.Add(new RowDefinition { Height = new GridLength(21) });
Root.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
if (!last)
{
// (the rail to the next step)
var rail = new Rectangle { Width = 1, Fill = shell.Brush("Line"), HorizontalAlignment = HorizontalAlignment.Left, Margin = new Thickness(5, 19, 0, -3) };
Grid.SetRowSpan(rail, 2);
Root.Children.Add(rail);
}
ring.RenderTransform = new TransformGroup { Children = { new RotateTransform(45), ringGrow } };
ring.Stroke = shell.Brush("Gold300");
foreach (var m in new[] { ring, mark })
{
m.HorizontalAlignment = HorizontalAlignment.Left;
m.VerticalAlignment = VerticalAlignment.Top;
m.Margin = new Thickness(1, 6, 0, 0);
Root.Children.Add(m);
}
name.Text = text;
percent.Foreground = shell.Brush("Gold");
Grid.SetColumn(name, 1);
Grid.SetColumn(percent, 1);
Grid.SetRow(bar, 1);
Grid.SetColumn(bar, 1);
Root.Children.Add(name);
Root.Children.Add(percent);
Root.Children.Add(bar);
Reset();
}
public void SetText(string text) => name.Text = text;
void Mark(string? fill, string stroke, bool glow)
{
mark.Fill = fill == null ? Brushes.Transparent : shell.Brush(fill);
mark.Stroke = shell.Brush(stroke);
mark.Effect = glow ? new System.Windows.Media.Effects.DropShadowEffect { Color = Fx.Rgb(Fx.Gold500), BlurRadius = 10, ShadowDepth = 0, Opacity = 0.9 } : null;
}
void Pulse(bool on)
{
ring.BeginAnimation(UIElement.OpacityProperty, null);
ringGrow.BeginAnimation(ScaleTransform.ScaleXProperty, null);
ringGrow.BeginAnimation(ScaleTransform.ScaleYProperty, null);
ring.Opacity = 0;
if (!on || Fx.Still) return;
var time = TimeSpan.FromMilliseconds(1800);
var grow = new DoubleAnimation(1, 2.6, time) { RepeatBehavior = RepeatBehavior.Forever, EasingFunction = Fx.Out };
ringGrow.BeginAnimation(ScaleTransform.ScaleXProperty, grow);
ringGrow.BeginAnimation(ScaleTransform.ScaleYProperty, grow);
ring.BeginAnimation(UIElement.OpacityProperty, new DoubleAnimation(0.7, 0, time) { RepeatBehavior = RepeatBehavior.Forever });
}
public void Reset()
{
Mark(null, "TextFaint", false);
Pulse(false);
name.Foreground = shell.Brush("TextFaint");
percent.Text = "";
bar.Visibility = Visibility.Collapsed;
bar.Value = 0;
}
public void Begin()
{
Mark("Gold300", "Gold300", true);
Pulse(true);
name.Foreground = shell.Brush("TextHi");
if (stone >= 0) shell.stage.Charge(stone, 0);
}
public void Progress(double f)
{
bar.Visibility = Visibility.Visible;
bar.Value = f;
percent.Text = (int)(f * 100) + "%";
if (stone >= 0) shell.stage.Charge(stone, f);
}
public void Done()
{
Mark("Gold", "Gold", false);
Pulse(false);
name.Foreground = shell.Brush("TextDim");
percent.Text = "";
bar.Visibility = Visibility.Collapsed;
if (stone >= 0) shell.stage.Set(stone, true);
}
public void Stopped()
{
Mark(null, "Bad", false);
Pulse(false);
name.Foreground = shell.Brush("Bad");
bar.Visibility = Visibility.Collapsed;
percent.Text = "";
if (stone >= 0) shell.stage.Set(stone, false);
}
}
}

271
setup/Stage.cs Normal file
View File

@@ -0,0 +1,271 @@
// The hall and the relic: everything behind and beside the pages. A warm dark room with one soft light, and in it the crest,
// whose three stones are lit or unlit as the work goes (gathering, building) and all alight when there is nothing to wait for.
// Built in code into Main.xaml's StageHost, at fixed places: the window is one composed picture (Shell fits it to small screens).
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Shapes;
namespace TriforceSetup;
sealed class Stage
{
public const double WindowWidth = 1060, WindowHeight = 640, Column = 430;
const double CrestWidth = 300, CrestTop = 150;
static readonly double CrestHeight = CrestWidth * 468 / 512;
static readonly double MidX = WindowWidth - Column / 2, MidY = CrestTop + CrestHeight / 2;
// (the gleam's band: its size, its lean, and how far left and right it must go to be wholly off the crest's box)
const double BandWidth = CrestWidth * 0.24, BandLean = 24;
static readonly double BandHeight = CrestHeight * 1.8;
static readonly double BandReach = (BandWidth * Math.Cos(BandLean * Math.PI / 180) + BandHeight * Math.Sin(BandLean * Math.PI / 180)) / 2;
static readonly double BandFrom = -BandReach - BandWidth / 2, BandTo = CrestWidth + BandReach - BandWidth / 2;
public readonly Canvas Root = new() { Width = WindowWidth, Height = WindowHeight, IsHitTestVisible = false, ClipToBounds = true };
readonly Canvas relic = new() { Width = WindowWidth, Height = WindowHeight };
readonly Image[] stones = new Image[3];
readonly Ellipse[] rest = new Ellipse[3], bloom = new Ellipse[3];
readonly bool[] lit = new bool[3];
readonly Rectangle gleam;
readonly TranslateTransform gleamMove = new();
readonly RotateTransform marksTurn = new();
readonly Ellipse halo;
static RadialGradientBrush Radial(params (Color c, double at)[] stops)
{
var b = new RadialGradientBrush();
foreach (var (c, at) in stops) b.GradientStops.Add(new GradientStop(c, at));
b.Freeze();
return b;
}
static T Place<T>(T e, double x, double y) where T : UIElement
{
Canvas.SetLeft(e, x);
Canvas.SetTop(e, y);
return e;
}
public Stage()
{
// ---- the hall: light from above, the halo, the lattice in it, the dark corners, grain ----
var top = new LinearGradientBrush(Fx.Rgb(0xFFECAA, 0.045), Fx.Rgb(0xFFECAA, 0), 90);
top.Freeze();
Root.Children.Add(Place(new Rectangle { Width = WindowWidth, Height = WindowHeight * 0.45, Fill = top }, 0, 0));
const double reach = CrestWidth * 1.2;
halo = Place(new Ellipse
{
Width = reach * 2, Height = reach * 2,
Fill = Radial((Fx.Rgb(Fx.Gold500, 0.24), 0), (Fx.Rgb(Fx.Gold500, 0.075), 0.45), (Fx.Rgb(Fx.Gold500, 0), 1)),
}, MidX - reach, MidY - reach);
Root.Children.Add(halo);
Root.Children.Add(Place(new Rectangle
{
Width = reach * 2, Height = reach * 2, Fill = Art.Lattice(56, Fx.Rgb(Fx.Gold500, 0.06)),
OpacityMask = Radial((Colors.White, 0), (Color.FromArgb(120, 255, 255, 255), 0.5), (Colors.Transparent, 0.95)),
}, MidX - reach, MidY - reach));
// (an arc over the crest: a fine ring and, outside it, a ring of small marks that turns too slowly to notice, like the
// dial of an instrument. Both fade out on their way down, before they would reach the name)
// (the fade is pinned to the rings' box in absolute units: in relative units it maps to the bounds of what is drawn, and
// the turning ring's bounds grow and shrink with its angle, which moved the fade up and down by some 40 px as it turned)
const double dial = CrestWidth * 0.72;
var arc = new LinearGradientBrush { MappingMode = BrushMappingMode.Absolute, StartPoint = new Point(0, 0), EndPoint = new Point(0, dial * 2) };
arc.GradientStops.Add(new GradientStop(Colors.White, 0));
arc.GradientStops.Add(new GradientStop(Colors.White, 0.42));
arc.GradientStops.Add(new GradientStop(Colors.Transparent, 0.74));
arc.Freeze();
var rings = Place(new Grid { Width = dial * 2, Height = dial * 2, OpacityMask = arc }, MidX - dial, MidY - dial + CrestHeight * 0.06);
Root.Children.Add(rings);
foreach (var (radius, alpha, marks, seconds) in new[] { (CrestWidth * 0.66, 0.17, false, 0.0), (CrestWidth * 0.705, 0.28, true, 420.0) })
{
var ring = new Ellipse
{
Width = radius * 2, Height = radius * 2, Stroke = Fx.Paint(Fx.Gold500, alpha), StrokeThickness = marks ? 3 : 1,
RenderTransformOrigin = new Point(0.5, 0.5), HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center,
};
if (marks)
{
// (a short stroke, a long gap; 120 of them round the ring)
var around = 2 * Math.PI * (radius - 1.5) / 3;
ring.StrokeDashArray = new DoubleCollection { 1.0 / 3, around / 120 - 1.0 / 3 };
var turn = marksTurn;
ring.RenderTransform = turn;
if (!Fx.Still) turn.BeginAnimation(RotateTransform.AngleProperty, new DoubleAnimation(0, 360, TimeSpan.FromSeconds(seconds)) { RepeatBehavior = RepeatBehavior.Forever });
}
rings.Children.Add(ring);
}
var corners = new RadialGradientBrush { Center = new Point(0.5, 0.5), GradientOrigin = new Point(0.5, 0.5), RadiusX = 0.78, RadiusY = 0.78 };
corners.GradientStops.Add(new GradientStop(Fx.Rgb(0, 0), 0.55));
corners.GradientStops.Add(new GradientStop(Fx.Rgb(0, 0.55), 1));
corners.Freeze();
Root.Children.Add(Place(new Rectangle { Width = WindowWidth, Height = WindowHeight, Fill = corners }, 0, 0));
Root.Children.Add(Place(new Rectangle { Width = WindowWidth, Height = WindowHeight, Fill = Art.Grain(), Opacity = 0.55 }, 0, 0));
// ---- the relic: the crest on its light, its name under it ----
Root.Children.Add(relic);
double left = MidX - CrestWidth / 2;
relic.Children.Add(Place(new Ellipse
{
Width = CrestWidth * 0.86, Height = 30,
Fill = Radial((Fx.Rgb(Fx.Gold500, 0.26), 0), (Fx.Rgb(Fx.Gold500, 0.08), 0.55), (Fx.Rgb(Fx.Gold500, 0), 1)),
}, MidX - CrestWidth * 0.43, CrestTop + CrestHeight - 13));
var crest = Place(new Grid { Width = CrestWidth, Height = CrestHeight }, left, CrestTop);
relic.Children.Add(crest);
Image Layer(ImageSource s) => new() { Source = s, Stretch = Stretch.Fill };
RenderOptions.SetBitmapScalingMode(crest, BitmapScalingMode.HighQuality);
crest.Children.Add(Layer(Art.Dim));
for (var s = 0; s < 3; s++)
{
stones[s] = Layer(Art.Stones[s]);
stones[s].Opacity = 0;
crest.Children.Add(stones[s]);
}
// (the light each stone throws once lit, and the bloom when it lights)
var lights = new Canvas { Width = CrestWidth, Height = CrestHeight };
crest.Children.Add(lights);
for (var s = 0; s < 3; s++)
{
double cx = Art.Centre[s].X * CrestWidth, cy = Art.Centre[s].Y * CrestHeight;
const double r = CrestWidth * 0.26;
rest[s] = Place(new Ellipse
{
Width = r * 2, Height = r * 2, Opacity = 0,
Fill = Radial((Fx.Rgb(Art.Glow[s], 0.30), 0), (Fx.Rgb(Art.Glow[s], 0.09), 0.5), (Fx.Rgb(Art.Glow[s], 0), 1)),
}, cx - r, cy - r);
const double b = CrestWidth * 0.5;
bloom[s] = Place(new Ellipse
{
Width = b * 2, Height = b * 2, Opacity = 0, RenderTransformOrigin = new Point(0.5, 0.5), RenderTransform = new ScaleTransform(0.5, 0.5),
Fill = Radial((Fx.Rgb(Art.Glow[s], 0.75), 0), (Fx.Rgb(Art.Glow[s], 0.22), 0.4), (Fx.Rgb(Art.Glow[s], 0), 1)),
}, cx - b, cy - b);
lights.Children.Add(rest[s]);
lights.Children.Add(bloom[s]);
}
// (the gleam: a band of light that crosses the gold, kept to the crest's own shape)
var band = new LinearGradientBrush { StartPoint = new Point(0, 0), EndPoint = new Point(1, 0) };
band.GradientStops.Add(new GradientStop(Fx.Rgb(Fx.Gold100, 0), 0));
band.GradientStops.Add(new GradientStop(Fx.Rgb(Fx.Gold100, 0.9), 0.5));
band.GradientStops.Add(new GradientStop(Fx.Rgb(Fx.Gold100, 0), 1));
band.Freeze();
// The layer has the crest's own box and its mask is pinned to that box in absolute units. (A mask left in relative
// units maps to the bounds of what is drawn, here the band itself: the crest's shape was squeezed into the band and
// travelled with it, on and off the crest. And a band taller than a Grid's cell is cut to the cell: hence a Canvas.)
gleam = Place(new Rectangle
{
Width = BandWidth, Height = BandHeight, Fill = band, RenderTransformOrigin = new Point(0.5, 0.5), Opacity = 0,
RenderTransform = new TransformGroup { Children = { new RotateTransform(BandLean), gleamMove } },
}, 0, (CrestHeight - BandHeight) / 2);
var shine = new Canvas
{
Width = CrestWidth, Height = CrestHeight, ClipToBounds = true,
OpacityMask = new ImageBrush(Art.Shine) { Stretch = Stretch.Fill, ViewportUnits = BrushMappingMode.Absolute, Viewport = new Rect(0, 0, CrestWidth, CrestHeight) },
};
shine.Children.Add(gleam);
crest.Children.Add(shine);
// (the name: gold capitals, wide apart, and a fine rule with a diamond)
var metal = new LinearGradientBrush { StartPoint = new Point(0, 0), EndPoint = new Point(0, 1) };
metal.GradientStops.Add(new GradientStop(Fx.Rgb(0xFFF1B8), 0.12));
metal.GradientStops.Add(new GradientStop(Fx.Rgb(0xE8B840), 0.46));
metal.GradientStops.Add(new GradientStop(Fx.Rgb(0xB57E1C), 0.60));
metal.GradientStops.Add(new GradientStop(Fx.Rgb(0xF3CF6A), 0.92));
metal.Freeze();
var name = new StackPanel { Width = Column };
var word = new Caps
{
Label = "Triforce", Gaps = 5, FontFamily = new FontFamily("Palatino Linotype, Book Antiqua, Georgia"), FontWeight = FontWeights.Bold, FontSize = 25,
Foreground = metal, HorizontalAlignment = HorizontalAlignment.Center,
Effect = new DropShadowEffect { Color = Colors.Black, BlurRadius = 6, ShadowDepth = 2, Direction = 270, Opacity = 0.8 },
};
TextOptions.SetTextFormattingMode(word, TextFormattingMode.Ideal);
name.Children.Add(word);
var rule = new Grid { Width = 220, Height = 12, Margin = new Thickness(0, 12, 0, 0) };
rule.ColumnDefinitions.Add(new ColumnDefinition());
rule.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
rule.ColumnDefinitions.Add(new ColumnDefinition());
var fadeIn = new LinearGradientBrush(Fx.Rgb(Fx.Gold500, 0), Fx.Rgb(Fx.Gold500, 0.55), 0);
var fadeOut = new LinearGradientBrush(Fx.Rgb(Fx.Gold500, 0.55), Fx.Rgb(Fx.Gold500, 0), 0);
var l = new Rectangle { Height = 1, Fill = fadeIn, VerticalAlignment = VerticalAlignment.Center };
var d = new Rectangle { Width = 5, Height = 5, Fill = Fx.Paint(Fx.Gold500), Margin = new Thickness(9, 0, 9, 0), RenderTransformOrigin = new Point(0.5, 0.5), RenderTransform = new RotateTransform(45), VerticalAlignment = VerticalAlignment.Center };
var rr = new Rectangle { Height = 1, Fill = fadeOut, VerticalAlignment = VerticalAlignment.Center };
Grid.SetColumn(d, 1);
Grid.SetColumn(rr, 2);
rule.Children.Add(l); rule.Children.Add(d); rule.Children.Add(rr);
name.Children.Add(rule);
relic.Children.Add(Place(name, WindowWidth - Column, CrestTop + CrestHeight + 30));
relic.Children.Add(Place(new Motes { Width = Column + 40, Height = WindowHeight - 110 }, WindowWidth - Column - 40, 70));
Fx.Breathe(halo, UIElement.OpacityProperty, 0.80, 1.0, 6000);
for (var s = 0; s < 3; s++) Set(s, true, quiet: true);
}
/// A stone lit or put out. Lighting it blooms once (unless quiet: the page simply shows it lit)
public void Set(int s, bool on, bool quiet = false)
{
var was = lit[s];
lit[s] = on;
Fx.To(stones[s], UIElement.OpacityProperty, on ? 1 : 0, quiet ? 0 : on ? 600 : Fx.Slow);
if (on) Fx.Breathe(rest[s], UIElement.OpacityProperty, 0.6, 1.0, 4500, s * 1500);
else Fx.To(rest[s], UIElement.OpacityProperty, 0, quiet ? 0 : Fx.Slow);
if (on && !was && !quiet && !Fx.Still)
{
var grow = (ScaleTransform)bloom[s].RenderTransform;
Fx.Once(grow, ScaleTransform.ScaleXProperty, 0.45, 1.0, 900);
Fx.Once(grow, ScaleTransform.ScaleYProperty, 0.45, 1.0, 900);
Fx.Once(bloom[s], UIElement.OpacityProperty, 0.75, 0, 900, 0, Fx.InOut);
}
}
public void All(bool on, bool quiet = false)
{
for (var s = 0; s < 3; s++) Set(s, on, quiet);
}
public bool Lit(int s) => lit[s];
/// A stone filling with light while its step runs (0..1): not lit yet, but on its way
public void Charge(int s, double f)
{
if (lit[s]) return;
f = Math.Max(0, Math.Min(1, f));
Fx.To(stones[s], UIElement.OpacityProperty, 0.10 + 0.50 * f, 300);
Fx.To(rest[s], UIElement.OpacityProperty, 0.15 + 0.35 * f, 300);
}
/// The band of light across the gold: when a page arrives with everything in order, and when the work is done
public void Gleam(int delay = 0)
{
if (Fx.Still) return;
Fx.Once(gleamMove, TranslateTransform.XProperty, BandFrom, BandTo, 1100, delay, Fx.InOut);
var show = new DoubleAnimationUsingKeyFrames { BeginTime = TimeSpan.FromMilliseconds(delay) };
show.KeyFrames.Add(new DiscreteDoubleKeyFrame(1, KeyTime.FromTimeSpan(TimeSpan.Zero)));
show.KeyFrames.Add(new DiscreteDoubleKeyFrame(0, KeyTime.FromTimeSpan(TimeSpan.FromMilliseconds(1100))));
gleam.BeginAnimation(UIElement.OpacityProperty, show);
}
/// (for still pictures: the band held at a place on its way, 0 = about to enter, 1 = just gone; below 0 puts it away)
public void GleamAt(double f)
{
gleam.BeginAnimation(UIElement.OpacityProperty, null);
gleamMove.BeginAnimation(TranslateTransform.XProperty, null);
gleam.Opacity = f < 0 ? 0 : 1;
gleamMove.X = BandFrom + (BandTo - BandFrom) * Math.Max(0, f);
}
/// (for still pictures: the ring of marks turned to an angle, to see that the arc's fade stays where it is)
public void TurnMarks(double angle)
{
marksTurn.BeginAnimation(RotateTransform.AngleProperty, null);
marksTurn.Angle = angle;
}
/// The relic steps back when something needs the whole width (the build's details)
public void Away(bool away) => Fx.To(relic, UIElement.OpacityProperty, away ? 0 : 1, Fx.Base);
}

180
setup/Strings.cs Normal file
View File

@@ -0,0 +1,180 @@
using System.Globalization;
using System;
using System.Linq;
namespace TriforceSetup;
/// One of the game's languages: its code in language.txt, its own name, and the app's text in it.
sealed class Language
{
public readonly string Code, Name;
public readonly string[] Text;
public Language(string code, string name, string[] text) { Code = code; Name = name; Text = text; }
public override string ToString() => Name;
}
enum S
{
Subtitle, GameFiles, Nup, Folders, DropHint, SaveTo, Build, Browse, Needs, Free, Checking, VersionOk, VersionBad, ToolsMissing, PythonMissing,
Building, Patience, Elapsed, Read, Lift, Compile, Finish, ShowDetails, HideDetails, Cancel, Back, OpenFolder, Play, Ready, BuiltIn,
Stopped, Cancelled, CancelledNote, CloseQuestion, LanguageLabel, StopClose, KeepBuilding,
// (the update, English only for now: Strings.Text falls back to it)
Download, Updating, UpdateFailed,
}
static class Strings
{
static readonly string[] En =
{
"Turns your own copy of Ocarina of Time into a game folder you can start on PC.", "Game files", ".nup file", "romfs and exefs",
"You can also drop a file or folder onto this window.", "Save the game to", "Build", "Browse", "Takes about 45 minutes and needs 60 GB.",
"{0} has {1} GB free.", "Checking the game version...", "This is the version Triforce supports.", "This version isn't supported. Triforce needs build e0f3ccfa.",
"The Triforce tools were not found next to this app.", "Python was not found.",
"Building", "This takes a while, and your PC stays usable.", "Elapsed", "Reading your game files", "Translating the game to PC code", "Compiling",
"Putting the game folder together", "Show details", "Hide details", "Cancel", "Back", "Open folder", "Play", "Your game is ready", "built in",
"The build stopped", "Build cancelled", "You can start again from the same folder.", "Stop the build and close?", "Language", "Stop and close", "Keep building",
"Downloading the new version", "Updating your game", "The update could not be downloaded",
};
static readonly string[] Fr =
{
"Transforme votre copie d'Ocarina of Time en un dossier de jeu à lancer sur PC.", "Fichiers du jeu", "Fichier .nup", "romfs et exefs",
"Vous pouvez aussi déposer un fichier ou un dossier sur cette fenêtre.", "Enregistrer le jeu dans", "Créer", "Parcourir", "Prend environ 45 minutes et nécessite 60 Go.",
"{0} : {1} Go libres.", "Vérification de la version du jeu...", "Cette version est prise en charge par Triforce.", "Cette version n'est pas prise en charge. Triforce a besoin de la version e0f3ccfa.",
"Les outils Triforce sont introuvables à côté de cette application.", "Python est introuvable.",
"Création en cours", "Cela prend du temps, et votre PC reste utilisable.", "Temps écoulé", "Lecture de vos fichiers de jeu", "Traduction du jeu en code PC", "Compilation",
"Assemblage du dossier du jeu", "Afficher les détails", "Masquer les détails", "Annuler", "Retour", "Ouvrir le dossier", "Jouer", "Votre jeu est prêt", "créé en",
"La création s'est arrêtée", "Création annulée", "Vous pouvez recommencer depuis le même dossier.", "Arrêter la création et fermer ?", "Langue", "Arrêter et fermer", "Continuer",
};
static readonly string[] De =
{
"Macht aus deiner eigenen Kopie von Ocarina of Time einen Spielordner für den PC.", "Spieldateien", ".nup-Datei", "romfs und exefs",
"Du kannst auch eine Datei oder einen Ordner auf dieses Fenster ziehen.", "Spiel speichern unter", "Erstellen", "Durchsuchen", "Dauert etwa 45 Minuten und benötigt 60 GB.",
"{0} hat {1} GB frei.", "Spielversion wird geprüft...", "Diese Version wird von Triforce unterstützt.", "Diese Version wird nicht unterstützt. Triforce benötigt Build e0f3ccfa.",
"Die Triforce-Werkzeuge wurden neben dieser App nicht gefunden.", "Python wurde nicht gefunden.",
"Wird erstellt", "Das dauert eine Weile, dein PC bleibt nutzbar.", "Vergangen", "Spieldateien werden gelesen", "Spiel wird in PC-Code übersetzt", "Kompilieren",
"Spielordner wird zusammengestellt", "Details anzeigen", "Details ausblenden", "Abbrechen", "Zurück", "Ordner öffnen", "Spielen", "Dein Spiel ist fertig", "erstellt in",
"Die Erstellung wurde angehalten", "Erstellung abgebrochen", "Du kannst im selben Ordner neu beginnen.", "Erstellung beenden und schließen?", "Sprache", "Beenden und schließen", "Weiter erstellen",
};
static readonly string[] It =
{
"Trasforma la tua copia di Ocarina of Time in una cartella di gioco da avviare su PC.", "File di gioco", "File .nup", "romfs ed exefs",
"Puoi anche trascinare un file o una cartella su questa finestra.", "Salva il gioco in", "Crea", "Sfoglia", "Richiede circa 45 minuti e 60 GB.",
"{0} ha {1} GB liberi.", "Controllo della versione del gioco...", "Questa versione è supportata da Triforce.", "Questa versione non è supportata. Triforce richiede la build e0f3ccfa.",
"Gli strumenti di Triforce non sono stati trovati accanto a questa app.", "Python non è stato trovato.",
"Creazione in corso", "Ci vuole un po', e il PC resta utilizzabile.", "Trascorso", "Lettura dei file di gioco", "Traduzione del gioco in codice PC", "Compilazione",
"Assemblaggio della cartella di gioco", "Mostra dettagli", "Nascondi dettagli", "Annulla", "Indietro", "Apri cartella", "Gioca", "Il tuo gioco è pronto", "creato in",
"La creazione si è interrotta", "Creazione annullata", "Puoi ricominciare dalla stessa cartella.", "Interrompere la creazione e chiudere?", "Lingua", "Interrompi e chiudi", "Continua",
};
static readonly string[] Es =
{
"Convierte tu copia de Ocarina of Time en una carpeta de juego para iniciar en PC.", "Archivos del juego", "Archivo .nup", "romfs y exefs",
"También puedes soltar un archivo o una carpeta en esta ventana.", "Guardar el juego en", "Crear", "Examinar", "Tarda unos 45 minutos y necesita 60 GB.",
"{0} tiene {1} GB libres.", "Comprobando la versión del juego...", "Triforce admite esta versión.", "Esta versión no es compatible. Triforce necesita la build e0f3ccfa.",
"No se encontraron las herramientas de Triforce junto a esta aplicación.", "No se encontró Python.",
"Creando", "Tarda un rato, y tu PC sigue siendo utilizable.", "Transcurrido", "Leyendo tus archivos del juego", "Traduciendo el juego a código de PC", "Compilando",
"Preparando la carpeta del juego", "Mostrar detalles", "Ocultar detalles", "Cancelar", "Atrás", "Abrir carpeta", "Jugar", "Tu juego está listo", "creado en",
"La creación se detuvo", "Creación cancelada", "Puedes empezar de nuevo desde la misma carpeta.", "¿Detener la creación y cerrar?", "Idioma", "Detener y cerrar", "Seguir creando",
};
static readonly string[] Pt =
{
"Transforma sua cópia de Ocarina of Time em uma pasta de jogo para iniciar no PC.", "Arquivos do jogo", "Arquivo .nup", "romfs e exefs",
"Você também pode soltar um arquivo ou uma pasta nesta janela.", "Salvar o jogo em", "Criar", "Procurar", "Leva cerca de 45 minutos e precisa de 60 GB.",
"{0} tem {1} GB livres.", "Verificando a versão do jogo...", "Esta versão é compatível com o Triforce.", "Esta versão não é compatível. O Triforce precisa da build e0f3ccfa.",
"As ferramentas do Triforce não foram encontradas ao lado deste aplicativo.", "O Python não foi encontrado.",
"Criando", "Isso leva um tempo, e seu PC continua utilizável.", "Decorrido", "Lendo seus arquivos do jogo", "Traduzindo o jogo para código de PC", "Compilando",
"Montando a pasta do jogo", "Mostrar detalhes", "Ocultar detalhes", "Cancelar", "Voltar", "Abrir pasta", "Jogar", "Seu jogo está pronto", "criado em",
"A criação parou", "Criação cancelada", "Você pode recomeçar a partir da mesma pasta.", "Parar a criação e fechar?", "Idioma", "Parar e fechar", "Continuar",
};
static readonly string[] Nl =
{
"Maakt van je eigen exemplaar van Ocarina of Time een spelmap om op pc te starten.", "Spelbestanden", ".nup-bestand", "romfs en exefs",
"Je kunt ook een bestand of map op dit venster slepen.", "Spel opslaan in", "Maken", "Bladeren", "Duurt ongeveer 45 minuten en vereist 60 GB.",
"{0} heeft {1} GB vrij.", "Spelversie controleren...", "Deze versie wordt door Triforce ondersteund.", "Deze versie wordt niet ondersteund. Triforce heeft build e0f3ccfa nodig.",
"De Triforce-tools zijn niet naast deze app gevonden.", "Python is niet gevonden.",
"Bezig met maken", "Dit duurt even, en je pc blijft bruikbaar.", "Verstreken", "Je spelbestanden lezen", "Spel vertalen naar pc-code", "Compileren",
"Spelmap samenstellen", "Details tonen", "Details verbergen", "Annuleren", "Terug", "Map openen", "Spelen", "Je spel is klaar", "gemaakt in",
"Het maken is gestopt", "Maken geannuleerd", "Je kunt opnieuw beginnen vanuit dezelfde map.", "Maken stoppen en sluiten?", "Taal", "Stoppen en sluiten", "Doorgaan",
};
static readonly string[] Pl =
{
"Zamienia Twoją kopię Ocarina of Time w folder gry, który uruchomisz na PC.", "Pliki gry", "Plik .nup", "romfs i exefs",
"Możesz też upuścić plik lub folder na to okno.", "Zapisz grę w", "Utwórz", "Przeglądaj", "Trwa około 45 minut i wymaga 60 GB.",
"{0}: wolne {1} GB.", "Sprawdzanie wersji gry...", "Ta wersja jest obsługiwana przez Triforce.", "Ta wersja nie jest obsługiwana. Triforce wymaga kompilacji e0f3ccfa.",
"Nie znaleziono narzędzi Triforce obok tej aplikacji.", "Nie znaleziono Pythona.",
"Tworzenie", "To chwilę potrwa, a komputer pozostanie w użyciu.", "Upłynęło", "Odczytywanie plików gry", "Tłumaczenie gry na kod PC", "Kompilowanie",
"Składanie folderu gry", "Pokaż szczegóły", "Ukryj szczegóły", "Anuluj", "Wstecz", "Otwórz folder", "Graj", "Twoja gra jest gotowa", "utworzono w",
"Tworzenie zostało przerwane", "Anulowano tworzenie", "Możesz zacząć ponownie z tego samego folderu.", "Przerwać tworzenie i zamknąć?", "Język", "Przerwij i zamknij", "Kontynuuj",
};
static readonly string[] Ru =
{
"Превращает вашу копию Ocarina of Time в папку с игрой для запуска на ПК.", "Файлы игры", "Файл .nup", "romfs и exefs",
"Также можно перетащить файл или папку в это окно.", "Сохранить игру в", "Собрать", "Обзор", "Занимает около 45 минут и требует 60 ГБ.",
"{0}: свободно {1} ГБ.", "Проверка версии игры...", "Эта версия поддерживается Triforce.", "Эта версия не поддерживается. Triforce нужна сборка e0f3ccfa.",
"Инструменты Triforce не найдены рядом с этим приложением.", "Python не найден.",
"Сборка", "Это займёт время, а компьютером можно пользоваться.", "Прошло", "Чтение файлов игры", "Перевод игры в код для ПК", "Компиляция",
"Подготовка папки с игрой", "Показать подробности", "Скрыть подробности", "Отмена", "Назад", "Открыть папку", "Играть", "Ваша игра готова", "собрано за",
"Сборка остановлена", "Сборка отменена", "Можно начать заново из той же папки.", "Остановить сборку и закрыть?", "Язык", "Остановить и закрыть", "Продолжить",
};
static readonly string[] Ja =
{
"お持ちの Ocarina of Time を、PC で起動できるゲームフォルダーに変換します。", "ゲームファイル", ".nup ファイル", "romfs と exefs",
"ファイルやフォルダーをこのウィンドウにドロップすることもできます。", "ゲームの保存先", "ビルド", "参照", "約 45 分かかり、60 GB 必要です。",
"{0} の空き容量: {1} GB", "ゲームのバージョンを確認しています...", "このバージョンは Triforce に対応しています。", "このバージョンには対応していません。Triforce にはビルド e0f3ccfa が必要です。",
"このアプリの横に Triforce ツールが見つかりません。", "Python が見つかりません。",
"ビルド中", "時間がかかりますが、PC はそのまま使えます。", "経過時間", "ゲームファイルを読み込んでいます", "ゲームを PC 用コードに変換しています", "コンパイル中",
"ゲームフォルダーを作成しています", "詳細を表示", "詳細を隠す", "キャンセル", "戻る", "フォルダーを開く", "プレイ", "ゲームの準備ができました", "所要時間",
"ビルドが停止しました", "ビルドをキャンセルしました", "同じフォルダーからやり直せます。", "ビルドを中止して閉じますか?", "言語", "中止して閉じる", "ビルドを続ける",
};
static readonly string[] Ko =
{
"가지고 있는 Ocarina of Time을 PC에서 실행할 수 있는 게임 폴더로 만듭니다.", "게임 파일", ".nup 파일", "romfs 및 exefs",
"파일이나 폴더를 이 창에 끌어다 놓을 수도 있습니다.", "게임 저장 위치", "빌드", "찾아보기", "약 45분이 걸리며 60GB가 필요합니다.",
"{0} 여유 공간: {1}GB", "게임 버전을 확인하는 중...", "Triforce이 지원하는 버전입니다.", "지원되지 않는 버전입니다. Triforce에는 빌드 e0f3ccfa가 필요합니다.",
"이 앱 옆에서 Triforce 도구를 찾을 수 없습니다.", "Python을 찾을 수 없습니다.",
"빌드 중", "시간이 걸리지만 PC는 계속 사용할 수 있습니다.", "경과 시간", "게임 파일을 읽는 중", "게임을 PC 코드로 변환하는 중", "컴파일 중",
"게임 폴더를 만드는 중", "자세히 보기", "자세히 숨기기", "취소", "뒤로", "폴더 열기", "플레이", "게임이 준비되었습니다", "소요 시간",
"빌드가 중단되었습니다", "빌드가 취소되었습니다", "같은 폴더에서 다시 시작할 수 있습니다.", "빌드를 중단하고 닫을까요?", "언어", "중단하고 닫기", "계속 빌드",
};
static readonly string[] ZhHans =
{
"将你自己的 Ocarina of Time 变成可在电脑上启动的游戏文件夹。", "游戏文件", ".nup 文件", "romfs 和 exefs",
"也可以将文件或文件夹拖放到此窗口。", "游戏保存位置", "生成", "浏览", "大约需要 45 分钟和 60 GB 空间。",
"{0} 可用空间 {1} GB。", "正在检查游戏版本...", "Triforce 支持此版本。", "不支持此版本。Triforce 需要构建版本 e0f3ccfa。",
"在此应用旁边找不到 Triforce 工具。", "找不到 Python。",
"正在生成", "这需要一些时间,期间电脑仍可正常使用。", "已用时间", "正在读取游戏文件", "正在将游戏转换为电脑代码", "正在编译",
"正在整理游戏文件夹", "显示详细信息", "隐藏详细信息", "取消", "返回", "打开文件夹", "开始游戏", "你的游戏已准备就绪", "用时",
"生成已停止", "生成已取消", "你可以从同一文件夹重新开始。", "要停止生成并关闭吗?", "语言", "停止并关闭", "继续生成",
};
static readonly string[] ZhHant =
{
"將你自己的 Ocarina of Time 變成可在電腦上啟動的遊戲資料夾。", "遊戲檔案", ".nup 檔案", "romfs 和 exefs",
"也可以將檔案或資料夾拖放到此視窗。", "遊戲儲存位置", "建置", "瀏覽", "大約需要 45 分鐘和 60 GB 空間。",
"{0} 可用空間 {1} GB。", "正在檢查遊戲版本...", "Triforce 支援此版本。", "不支援此版本。Triforce 需要建置版本 e0f3ccfa。",
"在此應用程式旁找不到 Triforce 工具。", "找不到 Python。",
"正在建置", "這需要一些時間,期間電腦仍可正常使用。", "已用時間", "正在讀取遊戲檔案", "正在將遊戲轉換為電腦程式碼", "正在編譯",
"正在整理遊戲資料夾", "顯示詳細資訊", "隱藏詳細資訊", "取消", "返回", "開啟資料夾", "開始遊戲", "你的遊戲已準備就緒", "用時",
"建置已停止", "建置已取消", "你可以從同一資料夾重新開始。", "要停止建置並關閉嗎?", "語言", "停止並關閉", "繼續建置",
};
public static readonly Language[] All =
{
new("en-US", "English (US)", En), new("en-GB", "English (UK)", En), new("fr", "Français", Fr), new("fr-CA", "Français (Canada)", Fr),
new("de", "Deutsch", De), new("it", "Italiano", It), new("es", "Español (España)", Es), new("es-419", "Español (Latinoamérica)", Es),
new("pt-BR", "Português (Brasil)", Pt), new("nl", "Nederlands", Nl), new("pl", "Polski", Pl), new("ru", "Русский", Ru),
new("ja", "日本語", Ja), new("ko", "한국어", Ko), new("zh-Hans", "简体中文", ZhHans), new("zh-Hant", "繁體中文", ZhHant),
};
/// The language closest to Windows' own: the exact one, then the same family, else English (US).
public static Language Default()
{
var c = CultureInfo.CurrentUICulture;
var name = c.Name;
var pick = All.FirstOrDefault(l => l.Code.Equals(name, StringComparison.OrdinalIgnoreCase));
if (pick != null) return pick;
if (name.StartsWith("zh")) return All.First(l => l.Code == (name.Contains("TW") || name.Contains("HK") || name.Contains("Hant") ? "zh-Hant" : "zh-Hans"));
if (name.StartsWith("es-") && name != "es-ES") return All.First(l => l.Code == "es-419");
if (name.StartsWith("pt")) return All.First(l => l.Code == "pt-BR");
return All.FirstOrDefault(l => l.Code == c.TwoLetterISOLanguageName) ?? All[0];
}
}

103
setup/build.ps1 Normal file
View File

@@ -0,0 +1,103 @@
# Builds TriforceSetup.exe: .NET Framework 4.8 (in every Windows 10/11), one file, no installers needed to run it.
# powershell -File setup\build.ps1 [-Version v1.0.0] -> setup\out\TriforceSetup.exe
# Needs the C# compiler from Visual Studio (Build Tools) for modern C#; the window (Main.xaml) and its pictures are embedded.
# -Out <folder> puts the exe (and the generated pictures) somewhere else, e.g. a scratch folder for previews.
param([string]$Version = 'dev', [string]$Out = '')
$ErrorActionPreference = 'Stop'
$here = $PSScriptRoot
$repo = Split-Path $here
$out = if ($Out) { $Out } else { Join-Path $here 'out' }
$gen = Join-Path $out 'gen'
New-Item -ItemType Directory -Force $gen | Out-Null
$csc = Get-ChildItem 'C:\Program Files*\Microsoft Visual Studio\*\*\MSBuild\Current\Bin\Roslyn\csc.exe' -ErrorAction SilentlyContinue |
Sort-Object FullName -Descending | Select-Object -First 1 -ExpandProperty FullName
if (-not $csc) { throw 'No C# compiler found (Visual Studio Build Tools: MSBuild\Current\Bin\Roslyn\csc.exe)' }
# ---- pictures: the crest, the exe's icon ----
Add-Type -AssemblyName System.Drawing
function Resize([System.Drawing.Image]$src, [int]$w) {
$h = [int][math]::Round($src.Height * $w / $src.Width)
$b = New-Object System.Drawing.Bitmap $w, $h, ([System.Drawing.Imaging.PixelFormat]::Format32bppArgb)
$g = [System.Drawing.Graphics]::FromImage($b)
$g.InterpolationMode = 'HighQualityBicubic'; $g.PixelOffsetMode = 'HighQuality'; $g.CompositingMode = 'SourceCopy'
$ia = New-Object System.Drawing.Imaging.ImageAttributes; $ia.SetWrapMode('TileFlipXY')
$g.DrawImage($src, (New-Object System.Drawing.Rectangle 0, 0, $w, $h), 0, 0, $src.Width, $src.Height, 'Pixel', $ia)
$g.Dispose(); return $b
}
function Square([System.Drawing.Image]$src, [int]$s) {
# (the crest centred in a square, for the icon)
$b = New-Object System.Drawing.Bitmap $s, $s, ([System.Drawing.Imaging.PixelFormat]::Format32bppArgb)
$g = [System.Drawing.Graphics]::FromImage($b)
$g.InterpolationMode = 'HighQualityBicubic'; $g.PixelOffsetMode = 'HighQuality'
$scale = [math]::Min($s / $src.Width, $s / $src.Height)
$w = $src.Width * $scale; $h = $src.Height * $scale
$g.DrawImage($src, [single](($s - $w) / 2), [single](($s - $h) / 2), [single]$w, [single]$h)
$g.Dispose(); return $b
}
$crest = [System.Drawing.Image]::FromFile((Join-Path $repo 'assets\triforce.png'))
# (the crest whole, as painted: Setup shows it large and cuts its stones out of it, Art.cs)
Copy-Item (Join-Path $repo 'assets\triforce.png') (Join-Path $gen 'triforce.png') -Force
(Square $crest 64).Save((Join-Path $gen 'icon.png'), [System.Drawing.Imaging.ImageFormat]::Png)
# icon: PNG entries 16..256
$sizes = 16, 20, 24, 32, 40, 48, 64, 96, 128, 256
$pngs = foreach ($s in $sizes) { $ms = New-Object IO.MemoryStream; (Square $crest $s).Save($ms, [System.Drawing.Imaging.ImageFormat]::Png); , $ms.ToArray() }
$ico = New-Object IO.MemoryStream; $bw = New-Object IO.BinaryWriter $ico
$bw.Write([uint16]0); $bw.Write([uint16]1); $bw.Write([uint16]$sizes.Count)
$offset = 6 + 16 * $sizes.Count
for ($i = 0; $i -lt $sizes.Count; $i++) {
$s = $sizes[$i]; $d = if ($s -ge 256) { 0 } else { $s }
$bw.Write([byte]$d); $bw.Write([byte]$d); $bw.Write([byte]0); $bw.Write([byte]0)
$bw.Write([uint16]1); $bw.Write([uint16]32); $bw.Write([uint32]$pngs[$i].Length); $bw.Write([uint32]$offset)
$offset += $pngs[$i].Length
}
foreach ($p in $pngs) { $bw.Write($p) }
$bw.Flush(); [IO.File]::WriteAllBytes((Join-Path $gen 'triforce.ico'), $ico.ToArray())
$crest.Dispose()
# ---- version + manifest ----
$numeric = if ($Version -match '(\d+)\.(\d+)\.(\d+)') { "$($Matches[1]).$($Matches[2]).$($Matches[3]).0" } else { '0.0.0.0' }
@"
[assembly: System.Reflection.AssemblyTitle("Triforce Setup")]
[assembly: System.Reflection.AssemblyProduct("Triforce")]
[assembly: System.Reflection.AssemblyDescription("Installs, builds and updates Triforce")]
[assembly: System.Reflection.AssemblyCopyright("GPL-3.0-or-later")]
[assembly: System.Reflection.AssemblyVersion("$numeric")]
[assembly: System.Reflection.AssemblyFileVersion("$numeric")]
[assembly: System.Reflection.AssemblyInformationalVersion("$Version")]
"@ | Set-Content (Join-Path $gen 'AssemblyInfo.cs') -Encoding UTF8
@'
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="TriforceSetup"/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security><requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"><requestedExecutionLevel level="asInvoker" uiAccess="false"/></requestedPrivileges></security>
</trustInfo>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application><supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/></application>
</compatibility>
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware>
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>
<longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>
</windowsSettings>
</application>
</assembly>
'@ | Set-Content (Join-Path $gen 'app.manifest') -Encoding UTF8
# ---- compile ----
$fw = 'C:\Windows\Microsoft.NET\Framework64\v4.0.30319'
$refs = "$fw\WPF\PresentationCore.dll", "$fw\WPF\PresentationFramework.dll", "$fw\WPF\WindowsBase.dll", "$fw\System.Xaml.dll",
"$fw\System.dll", "$fw\System.Core.dll", "$fw\System.Net.Http.dll", "$fw\System.IO.Compression.dll",
"$fw\System.IO.Compression.FileSystem.dll", "$fw\Microsoft.CSharp.dll", "$fw\System.Web.Extensions.dll"
$exe = Join-Path $out 'TriforceSetup.exe'
$cscArgs = @('/nologo', '/target:winexe', '/langversion:latest', '/nullable:enable', '/optimize+', '/platform:anycpu', '/utf8output',
"/out:$exe", "/win32icon:$gen\triforce.ico", "/win32manifest:$gen\app.manifest", '/nowarn:CS8618,CS8632,CS1701,CS1702')
$cscArgs += $refs | ForEach-Object { "/reference:$_" }
$cscArgs += "/resource:$here\Main.xaml,Main.xaml", "/resource:$gen\triforce.png,triforce.png", "/resource:$gen\icon.png,icon.png"
$cscArgs += "$here\Setup.cs", "$here\Shell.cs", "$here\Shell.Home.cs", "$here\Shell.Saves.cs", "$here\Shell.Test.cs", "$here\Stage.cs", "$here\Art.cs", "$here\Look.cs", "$here\Saves.cs", "$here\Strings.cs", "$gen\AssemblyInfo.cs"
& $csc @cscArgs
if ($LASTEXITCODE -ne 0) { throw "csc failed ($LASTEXITCODE)" }
"built $exe ($Version, {0:N0} KB)" -f ((Get-Item $exe).Length / 1KB)

102
setup/pack_tools.ps1 Normal file
View File

@@ -0,0 +1,102 @@
# Packs Triforce-Tools.zip, the release asset Triforce Setup downloads: a "tools" folder with everything a build needs.
# powershell -File setup\pack_tools.ps1 -Tag v1.0.0 [-Deps D:\src\release\triforce-deps] [-Out setup\out\release]
# From this checkout: nx2, host, gpu, scripts, third_party (tracked files, as they are on disk), the speed profile in work\.
# From -Deps (not in git, too big or binary): python\ (with lz4 numpy capstone unicorn zstandard), cpm\ (Vulkan headers, FFmpeg),
# wgpu-native\, llvm-mingw\ (the compiler; without it a player's PC would need Visual Studio), third_party\ (SDL2.dll, zbic.dll/.lib).
param(
[Parameter(Mandatory = $true)][string]$Tag,
[string]$Deps = 'D:\src\release\triforce-deps',
[string]$Out = (Join-Path $PSScriptRoot 'out\release'),
[switch]$AllowNoCompiler
)
$ErrorActionPreference = 'Stop'
$repo = Split-Path $PSScriptRoot
foreach ($need in 'python\python.exe', 'cpm', 'wgpu-native') {
if (-not (Test-Path (Join-Path $Deps $need))) { throw "missing $need in $Deps" }
}
if (-not (Test-Path (Join-Path $Deps 'llvm-mingw\bin\clang.exe')) -and -not $AllowNoCompiler) {
throw "no llvm-mingw in ${Deps}: players' builds would need Visual Studio. (-AllowNoCompiler packs anyway, for tests)"
}
$stage = Join-Path $Out 'stage'
$tools = Join-Path $stage 'tools'
if (Test-Path $stage) { Remove-Item -Recurse -Force $stage }
New-Item -ItemType Directory -Force $tools | Out-Null
# 1. this checkout's sources (tracked files, working-tree versions)
$files = git -C $repo ls-files -- nx2 host gpu scripts third_party LICENSE
foreach ($f in $files) {
$src = Join-Path $repo $f
if (-not (Test-Path $src -PathType Leaf)) { continue }
$dst = Join-Path $tools $f
New-Item -ItemType Directory -Force (Split-Path $dst) | Out-Null
Copy-Item $src $dst
}
"sources: $($files.Count) files"
# 2. the dependencies
foreach ($d in 'python', 'cpm', 'wgpu-native', 'llvm-mingw', 'third_party') {
$src = Join-Path $Deps $d
if (Test-Path $src) { robocopy $src (Join-Path $tools $d) /E /NFL /NDL /NJH /NJS /NP | Out-Null; "deps: $d" }
}
# 3. the speed profile (hot functions, link order, play profile, chunk list) and the Triforce icon for the game's exe
$work = Join-Path $tools 'work'
New-Item -ItemType Directory -Force $work | Out-Null
foreach ($n in 'hot_funcs.txt', 'hot_order.txt', 'hookshot_pieces.prof') {
if (Test-Path (Join-Path $repo "work\$n")) { Copy-Item (Join-Path $repo "work\$n") $work }
}
if (Test-Path (Join-Path $repo 'work\image')) { robocopy (Join-Path $repo 'work\image') (Join-Path $work 'image') /E /NFL /NDL /NJH /NJS /NP | Out-Null }
Add-Type -AssemblyName System.Drawing
$crest = [System.Drawing.Image]::FromFile((Join-Path $repo 'assets\triforce.png'))
$sizes = 16, 24, 32, 48, 64, 128, 256
$pngs = foreach ($s in $sizes) {
$b = New-Object System.Drawing.Bitmap $s, $s, ([System.Drawing.Imaging.PixelFormat]::Format32bppArgb)
$g = [System.Drawing.Graphics]::FromImage($b); $g.InterpolationMode = 'HighQualityBicubic'; $g.PixelOffsetMode = 'HighQuality'
$k = [math]::Min($s / $crest.Width, $s / $crest.Height); $w = $crest.Width * $k; $h = $crest.Height * $k
$g.DrawImage($crest, [single](($s - $w) / 2), [single](($s - $h) / 2), [single]$w, [single]$h); $g.Dispose()
$ms = New-Object IO.MemoryStream; $b.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png); , $ms.ToArray()
}
$crest.Dispose()
# .ico
$ico = New-Object IO.MemoryStream; $w = New-Object IO.BinaryWriter $ico
$w.Write([uint16]0); $w.Write([uint16]1); $w.Write([uint16]$sizes.Count); $off = 6 + 16 * $sizes.Count
for ($i = 0; $i -lt $sizes.Count; $i++) { $d = $sizes[$i] -band 255; $w.Write([byte]$d); $w.Write([byte]$d); $w.Write([uint16]0); $w.Write([uint16]1); $w.Write([uint16]32); $w.Write([uint32]$pngs[$i].Length); $w.Write([uint32]$off); $off += $pngs[$i].Length }
foreach ($p in $pngs) { $w.Write($p) }; $w.Flush(); [IO.File]::WriteAllBytes((Join-Path $work 'hookshot.ico'), $ico.ToArray())
# .res (as nx2/make_icon.py: RT_ICON entries + RT_GROUP_ICON 1, which the game's window class loads)
function ResEntry([int]$kind, [int]$name, [byte[]]$data, [int]$flags) {
$m = New-Object IO.MemoryStream; $x = New-Object IO.BinaryWriter $m
$x.Write([uint32]$data.Length); $x.Write([uint32]32); $x.Write([uint16]0xFFFF); $x.Write([uint16]$kind); $x.Write([uint16]0xFFFF); $x.Write([uint16]$name)
$x.Write([uint32]0); $x.Write([uint16]$flags); $x.Write([uint16]0x0409); $x.Write([uint32]0); $x.Write([uint32]0)
$x.Write($data); $pad = (4 - ($data.Length % 4)) % 4; for ($j = 0; $j -lt $pad; $j++) { $x.Write([byte]0) }
$x.Flush(); , $m.ToArray()
}
$group = New-Object IO.MemoryStream; $gw = New-Object IO.BinaryWriter $group
$gw.Write([uint16]0); $gw.Write([uint16]1); $gw.Write([uint16]$sizes.Count)
for ($i = 0; $i -lt $sizes.Count; $i++) { $d = $sizes[$i] -band 255; $gw.Write([byte]$d); $gw.Write([byte]$d); $gw.Write([uint16]0); $gw.Write([uint16]1); $gw.Write([uint16]32); $gw.Write([uint32]$pngs[$i].Length); $gw.Write([uint16]($i + 1)) }
$gw.Flush()
$res = New-Object IO.MemoryStream
$res.Write(($e = ResEntry 0 0 ([byte[]]@()) 0), 0, $e.Length)
for ($i = 0; $i -lt $sizes.Count; $i++) { $e = ResEntry 3 ($i + 1) $pngs[$i] 0x1010; $res.Write($e, 0, $e.Length) }
$e = ResEntry 14 1 $group.ToArray() 0x1030; $res.Write($e, 0, $e.Length)
[IO.File]::WriteAllBytes((Join-Path $work 'hookshot.res'), $res.ToArray())
"work: profile + Triforce icon"
# 4. the release name, read by nx2/version.py and Triforce Setup
Set-Content (Join-Path $tools 'version.txt') $Tag -Encoding ASCII
# 5. zip (tools/... inside)
$zip = Join-Path $Out 'Triforce-Tools.zip'
if (Test-Path $zip) { Remove-Item $zip }
Add-Type -AssemblyName System.IO.Compression, System.IO.Compression.FileSystem
# (entries written one by one: Windows PowerShell's CreateFromDirectory names them with backslashes)
$fs = [IO.File]::Open($zip, 'CreateNew')
$archive = New-Object IO.Compression.ZipArchive $fs, ([IO.Compression.ZipArchiveMode]::Create)
$base = (Resolve-Path $stage).Path.TrimEnd('\') + '\'
foreach ($f in Get-ChildItem $tools -Recurse -File) {
$name = $f.FullName.Substring($base.Length).Replace('\', '/')
[void][IO.Compression.ZipFileExtensions]::CreateEntryFromFile($archive, $f.FullName, $name, [IO.Compression.CompressionLevel]::Optimal)
}
$archive.Dispose(); $fs.Dispose()
Remove-Item -Recurse -Force $stage
"packed $zip ({0:N0} MB)" -f ((Get-Item $zip).Length / 1MB)