329 lines
16 KiB
C#
329 lines
16 KiB
C#
using System;
|
||
using System.Collections.Generic;
|
||
using System.IO;
|
||
using System.Linq;
|
||
using FontStashSharp;
|
||
using Microsoft.Xna.Framework;
|
||
using Microsoft.Xna.Framework.Graphics;
|
||
|
||
namespace GladiatorIdle.Gfx
|
||
{
|
||
/// <summary>
|
||
/// Bilder, Clips und Schriften zur Laufzeit: Texturen aus Assets/Sprites bzw. Assets/Video
|
||
/// (von der Platte, vormultipliziertes Alpha), Schriften als TTF aus dem System.
|
||
/// </summary>
|
||
internal static class Assets
|
||
{
|
||
static GraphicsDevice _gd = null!;
|
||
public static GraphicsDevice Device => _gd;
|
||
static readonly Dictionary<string, Texture2D?> _tex = new();
|
||
static readonly Dictionary<Texture2D, Texture2D> _white = new();
|
||
static string? _root;
|
||
|
||
public static Texture2D Pixel { get; private set; } = null!;
|
||
/// Weicher Kreis (Licht, Staub, Schatten), 128 px.
|
||
public static Texture2D Soft { get; private set; } = null!;
|
||
/// Scharfer Kreis mit geglättetem Rand (Farbfelder, Knöpfe), 128 px.
|
||
public static Texture2D Disc { get; private set; } = null!;
|
||
|
||
public static FontSystem Serif { get; private set; } = null!;
|
||
public static FontSystem Sans { get; private set; } = null!;
|
||
public static FontSystem SansBold { get; private set; } = null!;
|
||
|
||
public static void Init(GraphicsDevice gd)
|
||
{
|
||
_gd = gd;
|
||
Pixel = new Texture2D(gd, 1, 1);
|
||
Pixel.SetData(new[] { Color.White });
|
||
const int S = 128;
|
||
var soft = new Color[S * S];
|
||
for (int y = 0; y < S; y++)
|
||
for (int x = 0; x < S; x++)
|
||
{
|
||
float dx = (x + 0.5f) / S * 2 - 1, dy = (y + 0.5f) / S * 2 - 1;
|
||
float a = MathHelper.Clamp(1 - MathF.Sqrt(dx * dx + dy * dy), 0, 1);
|
||
a = a * a * (3 - 2 * a);
|
||
soft[y * S + x] = new Color(a, a, a, a);
|
||
}
|
||
Soft = new Texture2D(gd, S, S);
|
||
Soft.SetData(soft);
|
||
var disc = new Color[S * S];
|
||
for (int y = 0; y < S; y++)
|
||
for (int x = 0; x < S; x++)
|
||
{
|
||
float dx = x + 0.5f - S / 2f, dy = y + 0.5f - S / 2f;
|
||
float a = MathHelper.Clamp(S / 2f - 1 - MathF.Sqrt(dx * dx + dy * dy), 0, 1);
|
||
disc[y * S + x] = new Color(a, a, a, a);
|
||
}
|
||
Disc = new Texture2D(gd, S, S);
|
||
Disc.SetData(disc);
|
||
|
||
string fonts = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "Fonts");
|
||
Serif = Font(fonts, "georgiab.ttf");
|
||
Sans = Font(fonts, "segoeui.ttf");
|
||
SansBold = Font(fonts, "segoeuib.ttf");
|
||
}
|
||
|
||
static FontSystem Font(string dir, string file)
|
||
{
|
||
var fs = new FontSystem(new FontSystemSettings { FontResolutionFactor = 1, KernelWidth = 1, KernelHeight = 1 });
|
||
fs.AddFont(File.ReadAllBytes(Path.Combine(dir, file)));
|
||
return fs;
|
||
}
|
||
|
||
static string? Root => _root ??= FindRoot();
|
||
|
||
/// Assets-Ordner (null, wenn nicht gefunden).
|
||
public static string? RootDir => Root;
|
||
|
||
static string? FindRoot()
|
||
{
|
||
var dir = new DirectoryInfo(AppContext.BaseDirectory);
|
||
while (dir != null)
|
||
{
|
||
if (Directory.Exists(Path.Combine(dir.FullName, "Assets", "Sprites"))) return Path.Combine(dir.FullName, "Assets");
|
||
dir = dir.Parent;
|
||
}
|
||
return null;
|
||
}
|
||
|
||
/// Bild aus Assets/Sprites (null, wenn es fehlt).
|
||
public static Texture2D? Sprite(string name, string ext = "png") => Load($"Sprites/{name}.{ext}");
|
||
|
||
public static Texture2D? Load(string rel)
|
||
{
|
||
if (_tex.TryGetValue(rel, out var t)) return t;
|
||
Texture2D? result = null;
|
||
if (Root is string root && File.Exists(Path.Combine(root, rel)))
|
||
using (var fs = File.OpenRead(Path.Combine(root, rel)))
|
||
result = Texture2D.FromStream(_gd, fs, DefaultColorProcessors.PremultiplyAlpha);
|
||
_tex[rel] = result;
|
||
return result;
|
||
}
|
||
|
||
// ── Mipmaps: verkleinerte Stufen für Texturen, die schräg oder weit weg zu sehen sind
|
||
// (Sand, Mauer, Publikum, Figuren) – sonst flimmern sie in der Tiefe ──
|
||
static readonly Dictionary<Texture2D, Texture2D> _mipped = new();
|
||
|
||
/// Dieselbe Textur mit allen Mipmap-Stufen (einmal je Quelle).
|
||
public static Texture2D Mipmapped(Texture2D src)
|
||
{
|
||
if (src.LevelCount > 1) return src;
|
||
if (_mipped.TryGetValue(src, out var t)) return t;
|
||
var data = new Color[src.Width * src.Height];
|
||
src.GetData(data);
|
||
return _mipped[src] = MipTexture(data, src.Width, src.Height);
|
||
}
|
||
|
||
/// Textur aus Pixeln mit Mipmap-Stufen (2×2-Mittel je Stufe).
|
||
public static Texture2D MipTexture(Color[] data, int w, int h) => Upload(MipLevels(data, w, h), w, h);
|
||
|
||
/// Mipmap-Stufen nur aus Pixeln (ohne Grafikkarte, also auch im Hintergrund nutzbar).
|
||
public static Color[][] MipLevels(Color[] data, int w, int h)
|
||
{
|
||
var levels = new List<Color[]> { data };
|
||
var cur = data; int cw = w, ch = h;
|
||
while (cw > 1 || ch > 1)
|
||
{
|
||
int nw = Math.Max(1, cw / 2), nh = Math.Max(1, ch / 2);
|
||
var next = new Color[nw * nh];
|
||
var src = cur; int sw = cw, sh = ch;
|
||
System.Threading.Tasks.Parallel.For(0, nh, y =>
|
||
{
|
||
for (int x = 0; x < nw; x++)
|
||
{
|
||
int x0 = Math.Min(sw - 1, x * 2), x1 = Math.Min(sw - 1, x * 2 + 1), y0 = Math.Min(sh - 1, y * 2), y1 = Math.Min(sh - 1, y * 2 + 1);
|
||
var a = src[y0 * sw + x0]; var b = src[y0 * sw + x1]; var c = src[y1 * sw + x0]; var d = src[y1 * sw + x1];
|
||
next[y * nw + x] = new Color((a.R + b.R + c.R + d.R + 2) / 4, (a.G + b.G + c.G + d.G + 2) / 4, (a.B + b.B + c.B + d.B + 2) / 4, (a.A + b.A + c.A + d.A + 2) / 4);
|
||
}
|
||
});
|
||
levels.Add(next);
|
||
cur = next; cw = nw; ch = nh;
|
||
}
|
||
return levels.ToArray();
|
||
}
|
||
|
||
/// Fertige Stufen zur Grafikkarte (Hauptthread, schnell).
|
||
public static Texture2D Upload(Color[][] levels, int w, int h)
|
||
{
|
||
var t = new Texture2D(_gd, w, h, true, SurfaceFormat.Color);
|
||
for (int i = 0; i < Math.Min(levels.Length, t.LevelCount); i++) t.SetData(i, null, levels[i], 0, levels[i].Length);
|
||
return t;
|
||
}
|
||
|
||
/// Pixel einer Textur schon bekannt (Figuren): Einfärben braucht dann kein Zurücklesen von der Grafikkarte.
|
||
public static void RegisterPixels(Texture2D t, Color[] data) { lock (_known) _known[t] = data; }
|
||
public static Color[]? KnownPixels(Texture2D t) { lock (_known) return _known.TryGetValue(t, out var d) ? d : null; }
|
||
static readonly Dictionary<Texture2D, Color[]> _known = new();
|
||
|
||
/// Bild eines Video-Sprites: Farbe vor Schwarz (JPEG, also schon vormultipliziert)
|
||
/// plus Deckkraft (Graustufen-PNG) — zusammengesetzt zu einer Textur.
|
||
public static Texture2D? LoadFrame(string relBase)
|
||
{
|
||
if (Root is not string root) return null;
|
||
string jpg = Path.Combine(root, relBase + ".jpg"), mask = Path.Combine(root, relBase + "_a.png");
|
||
if (!File.Exists(jpg) || !File.Exists(mask)) return null;
|
||
Texture2D color, alpha;
|
||
using (var fs = File.OpenRead(jpg)) color = Texture2D.FromStream(_gd, fs);
|
||
using (var fs = File.OpenRead(mask)) alpha = Texture2D.FromStream(_gd, fs);
|
||
var c = new Color[color.Width * color.Height];
|
||
var a = new Color[alpha.Width * alpha.Height];
|
||
color.GetData(c); alpha.GetData(a);
|
||
for (int i = 0; i < c.Length && i < a.Length; i++) c[i].A = a[i].R;
|
||
color.SetData(c);
|
||
alpha.Dispose();
|
||
return color;
|
||
}
|
||
|
||
/// Textdatei aus Assets (z. B. Clip-Angaben), null wenn sie fehlt.
|
||
public static string? ReadText(string rel) =>
|
||
Root is string root && File.Exists(Path.Combine(root, rel)) ? File.ReadAllText(Path.Combine(root, rel)) : null;
|
||
|
||
/// Frames eines Wan-Clips (Assets/Video/<name>_NN.jpg).
|
||
public static List<Texture2D> Clip(string name)
|
||
{
|
||
var list = new List<Texture2D>();
|
||
for (int i = 0; i < 1000; i++)
|
||
{
|
||
var t = Load($"Video/{name}_{i:D2}.jpg");
|
||
if (t == null) break;
|
||
list.Add(t);
|
||
}
|
||
return list;
|
||
}
|
||
|
||
/// Weiße Silhouette einer Textur (Treffer-Blitz, Leuchten), einmal erzeugt.
|
||
public static Texture2D White(Texture2D src)
|
||
{
|
||
if (_white.TryGetValue(src, out var w)) return w;
|
||
var data = new Color[src.Width * src.Height];
|
||
src.GetData(data);
|
||
for (int i = 0; i < data.Length; i++) { byte a = data[i].A; data[i] = new Color(a, a, a, a); }
|
||
w = new Texture2D(_gd, src.Width, src.Height);
|
||
w.SetData(data);
|
||
_white[src] = w;
|
||
return w;
|
||
}
|
||
|
||
static readonly Dictionary<(Texture2D, int), Texture2D> _painted = new();
|
||
|
||
/// Teamfarbe: Magenta-Flächen (Stoff, Federbusch, Schildbemalung) in die gewählte Farbe,
|
||
/// Schattierung bleibt; weiche Übergänge am Rand der Flächen. Einmal je Bild und Farbe.
|
||
public static Texture2D Paint(Texture2D src, int colorIndex)
|
||
{
|
||
if (_painted.TryGetValue((src, colorIndex), out var t)) return t;
|
||
var sw = System.Diagnostics.Stopwatch.StartNew();
|
||
var info = PaintInfoOf(src);
|
||
if (info.Index.Length == 0) return _painted[(src, colorIndex)] = src; // keine Teamfarben-Flächen
|
||
var data = (Color[])info.Data.Clone();
|
||
var c = Appearance.Colors[colorIndex];
|
||
System.Threading.Tasks.Parallel.For(0, (info.Index.Length + 8191) / 8192, chunk =>
|
||
{
|
||
int end = Math.Min(info.Index.Length, (chunk + 1) * 8192);
|
||
for (int k = chunk * 8192; k < end; k++)
|
||
{
|
||
int i = info.Index[k];
|
||
var px = data[i];
|
||
float a = px.A / 255f, r = px.R / 255f / a, g = px.G / 255f / a, b = px.B / 255f / a;
|
||
float max = info.Max[k], s = info.Sat[k], w = info.Weight[k];
|
||
var (nr, ng, nb) = Hsv(c.Hue, MathHelper.Clamp(s * c.Sat, 0, 1), MathHelper.Clamp(max * c.Val, 0, 1));
|
||
r += (nr - r) * w; g += (ng - g) * w; b += (nb - b) * w;
|
||
data[i] = new Color(r * a, g * a, b * a, a);
|
||
}
|
||
});
|
||
if (src.LevelCount > 1) t = MipTexture(data, src.Width, src.Height); // Figuren: Stufen behalten
|
||
else { t = new Texture2D(_gd, src.Width, src.Height); t.SetData(data); }
|
||
_painted[(src, colorIndex)] = t;
|
||
if (DevShot.Active && src.Width > 512) DevShot.Log($"timing: paint {src.Width}x{src.Height} color {colorIndex} in {sw.ElapsedMilliseconds} ms ({info.Index.Length} px)");
|
||
return t;
|
||
}
|
||
|
||
/// Je Quelle einmal: Pixel und welche davon Teamfarbe (Magenta) sind, mit Sättigung, Helligkeit, Gewicht.
|
||
public sealed record PaintInfo(Color[] Data, int[] Index, float[] Sat, float[] Max, float[] Weight);
|
||
|
||
/// Teamfarben-Daten vorab (auch im Hintergrund) und für eine Textur hinterlegen.
|
||
public static void RegisterPaintInfo(Texture2D t, PaintInfo info) { lock (_known) _paintInfo[t] = info; }
|
||
static readonly Dictionary<Texture2D, PaintInfo> _paintInfo = new();
|
||
|
||
static PaintInfo PaintInfoOf(Texture2D src)
|
||
{
|
||
lock (_known) if (_paintInfo.TryGetValue(src, out var info)) return info;
|
||
Color[]? known;
|
||
lock (_known) _known.TryGetValue(src, out known);
|
||
var data = known ?? new Color[src.Width * src.Height];
|
||
if (known == null) src.GetData(data);
|
||
var made = ComputePaintInfo(data);
|
||
lock (_known) _paintInfo[src] = made;
|
||
return made;
|
||
}
|
||
|
||
/// Welche Pixel Teamfarbe (Magenta) sind – reine Rechnung, auch im Hintergrund.
|
||
public static PaintInfo ComputePaintInfo(Color[] data)
|
||
{
|
||
// Gewicht je Pixel parallel, danach nur die Teamfarben-Pixel einsammeln
|
||
var wAll = new float[data.Length]; var sAll = new float[data.Length]; var mAll = new float[data.Length];
|
||
System.Threading.Tasks.Parallel.For(0, (data.Length + 16383) / 16384, chunk =>
|
||
{
|
||
for (int i = chunk * 16384, end = Math.Min(data.Length, (chunk + 1) * 16384); i < end; i++)
|
||
{
|
||
var px = data[i];
|
||
if (px.A == 0) continue;
|
||
float a = px.A / 255f, r = px.R / 255f / a, g = px.G / 255f / a, b = px.B / 255f / a;
|
||
float max = MathF.Max(r, MathF.Max(g, b)), min = MathF.Min(r, MathF.Min(g, b)), d = max - min;
|
||
if (max <= 0.08f || d <= 0.001f) continue;
|
||
float s = d / max;
|
||
float h = max == r ? 60 * (((g - b) / d) % 6) : max == g ? 60 * ((b - r) / d + 2) : 60 * ((r - g) / d + 4);
|
||
if (h < 0) h += 360;
|
||
float w = Smooth(48, 30, MathF.Abs(h - 312)) * Smooth(0.18f, 0.32f, s);
|
||
if (w > 0) { wAll[i] = w; sAll[i] = s; mAll[i] = max; }
|
||
}
|
||
});
|
||
var idx = new List<int>(); var sat = new List<float>(); var mx = new List<float>(); var wt = new List<float>();
|
||
for (int i = 0; i < data.Length; i++)
|
||
if (wAll[i] > 0) { idx.Add(i); sat.Add(sAll[i]); mx.Add(mAll[i]); wt.Add(wAll[i]); }
|
||
return new PaintInfo(data, idx.ToArray(), sat.ToArray(), mx.ToArray(), wt.ToArray());
|
||
}
|
||
|
||
/// Umfärben auf Pixeldaten (vormultipliziert) — auch im Hintergrund nutzbar.
|
||
public static void PaintPixels(Color[] data, int colorIndex)
|
||
{
|
||
var c = Appearance.Colors[colorIndex];
|
||
for (int i = 0; i < data.Length; i++)
|
||
{
|
||
var px = data[i];
|
||
if (px.A == 0) continue;
|
||
float a = px.A / 255f, r = px.R / 255f / a, g = px.G / 255f / a, b = px.B / 255f / a;
|
||
float max = MathF.Max(r, MathF.Max(g, b)), min = MathF.Min(r, MathF.Min(g, b)), d = max - min;
|
||
if (max <= 0.08f || d <= 0.001f) continue;
|
||
float s = d / max;
|
||
float h = max == r ? 60 * (((g - b) / d) % 6) : max == g ? 60 * ((b - r) / d + 2) : 60 * ((r - g) / d + 4);
|
||
if (h < 0) h += 360;
|
||
float dist = MathF.Abs(h - 312);
|
||
float w = Smooth(48, 30, dist) * Smooth(0.18f, 0.32f, s);
|
||
if (w <= 0) continue;
|
||
var (nr, ng, nb) = Hsv(c.Hue, MathHelper.Clamp(s * c.Sat, 0, 1), MathHelper.Clamp(max * c.Val, 0, 1));
|
||
r += (nr - r) * w; g += (ng - g) * w; b += (nb - b) * w;
|
||
data[i] = new Color(r * a, g * a, b * a, a);
|
||
}
|
||
}
|
||
|
||
/// 0 bei <paramref name="from"/>, 1 bei <paramref name="to"/> (auch absteigend), weich dazwischen.
|
||
static float Smooth(float from, float to, float x)
|
||
{
|
||
float k = MathHelper.Clamp((x - from) / (to - from), 0, 1);
|
||
return k * k * (3 - 2 * k);
|
||
}
|
||
|
||
static (float, float, float) Hsv(float h, float s, float v)
|
||
{
|
||
float c = v * s, x = c * (1 - MathF.Abs(h / 60 % 2 - 1)), m = v - c;
|
||
var (r, g, b) = h < 60 ? (c, x, 0f) : h < 120 ? (x, c, 0f) : h < 180 ? (0f, c, x) : h < 240 ? (0f, x, c) : h < 300 ? (x, 0f, c) : (c, 0f, x);
|
||
return (r + m, g + m, b + m);
|
||
}
|
||
|
||
public static bool Has(string name) => Sprite(name) != null;
|
||
|
||
public static IEnumerable<string> Existing(IEnumerable<string> names) => names.Where(Has);
|
||
}
|
||
}
|