Gladiator Idle (MonoGame) – Spiel mit 3D-Gladiatoren
Nur was zum Bauen und Starten nötig ist: Mono/ (Spiel), Game/, Core/, Languages/, Assets/ (Bilder, Clips, 3D-Figuren, Ton), build-release.bat. Bauen: build-release.bat → Spiel\GladiatorIdle.exe Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
210
Mono/Gfx/Assets.cs
Normal file
210
Mono/Gfx/Assets.cs
Normal file
@@ -0,0 +1,210 @@
|
||||
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;
|
||||
}
|
||||
|
||||
/// 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 data = new Color[src.Width * src.Height];
|
||||
src.GetData(data);
|
||||
PaintPixels(data, colorIndex);
|
||||
t = new Texture2D(_gd, src.Width, src.Height);
|
||||
t.SetData(data);
|
||||
_painted[(src, colorIndex)] = t;
|
||||
return t;
|
||||
}
|
||||
|
||||
/// 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);
|
||||
}
|
||||
}
|
||||
196
Mono/Gfx/ClipCache.cs
Normal file
196
Mono/Gfx/ClipCache.cs
Normal file
@@ -0,0 +1,196 @@
|
||||
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 (<name>_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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
78
Mono/Gfx/Draw.cs
Normal file
78
Mono/Gfx/Draw.cs
Normal file
@@ -0,0 +1,78 @@
|
||||
using System;
|
||||
using FontStashSharp;
|
||||
using Microsoft.Xna.Framework;
|
||||
using Microsoft.Xna.Framework.Graphics;
|
||||
|
||||
namespace GladiatorIdle.Gfx
|
||||
{
|
||||
internal enum Align { Left, Center, Right }
|
||||
|
||||
/// <summary>
|
||||
/// Zeichenhilfen in Design-Pixeln (1920×1080). Schrift wird in Bildschirmgröße gerastert
|
||||
/// (<see cref="UiScale"/>) und verkleinert gezeichnet — scharf auch in 4K.
|
||||
/// </summary>
|
||||
internal static class Draw
|
||||
{
|
||||
public static float UiScale = 1f;
|
||||
|
||||
public static readonly Color Gold = new(236, 190, 84), Sand = new(222, 196, 150), Dim = new(150, 128, 98),
|
||||
Red = new(200, 64, 52), Green = new(110, 190, 90), Blue = new(110, 160, 220), Purple = new(170, 130, 220),
|
||||
Panel = new(24, 18, 12), Border = new(110, 82, 46);
|
||||
|
||||
public static Color A(Color c, float alpha) => c * MathHelper.Clamp(alpha, 0, 1);
|
||||
|
||||
public static void Rect(SpriteBatch sb, RectangleF r, Color c) =>
|
||||
sb.Draw(Assets.Pixel, new Vector2(r.X, r.Y), null, c, 0, Vector2.Zero, new Vector2(r.Width, r.Height), SpriteEffects.None, 0);
|
||||
|
||||
public static void Frame(SpriteBatch sb, RectangleF r, Color c, float t = 2)
|
||||
{
|
||||
Rect(sb, new RectangleF(r.X, r.Y, r.Width, t), c);
|
||||
Rect(sb, new RectangleF(r.X, r.Bottom - t, r.Width, t), c);
|
||||
Rect(sb, new RectangleF(r.X, r.Y, t, r.Height), c);
|
||||
Rect(sb, new RectangleF(r.Right - t, r.Y, t, r.Height), c);
|
||||
}
|
||||
|
||||
public static void Glow(SpriteBatch sb, Vector2 center, Vector2 size, Color c) =>
|
||||
sb.Draw(Assets.Soft, center, null, c, 0, new Vector2(64, 64), size / 128f, SpriteEffects.None, 0);
|
||||
|
||||
public static Vector2 Measure(FontSystem fs, float px, string text) =>
|
||||
fs.GetFont(px * UiScale).MeasureString(text) / UiScale;
|
||||
|
||||
/// Text an <paramref name="pos"/> (y = Mitte der Zeile), mit weichem Schatten.
|
||||
public static void Text(SpriteBatch sb, FontSystem fs, float px, string text, Vector2 pos, Color c,
|
||||
Align align = Align.Left, float scale = 1f, bool shadow = true)
|
||||
{
|
||||
// feste Rastergröße (ganze Pixel), Animation nur über die Zeichen-Skalierung —
|
||||
// sonst entstehen jedes Bild neue Glyphen
|
||||
var font = fs.GetFont(MathF.Max(4, MathF.Round(px * UiScale)));
|
||||
var size = font.MeasureString(text) / UiScale * scale;
|
||||
float x = align switch { Align.Center => pos.X - size.X / 2, Align.Right => pos.X - size.X, _ => pos.X };
|
||||
var p = new Vector2(x, pos.Y - size.Y / 2);
|
||||
var s = new Vector2(scale / UiScale);
|
||||
if (shadow) font.DrawText(sb, text, p + new Vector2(2, 3) * scale, Color.Black * (c.A / 255f * 0.6f), scale: s);
|
||||
font.DrawText(sb, text, p, c, scale: s);
|
||||
}
|
||||
|
||||
/// Balken mit verzögertem Rest (weißer Abschnitt zeigt den gerade verlorenen Teil).
|
||||
public static void Bar(SpriteBatch sb, RectangleF r, float value, float lag, Color c, bool fromRight = false)
|
||||
{
|
||||
Rect(sb, r, new Color(12, 8, 5) * 0.85f);
|
||||
value = MathHelper.Clamp(value, 0, 1); lag = MathHelper.Clamp(lag, value, 1);
|
||||
RectangleF Part(float a, float b) => fromRight
|
||||
? new RectangleF(r.Right - 3 - (r.Width - 6) * b, r.Y + 3, (r.Width - 6) * (b - a), r.Height - 6)
|
||||
: new RectangleF(r.X + 3 + (r.Width - 6) * a, r.Y + 3, (r.Width - 6) * (b - a), r.Height - 6);
|
||||
Rect(sb, Part(value, lag), new Color(255, 240, 220));
|
||||
Rect(sb, Part(0, value), c);
|
||||
Rect(sb, new RectangleF(r.X + 3, r.Y + 3, r.Width - 6, (r.Height - 6) * 0.35f), Color.White * 0.12f);
|
||||
Frame(sb, r, Border);
|
||||
}
|
||||
}
|
||||
|
||||
internal readonly record struct RectangleF(float X, float Y, float Width, float Height)
|
||||
{
|
||||
public float Right => X + Width;
|
||||
public float Bottom => Y + Height;
|
||||
public Vector2 Center => new(X + Width / 2, Y + Height / 2);
|
||||
public bool Contains(Vector2 p) => p.X >= X && p.X < Right && p.Y >= Y && p.Y < Bottom;
|
||||
}
|
||||
}
|
||||
604
Mono/Gfx/Model3D.cs
Normal file
604
Mono/Gfx/Model3D.cs
Normal file
@@ -0,0 +1,604 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using Microsoft.Xna.Framework;
|
||||
using Microsoft.Xna.Framework.Graphics;
|
||||
|
||||
namespace GladiatorIdle.Gfx
|
||||
{
|
||||
/// Punkt mit Lage, Normale und Farbe (BasicEffect mit Licht und Punktfarben).
|
||||
internal struct VertexPNC : IVertexType
|
||||
{
|
||||
public Vector3 Position, Normal;
|
||||
public Color Color;
|
||||
public static readonly VertexDeclaration Decl = new(
|
||||
new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0),
|
||||
new VertexElement(12, VertexElementFormat.Vector3, VertexElementUsage.Normal, 0),
|
||||
new VertexElement(24, VertexElementFormat.Color, VertexElementUsage.Color, 0));
|
||||
VertexDeclaration IVertexType.VertexDeclaration => Decl;
|
||||
}
|
||||
|
||||
/// Wie <see cref="VertexPNC"/>, dazu Texturkoordinaten (Figuren mit Textur, z. B. aus Meshy).
|
||||
internal struct VertexPNCT : IVertexType
|
||||
{
|
||||
public Vector3 Position, Normal;
|
||||
public Color Color;
|
||||
public Vector2 Uv;
|
||||
public static readonly VertexDeclaration Decl = new(
|
||||
new VertexElement(0, VertexElementFormat.Vector3, VertexElementUsage.Position, 0),
|
||||
new VertexElement(12, VertexElementFormat.Vector3, VertexElementUsage.Normal, 0),
|
||||
new VertexElement(24, VertexElementFormat.Color, VertexElementUsage.Color, 0),
|
||||
new VertexElement(28, VertexElementFormat.Vector2, VertexElementUsage.TextureCoordinate, 0));
|
||||
VertexDeclaration IVertexType.VertexDeclaration => Decl;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 3D-Figur mit Skelett aus einer .gim-Datei (fbx2gim aus _Tools/ModelTools: Mixamo-Figur +
|
||||
/// Bewegungen). Die Verformung rechnet der Prozessor (wenige zehntausend Punkte), Clips werden
|
||||
/// beim Wechsel kurz überblendet. Teamfarbe: Magenta-Punkte wie bei den Sprites umgefärbt.
|
||||
/// </summary>
|
||||
internal sealed class Model3D
|
||||
{
|
||||
public sealed class Clip { public string Name = ""; public float Fps; public int Frames; public float[] Data = null!; public float Length => (Frames - 1) / Fps; }
|
||||
|
||||
readonly string[] _names;
|
||||
readonly int[] _parent;
|
||||
readonly float[] _rest; // 10 je Knochen
|
||||
readonly Matrix[] _offset;
|
||||
readonly Vector3[] _pos, _nrm;
|
||||
readonly Color[] _baseCol;
|
||||
readonly byte[] _bi;
|
||||
readonly float[] _bw;
|
||||
public readonly int[] Indices;
|
||||
public readonly List<Clip> Clips = new();
|
||||
public readonly VertexPNCT[] Vertices;
|
||||
public BoundingBox Bounds { get; }
|
||||
readonly Texture2D? _texture;
|
||||
Texture2D? _painted;
|
||||
/// Maßstab: Modell-Einheiten je Zentimeter (Mixamo-Figuren gibt es in cm und in m).
|
||||
public readonly float Unit;
|
||||
|
||||
readonly float[] _pose, _from; // aktuelle und überblendete Haltung (10 je Knochen)
|
||||
readonly Matrix[] _global, _skin;
|
||||
int _color = -1;
|
||||
|
||||
public int BoneCount => _names.Length;
|
||||
|
||||
public static Model3D? Load(string name) => Load(Assets.Device, name);
|
||||
|
||||
public static Model3D? Load(GraphicsDevice gd, string name)
|
||||
{
|
||||
string? path = Assets.RootDir is string root ? Path.Combine(root, "Models", name + ".gim") : null;
|
||||
return path != null && File.Exists(path) ? new Model3D(gd, path) : null;
|
||||
}
|
||||
|
||||
Model3D(GraphicsDevice gd, string path)
|
||||
{
|
||||
using var r = new BinaryReader(File.OpenRead(path), Encoding.UTF8);
|
||||
string magic = Encoding.ASCII.GetString(r.ReadBytes(4));
|
||||
if (magic != "GIM1" && magic != "GIM2") throw new InvalidDataException(path);
|
||||
bool v2 = magic == "GIM2";
|
||||
var uv = new List<Vector2>();
|
||||
int nb = r.ReadInt32();
|
||||
_names = new string[nb]; _parent = new int[nb]; _rest = new float[nb * 10]; _offset = new Matrix[nb];
|
||||
for (int b = 0; b < nb; b++)
|
||||
{
|
||||
_names[b] = r.ReadString(); _parent[b] = r.ReadInt32();
|
||||
for (int k = 0; k < 10; k++) _rest[b * 10 + k] = r.ReadSingle();
|
||||
r.ReadByte();
|
||||
var m = new float[16];
|
||||
for (int k = 0; k < 16; k++) m[k] = r.ReadSingle();
|
||||
_offset[b] = new Matrix(m[0], m[1], m[2], m[3], m[4], m[5], m[6], m[7], m[8], m[9], m[10], m[11], m[12], m[13], m[14], m[15]);
|
||||
}
|
||||
int nv = r.ReadInt32();
|
||||
_pos = new Vector3[nv]; _nrm = new Vector3[nv]; _baseCol = new Color[nv]; _bi = new byte[nv * 4]; _bw = new float[nv * 4];
|
||||
for (int i = 0; i < nv; i++)
|
||||
{
|
||||
_pos[i] = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle());
|
||||
_nrm[i] = new Vector3(r.ReadSingle(), r.ReadSingle(), r.ReadSingle());
|
||||
uv.Add(v2 ? new Vector2(r.ReadSingle(), r.ReadSingle()) : Vector2.Zero);
|
||||
var c = r.ReadBytes(4); _baseCol[i] = new Color(c[0], c[1], c[2], c[3]);
|
||||
r.Read(_bi, i * 4, 4);
|
||||
for (int k = 0; k < 4; k++) _bw[i * 4 + k] = r.ReadSingle();
|
||||
}
|
||||
Indices = new int[r.ReadInt32()];
|
||||
for (int i = 0; i < Indices.Length; i++) Indices[i] = r.ReadInt32();
|
||||
int nc = r.ReadInt32();
|
||||
for (int c = 0; c < nc; c++)
|
||||
{
|
||||
var clip = new Clip { Name = r.ReadString(), Fps = r.ReadSingle(), Frames = r.ReadInt32() };
|
||||
clip.Data = new float[clip.Frames * nb * 10];
|
||||
for (int k = 0; k < clip.Data.Length; k++) clip.Data[k] = r.ReadSingle();
|
||||
Clips.Add(clip);
|
||||
}
|
||||
if (v2 && r.ReadInt32() is int texLen && texLen > 0)
|
||||
using (var ms = new MemoryStream(r.ReadBytes(texLen))) _texture = Texture2D.FromStream(gd, ms);
|
||||
Vertices = new VertexPNCT[nv];
|
||||
for (int i = 0; i < nv; i++) Vertices[i] = new VertexPNCT { Position = _pos[i], Normal = _nrm[i], Color = _baseCol[i], Uv = uv[i] };
|
||||
Bounds = BoundingBox.CreateFromPoints(_pos);
|
||||
_pose = (float[])_rest.Clone(); _from = (float[])_rest.Clone();
|
||||
_global = new Matrix[nb]; _skin = new Matrix[nb];
|
||||
// Kopf bis Knöchel etwa 150 cm bei einer 180-cm-Figur
|
||||
int head = Bone("Head"), foot = Bone("LeftFoot");
|
||||
Unit = head >= 0 && foot >= 0 ? Vector3.Distance(BindGlobal(head).Translation, BindGlobal(foot).Translation) / 150f : 1f;
|
||||
}
|
||||
|
||||
public Clip? Find(string name) => Clips.Find(c => c.Name == name);
|
||||
|
||||
/// Teamfarbe (Index in Appearance.Colors), -1 = Originalfarben.
|
||||
public void SetColor(int index)
|
||||
{
|
||||
if (index == _color) return;
|
||||
_color = index;
|
||||
var cols = (Color[])_baseCol.Clone();
|
||||
if (index >= 0) Assets.PaintPixels(cols, index);
|
||||
for (int i = 0; i < cols.Length; i++) Vertices[i].Color = cols[i];
|
||||
_dirty = true;
|
||||
if (_texture != null) _painted = index >= 0 ? Assets.Paint(_texture, index) : _texture;
|
||||
foreach (var p in Props)
|
||||
{
|
||||
var pc = (Color[])p.Base.Clone();
|
||||
if (index >= 0) Assets.PaintPixels(pc, index);
|
||||
for (int i = 0; i < pc.Length; i++) p.V[i].Color = pc[i];
|
||||
}
|
||||
}
|
||||
|
||||
/// Überblendung beginnen: die jetzige Haltung wird zum Ausgangspunkt.
|
||||
public void BeginBlend() { if (_posed) Array.Copy(_pose, _from, _pose.Length); }
|
||||
bool _posed; // erst nach der ersten Haltung überblenden (die Ruhehaltung der Figurdatei kann andere Einheiten haben)
|
||||
|
||||
/// Haltung aus einem Clip zur Zeit t; blend 0..1 mischt von der gemerkten Haltung her.
|
||||
/// inPlace hält die Hüfte waagerecht am Platz (Laufen auf der Stelle).
|
||||
public void Pose(Clip clip, float t, bool loop, float blend = 1, bool inPlace = true, bool skin = true, float rootY = 1)
|
||||
{
|
||||
int nb = _names.Length;
|
||||
if (!_posed) { blend = 1; _posed = true; }
|
||||
float f = t * clip.Fps;
|
||||
f = loop ? f % (clip.Frames - 1) : Math.Min(f, clip.Frames - 1);
|
||||
if (f < 0) f += clip.Frames - 1;
|
||||
int a = (int)f, b = Math.Min(a + 1, clip.Frames - 1);
|
||||
float k = f - a;
|
||||
for (int bone = 0; bone < nb; bone++)
|
||||
{
|
||||
int pa = (a * nb + bone) * 10, pb = (b * nb + bone) * 10, o = bone * 10;
|
||||
var tr = Vector3.Lerp(V(clip.Data, pa), V(clip.Data, pb), k);
|
||||
var q = Quaternion.Slerp(Q(clip.Data, pa), Q(clip.Data, pb), k);
|
||||
if (inPlace && _parent[bone] < 0) { var r0 = V(clip.Data, bone * 10); tr.X = r0.X; tr.Z = r0.Z; tr.Y = r0.Y + (tr.Y - r0.Y) * rootY; } // rootY: Sprunghöhe
|
||||
if (blend < 1)
|
||||
{
|
||||
tr = Vector3.Lerp(V(_from, o), tr, blend);
|
||||
q = Quaternion.Slerp(Q(_from, o), q, blend);
|
||||
}
|
||||
_pose[o] = tr.X; _pose[o + 1] = tr.Y; _pose[o + 2] = tr.Z;
|
||||
_pose[o + 3] = q.X; _pose[o + 4] = q.Y; _pose[o + 5] = q.Z; _pose[o + 6] = q.W;
|
||||
_pose[o + 7] = clip.Data[pa + 7]; _pose[o + 8] = clip.Data[pa + 8]; _pose[o + 9] = clip.Data[pa + 9];
|
||||
}
|
||||
Bones();
|
||||
if (skin) { SkinVertices(); _dirty = true; AvoidBody(); }
|
||||
}
|
||||
|
||||
/// Trefferzeitpunkt eines Schlag-Clips: der Schwertarm am weitesten vorn (Blickrichtung +Z).
|
||||
public float ImpactTime(Clip clip)
|
||||
{
|
||||
if (_impact.TryGetValue(clip, out float t)) return t;
|
||||
var keep = (float[])_pose.Clone(); bool posed = _posed;
|
||||
int hand = Bone("RightHand");
|
||||
float best = float.MinValue; t = clip.Length * 0.5f;
|
||||
for (int f = 0; f < clip.Frames && hand >= 0; f++)
|
||||
{
|
||||
_posed = true;
|
||||
Pose(clip, f / clip.Fps, false, 1, true, skin: false);
|
||||
float z = _global[hand].Translation.Z;
|
||||
if (z > best) { best = z; t = f / clip.Fps; }
|
||||
}
|
||||
Array.Copy(keep, _pose, keep.Length); _posed = posed; Bones();
|
||||
return _impact[clip] = t;
|
||||
}
|
||||
readonly Dictionary<Clip, float> _impact = new();
|
||||
|
||||
/// Figur auf 180 Einheiten Höhe, Füße auf y = 0, mittig (aus der jetzigen Haltung, robust gegen Ausreißer).
|
||||
public Matrix FitNow()
|
||||
{
|
||||
float Q(Func<Vector3, float> axis, float q)
|
||||
{
|
||||
var a = Array.ConvertAll(Vertices, v => axis(v.Position));
|
||||
Array.Sort(a);
|
||||
return a[(int)(q * (a.Length - 1))];
|
||||
}
|
||||
float y0 = Q(p => p.Y, 0.002f), y1 = Q(p => p.Y, 0.998f);
|
||||
float cx = (Q(p => p.X, 0.01f) + Q(p => p.X, 0.99f)) / 2, cz = (Q(p => p.Z, 0.01f) + Q(p => p.Z, 0.99f)) / 2;
|
||||
return Matrix.CreateTranslation(-cx, -y0, -cz) * Matrix.CreateScale(180 / MathF.Max(1e-3f, y1 - y0));
|
||||
}
|
||||
|
||||
static Vector3 V(float[] d, int o) => new(d[o], d[o + 1], d[o + 2]);
|
||||
static Quaternion Q(float[] d, int o) => new(d[o + 3], d[o + 4], d[o + 5], d[o + 6]);
|
||||
|
||||
void Bones()
|
||||
{
|
||||
for (int b = 0; b < _names.Length; b++)
|
||||
{
|
||||
int o = b * 10;
|
||||
var local = Matrix.CreateScale(_pose[o + 7], _pose[o + 8], _pose[o + 9]) * Matrix.CreateFromQuaternion(Q(_pose, o)) * Matrix.CreateTranslation(V(_pose, o));
|
||||
_global[b] = _parent[b] >= 0 ? local * _global[_parent[b]] : local; // Eltern stehen vorher
|
||||
_skin[b] = _offset[b] * _global[b];
|
||||
}
|
||||
}
|
||||
|
||||
void SkinVertices()
|
||||
{
|
||||
System.Threading.Tasks.Parallel.For(0, (_pos.Length + 4095) / 4096, chunk =>
|
||||
{
|
||||
for (int i = chunk * 4096, end = Math.Min(_pos.Length, i + 4096); i < end; i++)
|
||||
{
|
||||
Vector3 p = Vector3.Zero, n = Vector3.Zero;
|
||||
for (int k = 0; k < 4; k++)
|
||||
{
|
||||
float w = _bw[i * 4 + k];
|
||||
if (w <= 0) continue;
|
||||
ref var m = ref _skin[_bi[i * 4 + k]];
|
||||
p += Vector3.Transform(_pos[i], m) * w;
|
||||
n += Vector3.TransformNormal(_nrm[i], m) * w;
|
||||
}
|
||||
Vertices[i].Position = p;
|
||||
Vertices[i].Normal = n;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// aura: nur Umriss in der Farbe des Effekts (additiv, ohne Tiefe), für Leuchten hinter der Figur.
|
||||
IndexBuffer? _ib;
|
||||
DynamicVertexBuffer? _vb;
|
||||
bool _dirty;
|
||||
|
||||
public void Draw(GraphicsDevice gd, BasicEffect fx, bool aura = false)
|
||||
{
|
||||
gd.DepthStencilState = aura ? DepthStencilState.None : DepthStencilState.Default;
|
||||
gd.BlendState = aura ? BlendState.Additive : BlendState.Opaque;
|
||||
gd.RasterizerState = RasterizerState.CullNone;
|
||||
fx.TextureEnabled = _texture != null && !aura;
|
||||
fx.Texture = _painted ?? _texture;
|
||||
// Indizes liegen einmal auf der Grafikkarte, Punkte nur nach einer neuen Haltung neu
|
||||
if (_ib == null)
|
||||
{
|
||||
_ib = new IndexBuffer(gd, IndexElementSize.ThirtyTwoBits, Indices.Length, BufferUsage.WriteOnly);
|
||||
_ib.SetData(Indices);
|
||||
_vb = new DynamicVertexBuffer(gd, VertexPNCT.Decl, Vertices.Length, BufferUsage.WriteOnly);
|
||||
_dirty = true;
|
||||
}
|
||||
if (_dirty || _vb!.IsContentLost) { _vb!.SetData(Vertices, 0, Vertices.Length, SetDataOptions.Discard); _dirty = false; }
|
||||
gd.SetVertexBuffer(_vb);
|
||||
gd.Indices = _ib;
|
||||
foreach (var pass in fx.CurrentTechnique.Passes)
|
||||
{
|
||||
pass.Apply();
|
||||
gd.SamplerStates[0] = SamplerState.LinearClamp;
|
||||
gd.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, Indices.Length / 3);
|
||||
}
|
||||
fx.TextureEnabled = false;
|
||||
var world = fx.World;
|
||||
foreach (var p in Props)
|
||||
{
|
||||
fx.World = p.Local * _global[p.Bone] * p.Correction * world;
|
||||
foreach (var pass in fx.CurrentTechnique.Passes)
|
||||
{
|
||||
pass.Apply();
|
||||
gd.DrawUserIndexedPrimitives(PrimitiveType.TriangleList, p.V, 0, p.V.Length, p.I, 0, p.I.Length / 3);
|
||||
}
|
||||
}
|
||||
fx.World = world;
|
||||
}
|
||||
|
||||
// ── Waffen: einfache Formen, an einem Handknochen befestigt ──────────
|
||||
|
||||
public sealed class Prop
|
||||
{
|
||||
public int Bone; public Matrix Local;
|
||||
public bool Shield; public float Height, Width, Bend, Length; // Maße in cm (Schild: Höhe x, Breite y; Klinge: Länge entlang x)
|
||||
public Matrix Correction = Matrix.Identity; // Ausweichen vor dem eigenen Körper (Modell-Raum)
|
||||
public float Push, Angle; public Vector3 Axis = Vector3.Up;
|
||||
public VertexPNC[] V = Array.Empty<VertexPNC>(); public int[] I = Array.Empty<int>(); public Color[] Base = Array.Empty<Color>();
|
||||
}
|
||||
public readonly List<Prop> Props = new();
|
||||
|
||||
public int Bone(string name) => Array.FindIndex(_names, n => n == "mixamorig:" + name || n == name);
|
||||
|
||||
/// Lage eines Knochens in der Ruhehaltung (Netz-Raum).
|
||||
Matrix BindGlobal(int b) => Matrix.Invert(_offset[b]);
|
||||
Vector3 BindPos(string bone)
|
||||
{
|
||||
int b = Bone(bone);
|
||||
if (b >= 0) return BindGlobal(b).Translation;
|
||||
// Skelett ohne Finger (Mixamo mit kleinerer Skelettstufe): Fingerpunkte aus einem Rahmen, den das
|
||||
// Skelett selbst liefert (Unterarm, oben = Hüfte zum Kopf, seitlich), mit Werten gemittelt aus vier
|
||||
// vollständigen Figuren (Längen in cm bei 25 cm Unterarm). Unabhängig davon, wie die Figur im
|
||||
// Raum liegt (Meshy-Figuren sind in der Grundhaltung z-oben).
|
||||
string side = bone.StartsWith("Left") ? "Left" : "Right";
|
||||
int hand = Bone(side + "Hand"), fore = Bone(side + "ForeArm"), hips = Bone("Hips"), head = Bone("Head");
|
||||
if (hand < 0 || fore < 0 || hips < 0 || head < 0) return Vector3.Zero;
|
||||
var h = BindGlobal(hand).Translation;
|
||||
float cm = Vector3.Distance(h, BindGlobal(fore).Translation) / 25.25f;
|
||||
var a = Vector3.Normalize(h - BindGlobal(fore).Translation);
|
||||
var up = BindGlobal(head).Translation - BindGlobal(hips).Translation;
|
||||
var u = Vector3.Normalize(up - a * Vector3.Dot(up, a));
|
||||
var sd = Vector3.Cross(a, u);
|
||||
float sg = side == "Right" ? -1 : 1;
|
||||
Vector3 F(float x, float y, float z) => a * x + u * y + sd * (z * sg);
|
||||
var across = Vector3.Normalize(F(0.2f, 0.57f, 0.77f));
|
||||
var mid = h + F(13.8f, 1.4f, 0) * cm;
|
||||
return bone[side.Length..] switch
|
||||
{
|
||||
"HandMiddle1" => mid,
|
||||
"HandIndex1" => mid + across * 3.6f * cm,
|
||||
"HandPinky1" => mid - across * 3.5f * cm,
|
||||
"HandThumb1" => h + F(3.9f, -0.4f, 2.5f) * cm,
|
||||
_ => h
|
||||
};
|
||||
}
|
||||
|
||||
/// Rahmen in der Ruhehaltung (Achsen x, y, z, Ursprung) → lokal zum Knochen.
|
||||
Matrix Attach(int bone, Vector3 x, Vector3 y, Vector3 origin)
|
||||
{
|
||||
x.Normalize(); var z = Vector3.Normalize(Vector3.Cross(x, y)); y = Vector3.Cross(z, x);
|
||||
var frame = new Matrix(x.X, x.Y, x.Z, 0, y.X, y.Y, y.Z, 0, z.X, z.Y, z.Z, 0, origin.X, origin.Y, origin.Z, 1);
|
||||
return frame * _offset[bone]; // Rahmen · (Knochen in Ruhe)⁻¹
|
||||
}
|
||||
|
||||
/// Gladius in der Faust (Knochen-Präfix "Right"/"Left"). Klinge zeigt vom kleinen Finger zum Zeigefinger.
|
||||
public void AddSword(string side = "Right")
|
||||
{
|
||||
var h = BindPos(side + "Hand"); var m = BindPos(side + "HandMiddle1");
|
||||
var ix = BindPos(side + "HandIndex1"); var pk = BindPos(side + "HandPinky1"); var th = BindPos(side + "HandThumb1");
|
||||
var finger = Vector3.Normalize(m - h);
|
||||
var blade = Vector3.Normalize(ix - pk);
|
||||
var palm = Vector3.Normalize(Vector3.Cross(finger, blade));
|
||||
if (Vector3.Dot(palm, th - h) < 0) palm = -palm;
|
||||
var grip = h + (m - h) * 0.75f + palm * 2.5f * Unit;
|
||||
var b = new MeshBuilder();
|
||||
var steel = new Color(196, 200, 206); var brass = new Color(176, 136, 62); var wood = new Color(92, 58, 34);
|
||||
b.Box(new Vector3(-9, 0, 0), new Vector3(1.5f, 3.6f, 3.6f), brass); // Knauf
|
||||
b.Box(new Vector3(-3.5f, 0, 0), new Vector3(10, 3, 3), wood); // Griff
|
||||
b.Box(new Vector3(2.2f, 0, 0), new Vector3(1.6f, 4, 11), brass); // Parierstange
|
||||
b.Box(new Vector3(30, 0, 0), new Vector3(54, 0.8f, 5.2f), steel); // Klinge
|
||||
b.Box(new Vector3(60, 0, 0), new Vector3(6, 0.7f, 2.6f), steel); // Spitze
|
||||
var sword = b.Build(Bone(side + "Hand"), Matrix.CreateScale(Unit) * Attach(Bone(side + "Hand"), blade, palm, grip));
|
||||
sword.Length = 63;
|
||||
Props.Add(sword);
|
||||
}
|
||||
|
||||
/// Gewölbter Schild (Scutum) am Unterarm, Bemalung in Magenta (Teamfarbe), Bronzerand und Buckel.
|
||||
public void AddShield(string side = "Left")
|
||||
{
|
||||
var fa = BindPos(side + "ForeArm"); var h = BindPos(side + "Hand");
|
||||
var m = BindPos(side + "HandMiddle1"); var ix = BindPos(side + "HandIndex1"); var pk = BindPos(side + "HandPinky1"); var th = BindPos(side + "HandThumb1");
|
||||
var arm = Vector3.Normalize(h - fa);
|
||||
var across = Vector3.Normalize(ix - pk);
|
||||
var palm = Vector3.Normalize(Vector3.Cross(Vector3.Normalize(m - h), across));
|
||||
if (Vector3.Dot(palm, th - h) < 0) palm = -palm;
|
||||
// Scutum mit Quergriff: die Faust hält den Griff (kleiner Finger → Zeigefinger), die Knöchel
|
||||
// zeigen zum Schild; der Schild steht senkrecht zum Griff
|
||||
var knuckles = Vector3.Normalize(m - h);
|
||||
var centre = m + knuckles * 7 * Unit;
|
||||
var b = new MeshBuilder();
|
||||
var face = new Color(190, 30, 160); var rim = new Color(150, 112, 52); var boss = new Color(182, 150, 80);
|
||||
const float W = 50, H = 72, BEND = 0.011f;
|
||||
// x: Länge (entlang des Arms), y: Breite, z: nach außen (weg vom Arm), gewölbt um die Längsachse
|
||||
b.Curved(W, H, BEND, face, 1.2f);
|
||||
b.Rim(W, H, BEND, rim);
|
||||
b.Dome(new Vector3(0, 0, 2.5f), 9, 5, boss);
|
||||
// x (Höhe) = Griff (senkrecht gehalten, wie die Mixamo-Schildbewegungen es erwarten),
|
||||
// y (Breite) = Knöchel × Griff, z (außen) = x × y = Knöchelrichtung
|
||||
var shield = b.Build(Bone(side + "Hand"), Matrix.CreateScale(Unit) * Attach(Bone(side + "Hand"), across, Vector3.Cross(knuckles, across), centre));
|
||||
shield.Shield = true; shield.Height = H; shield.Width = W; shield.Bend = BEND;
|
||||
Props.Add(shield);
|
||||
}
|
||||
|
||||
// ── Waffen weichen dem eigenen Körper aus ───────────────────────────
|
||||
// Die Mixamo-Bewegungen kennen Schwert und Schild nicht: in manchen Haltungen läge der Schild
|
||||
// im Oberschenkel oder die Klinge im Rumpf. Der Körper wird grob als Kapseln (Strecke + Radius)
|
||||
// aus den Knochen gebaut; der Schild wird nach außen geschoben, die Klinge um den Griff weggedreht.
|
||||
// Beides federt nach, damit nichts springt oder zittert.
|
||||
|
||||
readonly List<(Vector3 A, Vector3 B, float R)> _body = new();
|
||||
int[]? _bodyBones;
|
||||
|
||||
void BuildBody(out float cm)
|
||||
{
|
||||
_bodyBones ??= new[] { Bone("Hips"), Bone("Neck"), Bone("Head"), Bone("LeftUpLeg"), Bone("LeftLeg"), Bone("LeftFoot"),
|
||||
Bone("RightUpLeg"), Bone("RightLeg"), Bone("RightFoot") };
|
||||
_body.Clear();
|
||||
var bb = _bodyBones;
|
||||
Vector3 P(int i) => bb[i] >= 0 ? _global[bb[i]].Translation : Vector3.Zero;
|
||||
// Maßstab: Oberschenkel etwa 45 cm
|
||||
cm = bb[3] >= 0 && bb[4] >= 0 ? Vector3.Distance(P(3), P(4)) / 45f : 1;
|
||||
if (bb[0] < 0 || bb[1] < 0) return;
|
||||
_body.Add((P(0), P(1), 15 * cm)); // Rumpf
|
||||
if (bb[3] >= 0 && bb[6] >= 0) _body.Add((P(3), P(6), 11 * cm)); // Becken
|
||||
if (bb[2] >= 0) _body.Add((P(2), P(2) + (P(2) - P(1)) * 0.6f, 11 * cm)); // Kopf
|
||||
if (bb[3] >= 0 && bb[4] >= 0 && bb[5] >= 0) { _body.Add((P(3), P(4), 9 * cm)); _body.Add((P(4), P(5), 6.5f * cm)); }
|
||||
if (bb[6] >= 0 && bb[7] >= 0 && bb[8] >= 0) { _body.Add((P(6), P(7), 9 * cm)); _body.Add((P(7), P(8), 6.5f * cm)); }
|
||||
}
|
||||
|
||||
static Vector3 Closest(Vector3 a, Vector3 b, Vector3 p)
|
||||
{
|
||||
var ab = b - a; float l = ab.LengthSquared();
|
||||
return l < 1e-9f ? a : a + ab * MathHelper.Clamp(Vector3.Dot(p - a, ab) / l, 0, 1);
|
||||
}
|
||||
|
||||
void AvoidBody()
|
||||
{
|
||||
if (Props.Count == 0) return;
|
||||
BuildBody(out float cm);
|
||||
if (_body.Count == 0) return;
|
||||
Prop? shield = null;
|
||||
foreach (var p in Props) if (p.Shield) shield = p;
|
||||
if (shield != null) AvoidShield(shield, cm);
|
||||
foreach (var p in Props) if (!p.Shield) AvoidBlade(p, shield, cm);
|
||||
}
|
||||
|
||||
static Vector3 Axis(Matrix m, int row) => row switch
|
||||
{
|
||||
0 => new Vector3(m.M11, m.M12, m.M13), 1 => new Vector3(m.M21, m.M22, m.M23), _ => new Vector3(m.M31, m.M32, m.M33)
|
||||
};
|
||||
|
||||
/// Schild entlang seiner Außenseite verschieben, bis kein Körperteil von innen hineinragt.
|
||||
void AvoidShield(Prop s, float cm)
|
||||
{
|
||||
var m = s.Local * _global[s.Bone];
|
||||
var c = m.Translation;
|
||||
float sc = Axis(m, 0).Length(); // Modell-Einheiten je Schild-cm
|
||||
var ax = Vector3.Normalize(Axis(m, 0)); var ay = Vector3.Normalize(Axis(m, 1)); var az = Vector3.Normalize(Axis(m, 2));
|
||||
float hh = s.Height / 2 * sc, hw = s.Width / 2 * sc, gap = 2 * cm, thick = 1.5f * sc;
|
||||
float need = 0;
|
||||
foreach (var (a, b, r) in _body)
|
||||
for (int k = 0; k <= 8; k++)
|
||||
{
|
||||
var d = Vector3.Lerp(a, b, k / 8f) - c;
|
||||
float u = Vector3.Dot(d, ax), v = Vector3.Dot(d, ay), w = Vector3.Dot(d, az);
|
||||
if (MathF.Abs(u) > hh + r * 0.5f || MathF.Abs(v) > hw + r * 0.5f) continue; // neben dem Schild
|
||||
float vc = MathHelper.Clamp(v, -hw, hw) / sc;
|
||||
float surf = -s.Bend * vc * vc * sc - thick; // Innenseite (gewölbt)
|
||||
if (w > surf + r) continue; // vor dem Schild: nicht durch Schieben lösbar
|
||||
need = MathF.Max(need, w + r + gap - surf);
|
||||
}
|
||||
need = MathF.Min(need, 40 * cm);
|
||||
s.Push += (need - s.Push) * (need > s.Push ? 0.55f : 0.12f); // schnell hinaus, langsam zurück
|
||||
s.Correction = Matrix.CreateTranslation(az * s.Push);
|
||||
}
|
||||
|
||||
/// Klinge um den Griff wegdrehen, wenn sie Körper oder eigenen Schild schneidet.
|
||||
void AvoidBlade(Prop p, Prop? shield, float cm)
|
||||
{
|
||||
var m = p.Local * _global[p.Bone];
|
||||
var grip = m.Translation;
|
||||
float sc = Axis(m, 0).Length();
|
||||
var dir = Vector3.Normalize(Axis(m, 0));
|
||||
float len = p.Length * sc, half = 2.5f * cm;
|
||||
var sm = shield != null ? shield.Local * _global[shield.Bone] * shield.Correction : Matrix.Identity;
|
||||
float ss = Axis(sm, 0).Length();
|
||||
var sx = Vector3.Normalize(Axis(sm, 0)); var sy = Vector3.Normalize(Axis(sm, 1)); var sz = Vector3.Normalize(Axis(sm, 2));
|
||||
|
||||
bool Hits(Vector3 d, out Vector3 away)
|
||||
{
|
||||
away = Vector3.Zero; bool hit = false;
|
||||
for (int k = 2; k <= 10; k++)
|
||||
{
|
||||
var q = grip + d * (len * k / 10f);
|
||||
foreach (var (a, b, r) in _body)
|
||||
{
|
||||
var cp = Closest(a, b, q);
|
||||
if (Vector3.DistanceSquared(cp, q) < (r + half) * (r + half)) { away += q - cp; hit = true; }
|
||||
}
|
||||
if (shield != null)
|
||||
{
|
||||
var dq = q - sm.Translation;
|
||||
float u = Vector3.Dot(dq, sx), v = Vector3.Dot(dq, sy), w = Vector3.Dot(dq, sz);
|
||||
float vc = v / ss, surf = -shield.Bend * vc * vc * ss;
|
||||
if (MathF.Abs(u) < shield.Height / 2 * ss && MathF.Abs(v) < shield.Width / 2 * ss && MathF.Abs(w - surf) < 2.5f * cm)
|
||||
{ away += sz * (w >= surf ? 1 : -1); hit = true; }
|
||||
}
|
||||
}
|
||||
return hit;
|
||||
}
|
||||
|
||||
float target = 0;
|
||||
if (Hits(dir, out var push) && push.LengthSquared() > 1e-9f)
|
||||
{
|
||||
var axis = Vector3.Cross(dir, Vector3.Normalize(push));
|
||||
if (axis.LengthSquared() > 1e-9f)
|
||||
{
|
||||
axis.Normalize();
|
||||
p.Axis = axis;
|
||||
target = MathHelper.ToRadians(50);
|
||||
for (int deg = 6; deg <= 50; deg += 6)
|
||||
if (!Hits(Vector3.Transform(dir, Quaternion.CreateFromAxisAngle(axis, MathHelper.ToRadians(deg))), out _))
|
||||
{ target = MathHelper.ToRadians(deg); break; }
|
||||
}
|
||||
}
|
||||
p.Angle += (target - p.Angle) * (target > p.Angle ? 0.5f : 0.12f);
|
||||
p.Correction = p.Angle < 1e-3f ? Matrix.Identity
|
||||
: Matrix.CreateTranslation(-grip) * Matrix.CreateFromAxisAngle(p.Axis, p.Angle) * Matrix.CreateTranslation(grip);
|
||||
}
|
||||
|
||||
sealed class MeshBuilder
|
||||
{
|
||||
readonly List<VertexPNC> _v = new(); readonly List<int> _i = new();
|
||||
|
||||
void Quad(Vector3 a, Vector3 b, Vector3 c, Vector3 d, Color col)
|
||||
{
|
||||
var n = Vector3.Normalize(Vector3.Cross(b - a, c - a));
|
||||
int o = _v.Count;
|
||||
foreach (var p in new[] { a, b, c, d }) _v.Add(new VertexPNC { Position = p, Normal = n, Color = col });
|
||||
_i.AddRange(new[] { o, o + 1, o + 2, o, o + 2, o + 3 });
|
||||
}
|
||||
|
||||
public void Box(Vector3 c, Vector3 s, Color col)
|
||||
{
|
||||
var h = s / 2;
|
||||
Vector3 P(float x, float y, float z) => c + new Vector3(x * h.X, y * h.Y, z * h.Z);
|
||||
Quad(P(-1, -1, 1), P(1, -1, 1), P(1, 1, 1), P(-1, 1, 1), col);
|
||||
Quad(P(1, -1, -1), P(-1, -1, -1), P(-1, 1, -1), P(1, 1, -1), col);
|
||||
Quad(P(-1, 1, -1), P(-1, 1, 1), P(1, 1, 1), P(1, 1, -1), col);
|
||||
Quad(P(-1, -1, 1), P(-1, -1, -1), P(1, -1, -1), P(1, -1, 1), col);
|
||||
Quad(P(1, -1, 1), P(1, -1, -1), P(1, 1, -1), P(1, 1, 1), col);
|
||||
Quad(P(-1, -1, -1), P(-1, -1, 1), P(-1, 1, 1), P(-1, 1, -1), col);
|
||||
}
|
||||
|
||||
static Vector3 Surf(float x, float y, float bend, float off) => new(x, y, -bend * y * y + off);
|
||||
|
||||
public void Curved(float w, float h, float bend, Color col, float thick)
|
||||
{
|
||||
const int NX = 8, NY = 10;
|
||||
for (int side = 0; side < 2; side++)
|
||||
for (int i = 0; i < NX; i++)
|
||||
for (int j = 0; j < NY; j++)
|
||||
{
|
||||
float x0 = -h / 2 + h * i / NX, x1 = -h / 2 + h * (i + 1) / NX;
|
||||
float y0 = -w / 2 + w * j / NY, y1 = -w / 2 + w * (j + 1) / NY;
|
||||
float off = side == 0 ? 0 : -thick;
|
||||
var shade = side == 0 ? col : new Color(110, 78, 46); // Innenseite Holz
|
||||
Quad(Surf(x0, y0, bend, off), Surf(x1, y0, bend, off), Surf(x1, y1, bend, off), Surf(x0, y1, bend, off), shade);
|
||||
}
|
||||
}
|
||||
|
||||
public void Rim(float w, float h, float bend, Color col)
|
||||
{
|
||||
const int N = 10;
|
||||
for (int j = 0; j < N; j++)
|
||||
{
|
||||
float y0 = -w / 2 + w * j / N, y1 = -w / 2 + w * (j + 1) / N;
|
||||
foreach (float x in new[] { -h / 2, h / 2 })
|
||||
{
|
||||
var a = Surf(x, y0, bend, 0.6f); var c = Surf(x, y1, bend, 0.6f);
|
||||
Box((a + c) / 2, new Vector3(3, MathF.Abs(y1 - y0) + 0.2f, 3), col);
|
||||
}
|
||||
}
|
||||
for (int i = 0; i < N; i++)
|
||||
{
|
||||
float x0 = -h / 2 + h * i / N, x1 = -h / 2 + h * (i + 1) / N;
|
||||
foreach (float y in new[] { -w / 2, w / 2 })
|
||||
Box(Surf((x0 + x1) / 2, y, bend, 0.6f), new Vector3(MathF.Abs(x1 - x0) + 0.2f, 3, 3), col);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dome(Vector3 c, float r, float hgt, Color col)
|
||||
{
|
||||
const int SEG = 12, RING = 4;
|
||||
for (int k = 0; k < RING; k++)
|
||||
for (int s = 0; s < SEG; s++)
|
||||
{
|
||||
float a0 = MathF.PI / 2 * k / RING, a1 = MathF.PI / 2 * (k + 1) / RING;
|
||||
float t0 = MathF.Tau * s / SEG, t1 = MathF.Tau * (s + 1) / SEG;
|
||||
Vector3 P(float a, float t) => c + new Vector3(MathF.Cos(t) * MathF.Cos(a) * r, MathF.Sin(t) * MathF.Cos(a) * r, MathF.Sin(a) * hgt);
|
||||
Quad(P(a0, t0), P(a0, t1), P(a1, t1), P(a1, t0), col);
|
||||
}
|
||||
}
|
||||
|
||||
public Prop Build(int bone, Matrix local)
|
||||
{
|
||||
var v = _v.ToArray();
|
||||
return new Prop { Bone = bone, Local = local, V = v, I = _i.ToArray(), Base = Array.ConvertAll(v, x => x.Color) };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
68
Mono/Gfx/Ui.cs
Normal file
68
Mono/Gfx/Ui.cs
Normal file
@@ -0,0 +1,68 @@
|
||||
using System;
|
||||
using FontStashSharp;
|
||||
using GladiatorIdle.Arena;
|
||||
using Microsoft.Xna.Framework;
|
||||
using Microsoft.Xna.Framework.Graphics;
|
||||
using Microsoft.Xna.Framework.Input;
|
||||
using D = GladiatorIdle.Gfx.Draw;
|
||||
|
||||
namespace GladiatorIdle.Gfx
|
||||
{
|
||||
/// <summary>
|
||||
/// Einfache Oberfläche im Sofort-Modus (Design-Pixel): jedes Bild werden Knöpfe gezeichnet und
|
||||
/// gleichzeitig geprüft, ob sie geklickt wurden. Maus in Design-Pixel umgerechnet.
|
||||
/// </summary>
|
||||
internal sealed class Ui
|
||||
{
|
||||
public Vector2 Mouse;
|
||||
public bool Click;
|
||||
public bool Hovering { get; private set; }
|
||||
Matrix _inverse;
|
||||
|
||||
public void Begin(Input input, Matrix ui)
|
||||
{
|
||||
_inverse = Matrix.Invert(ui);
|
||||
Mouse = Vector2.Transform(new Vector2(input.Mouse.X, input.Mouse.Y), _inverse);
|
||||
Click = input.LeftClick;
|
||||
Hovering = false;
|
||||
}
|
||||
|
||||
public bool Hover(RectangleF r)
|
||||
{
|
||||
bool h = r.Contains(Mouse);
|
||||
if (h) Hovering = true;
|
||||
return h;
|
||||
}
|
||||
|
||||
/// Klick auf die Fläche (einmal je Klick).
|
||||
public bool Hit(RectangleF r)
|
||||
{
|
||||
if (!Click || !r.Contains(Mouse)) return false;
|
||||
Click = false;
|
||||
SoundManager.PlayClick();
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Dunkle Tafel mit Bronzerand.
|
||||
public static void Panel(SpriteBatch sb, RectangleF r, Color? border = null, float alpha = 0.86f)
|
||||
{
|
||||
D.Rect(sb, r, new Color(18, 13, 9) * alpha);
|
||||
D.Frame(sb, r, border ?? D.Border, 2);
|
||||
D.Frame(sb, new RectangleF(r.X + 4, r.Y + 4, r.Width - 8, r.Height - 8), Color.Black * 0.35f, 1);
|
||||
}
|
||||
|
||||
/// Knopf mit Text; liefert true beim Klick.
|
||||
public bool Button(SpriteBatch sb, RectangleF r, string text, bool enabled = true, bool selected = false,
|
||||
float size = 24, Color? accent = null)
|
||||
{
|
||||
bool hover = enabled && Hover(r);
|
||||
var a = accent ?? D.Gold;
|
||||
var fill = !enabled ? new Color(24, 20, 16) : selected ? a * 0.32f : hover ? new Color(70, 52, 32) : new Color(38, 28, 19);
|
||||
D.Rect(sb, r, fill * 0.95f);
|
||||
D.Rect(sb, new RectangleF(r.X + 2, r.Y + 2, r.Width - 4, (r.Height - 4) * 0.45f), Color.White * (hover ? 0.08f : 0.04f));
|
||||
D.Frame(sb, r, !enabled ? new Color(60, 48, 36) : selected || hover ? a : D.Border, selected ? 3 : 2);
|
||||
D.Text(sb, Assets.SansBold, size, text, r.Center, !enabled ? D.Dim : selected ? Color.White : D.Sand, Align.Center);
|
||||
return enabled && Hit(r);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user