Files

197 lines
9.0 KiB
C#
Raw Permalink Normal View History

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using StbImageSharp;
namespace GladiatorIdle.Gfx
{
/// <summary>
/// Video-Sprites, einmal je Sitzung geladen und von allen Szenen geteilt. Entpacken und
/// Umfärben laufen im Hintergrund (höchstens zwei Clips gleichzeitig); <see cref="Pump"/>
/// schiebt die fertigen Bilder mit festem Zeitbudget pro Bild auf die Grafikkarte — das Spiel
/// steht dabei nie. Bis ein Clip bereit ist, liefert <see cref="Get"/> null (dann Posen).
/// </summary>
internal static class ClipCache
{
public sealed class Clip
{
public Texture2D[] Frames = Array.Empty<Texture2D>();
public int Impact;
public int Last => Frames.Length - 1;
}
sealed class Job
{
public Color[][]? Pixels;
public int W, H, Impact, Uploaded;
public int FullW, FullH, X0, Y0; // Zuschnitt in der vollen Leinwand
public Texture2D[]? Textures;
public volatile bool Decoded;
public bool Missing, Ready;
public Clip? Clip;
}
static readonly Dictionary<string, Job> _jobs = new();
static readonly Dictionary<Texture2D, (Vector4 Crop, float Aspect)> _crops = new();
/// Zugeschnittenes Clip-Bild: Lage (x, y, Breite, Höhe; 0..1) in der vollen Leinwand und deren Seitenverhältnis.
public static (Vector4, float)? CropOf(Texture2D t) => _crops.TryGetValue(t, out var c) ? c : null;
static readonly SemaphoreSlim _workers = new(2);
static readonly Regex ImpactRx = new("\"impact\":\\s*(\\d+)");
/// Clip der Figur <paramref name="art"/> für die Aktion (null = fehlt oder lädt noch).
public static Clip? Get(string art, string action, int color)
{
string key = $"{art}|{action}|{color}";
if (!_jobs.TryGetValue(key, out var job))
{
job = new Job();
_jobs[key] = job;
string? dir = Assets.RootDir is string root ? Path.Combine(root, "Sprites", "anim") : null;
if (dir == null || !File.Exists(Path.Combine(dir, $"{art}_{action}_00.jpg"))) job.Missing = true;
else Task.Run(() => Decode(job, dir, art, action, color));
}
return job.Ready ? job.Clip : null;
}
/// Wan-Clip aus Assets/Video (&lt;name&gt;_NN.jpg, ohne Transparenz), im Hintergrund geladen.
public static Texture2D[]? Video(string name)
{
string key = "video|" + name;
if (!_jobs.TryGetValue(key, out var job))
{
job = new Job();
_jobs[key] = job;
string? dir = Assets.RootDir is string root ? Path.Combine(root, "Video") : null;
if (dir == null || !File.Exists(Path.Combine(dir, $"{name}_00.jpg"))) job.Missing = true;
else Task.Run(() => DecodeVideo(job, dir, name));
}
return job.Ready ? job.Clip!.Frames : null;
}
static void DecodeVideo(Job job, string dir, string name)
{
_workers.Wait();
try
{
var frames = new List<Color[]>();
for (int i = 0; i < 1000; i++)
{
string p = Path.Combine(dir, $"{name}_{i:D2}.jpg");
if (!File.Exists(p)) break;
var rgb = ImageResult.FromMemory(File.ReadAllBytes(p), ColorComponents.RedGreenBlue);
var px = new Color[rgb.Width * rgb.Height];
for (int k = 0; k < px.Length; k++) px[k] = new Color(rgb.Data[k * 3], rgb.Data[k * 3 + 1], rgb.Data[k * 3 + 2], (byte)255);
frames.Add(px);
job.W = rgb.Width; job.H = rgb.Height;
}
job.Pixels = frames.ToArray();
job.Missing = frames.Count < 2;
}
catch (Exception ex) { job.Missing = true; DevShot.Log("video load failed " + name + ": " + ex.Message); }
finally { job.Decoded = true; _workers.Release(); }
}
/// Nur nachsehen, ob es den Clip gibt (ohne Laden).
public static bool Exists(string art, string action) =>
Assets.RootDir is string root && File.Exists(Path.Combine(root, "Sprites", "anim", $"{art}_{action}_00.jpg"));
static void Decode(Job job, string dir, string art, string action, int color)
{
_workers.Wait();
try
{
var frames = new List<Color[]>();
for (int i = 0; i < 100; i++)
{
string b = Path.Combine(dir, $"{art}_{action}_{i:D2}");
if (!File.Exists(b + ".jpg") || !File.Exists(b + "_a.png")) break;
var rgb = ImageResult.FromMemory(File.ReadAllBytes(b + ".jpg"), ColorComponents.RedGreenBlue);
var mask = ImageResult.FromMemory(File.ReadAllBytes(b + "_a.png"), ColorComponents.Grey);
var px = new Color[rgb.Width * rgb.Height];
int n = Math.Min(px.Length, mask.Data.Length);
// Farbe liegt vor Schwarz (schon vormultipliziert), Deckkraft aus der Maske
for (int k = 0; k < n; k++)
px[k] = new Color(rgb.Data[k * 3], rgb.Data[k * 3 + 1], rgb.Data[k * 3 + 2], mask.Data[k]);
if (color >= 0) Assets.PaintPixels(px, color);
frames.Add(px);
job.W = rgb.Width; job.H = rgb.Height;
}
Crop(job, frames);
job.Impact = Math.Max(3, frames.Count / 3);
string meta = Path.Combine(dir, $"{art}_{action}.json");
if (File.Exists(meta) && ImpactRx.Match(File.ReadAllText(meta)) is { Success: true } m)
job.Impact = Math.Clamp(int.Parse(m.Groups[1].Value), 3, Math.Max(3, frames.Count - 1));
job.Pixels = frames.ToArray();
job.Missing = frames.Count < 2;
}
catch (Exception ex) { job.Missing = true; DevShot.Log("clip load failed " + art + " " + action + ": " + ex.Message); }
finally
{
job.Decoded = true;
_workers.Release();
}
}
/// Auf den Bereich zuschneiden, den die Figur in irgendeinem Bild des Clips berührt (+ Rand).
static void Crop(Job job, List<Color[]> frames)
{
int w = job.W, h = job.H, x0 = w, y0 = h, x1 = -1, y1 = -1;
foreach (var px in frames)
for (int y = 0; y < h; y++)
{
int row = y * w;
for (int x = 0; x < w; x++)
if (px[row + x].A > 8)
{
if (x < x0) x0 = x; if (x > x1) x1 = x;
if (y < y0) y0 = y; if (y > y1) y1 = y;
}
}
if (x1 < 0) return;
const int PAD = 4;
x0 = Math.Max(0, x0 - PAD); y0 = Math.Max(0, y0 - PAD);
x1 = Math.Min(w - 1, x1 + PAD); y1 = Math.Min(h - 1, y1 + PAD);
int cw = x1 - x0 + 1, ch = y1 - y0 + 1;
for (int f = 0; f < frames.Count; f++)
{
var src = frames[f];
var dst = new Color[cw * ch];
for (int y = 0; y < ch; y++) Array.Copy(src, (y + y0) * w + x0, dst, y * cw, cw);
frames[f] = dst;
}
job.FullW = w; job.FullH = h; job.X0 = x0; job.Y0 = y0; job.W = cw; job.H = ch;
}
/// Fertig entpackte Bilder hochladen, bis das Zeitbudget verbraucht ist (Hauptthread).
public static void Pump(GraphicsDevice gd, double budgetMs)
{
var sw = Stopwatch.StartNew();
foreach (var job in _jobs.Values)
{
if (job.Ready || job.Missing || !job.Decoded || job.Pixels == null) continue;
job.Textures ??= new Texture2D[job.Pixels.Length];
while (job.Uploaded < job.Pixels.Length)
{
var t = new Texture2D(gd, job.W, job.H);
t.SetData(job.Pixels[job.Uploaded]);
if (job.FullW > 0)
_crops[t] = (new Vector4((float)job.X0 / job.FullW, (float)job.Y0 / job.FullH,
(float)job.W / job.FullW, (float)job.H / job.FullH), (float)job.FullW / job.FullH);
job.Textures[job.Uploaded++] = t;
if (sw.Elapsed.TotalMilliseconds > budgetMs) return;
}
job.Clip = new Clip { Frames = job.Textures, Impact = job.Impact };
job.Pixels = null; // Speicher frei
job.Ready = true;
}
}
}
}