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 , 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;
}
///
/// 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.
///
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 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();
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 _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 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(); public int[] I = Array.Empty(); public Color[] Base = Array.Empty();
}
public readonly List 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 _v = new(); readonly List _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) };
}
}
}
}