Puppet checks: the cell is the coarsest that resolves the limbs; every joint bent at once is bounded; the look constants are ranged

Findings minimum-resolution-unmeasured and stretch-bound-narrow. Resolved is stated: the thinnest
limb spans two cells, one piece, every body owns 48 triangle corners. The sweep over 50 to 100 mm
shows none resolves, so 40 mm stays. Soul's all-joint random bend is committed (200 poses at 45 and
90 degrees) with an explicit ratio and length bound; SminRadius must not exceed the thinnest limb.
The stretch and piece helpers live in PuppetChecks, once, and the smoke uses them.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-20 05:33:24 +01:00
commit ed85d9e6a6
5 changed files with 167 additions and 71 deletions

View file

@ -52,6 +52,11 @@ public partial class Puppet : Node3D
new Basis(new Vector3(r.R._m00, r.R._m10, r.R._m20), new Vector3(r.R._m01, r.R._m11, r.R._m21), new Vector3(r.R._m02, r.R._m12, r.R._m22)),
new Vector3(r.T.x, r.T.y, r.T.z));
/// <summary>The <see cref="Rigid"/> of a Godot transform (rotation only; no scale).</summary>
public static Rigid ToRigid(Transform3D t) => new(
new CultMath.float3x3(new CultMath.float3(t.Basis.Row0.X, t.Basis.Row0.Y, t.Basis.Row0.Z), new CultMath.float3(t.Basis.Row1.X, t.Basis.Row1.Y, t.Basis.Row1.Z), new CultMath.float3(t.Basis.Row2.X, t.Basis.Row2.Y, t.Basis.Row2.Z)),
new CultMath.float3(t.Origin.X, t.Origin.Y, t.Origin.Z));
/// <summary>Makes the carriers match the lanes (creates the missing, frees the gone, poses every one), then rebuilds the mesh if the topology changed. <paramref name="teleport"/> skips the interpolation from the previous pose.</summary>
public void Sync(in Box3DSoaView view, bool teleport = false)
{

View file

@ -79,7 +79,7 @@ public sealed class PuppetShape
/// </summary>
public static class PuppetField
{
/// <summary>The grid cell, the minimum that resolves the thinnest limb (radius 40 mm).</summary>
/// <summary>The grid cell (m): the coarsest at which the thinnest limb, radius 40 mm, still spans two cells across (PuppetChecks measures this against the coarser cells).</summary>
public const float Cell = 0.04f;
/// <summary>How far a Spherical joint's child subtree swings in the bind pose, so a limb hanging beside the trunk is not webbed to it.</summary>
@ -87,6 +87,9 @@ public static class PuppetField
private const int Newton = 2;
/// <summary>A body's radius, or for a box its smallest half extent: the thickness of the limb it draws.</summary>
public static float Thickness(Box3DSoaKind kind, float3 size) => kind == Box3DSoaKind.Box ? math.min(size.x, math.min(size.y, size.z)) : size.x;
/// <summary>The bodies of the lanes that are drawn: a shape, not an Anchor or a StaticBox.</summary>
public static bool HasShape(Box3DSoaKind kind) => kind is Box3DSoaKind.Sphere or Box3DSoaKind.Capsule or Box3DSoaKind.Box;
@ -94,7 +97,8 @@ public static class PuppetField
public static bool Qualifies(Box3DSoaJointKind joint, Box3DSoaKind a, Box3DSoaKind b) =>
joint is Box3DSoaJointKind.Revolute or Box3DSoaJointKind.Spherical or Box3DSoaJointKind.Weld && HasShape(a) && HasShape(b);
public static PuppetShape Build(IReadOnlyList<PuppetBody> bodies, IReadOnlyList<PuppetJoint> joints, float smin, float ballScale, float boxRound)
/// <summary>Builds the shape on a grid of <paramref name="cell"/> metres (the shipped <see cref="Cell"/>; the resolution check sweeps it).</summary>
public static PuppetShape Build(IReadOnlyList<PuppetBody> bodies, IReadOnlyList<PuppetJoint> joints, float smin, float ballScale, float boxRound, float cell = Cell)
{
int n = bodies.Count;
// The first qualifying joint with body b as its B decides b's blend (lane order); every other joint of b is ignored.
@ -120,7 +124,7 @@ public static class PuppetField
}
var field = new Field(bodies, t, joints, jointOf, smin, ballScale, boxRound);
return Mesh(field, bodies, t, joints, smin);
return Mesh(field, bodies, t, joints, smin, cell);
}
private static int Depth(int[] up, int i)
@ -141,7 +145,7 @@ public static class PuppetField
return false;
}
private static PuppetShape Mesh(Field f, IReadOnlyList<PuppetBody> bodies, Rigid[] t, IReadOnlyList<PuppetJoint> joints, float smin)
private static PuppetShape Mesh(Field f, IReadOnlyList<PuppetBody> bodies, Rigid[] t, IReadOnlyList<PuppetJoint> joints, float smin, float cell)
{
int n = bodies.Count;
var lo = new float3(float.MaxValue, float.MaxValue, float.MaxValue); var hi = new float3(float.MinValue, float.MinValue, float.MinValue);
@ -153,15 +157,15 @@ public static class PuppetField
reach = MathF.Max(reach, r);
if (f.BallR[i] > 0) { lo = math.min(lo, f.Ball[i] - f.BallR[i]); hi = math.max(hi, f.Ball[i] + f.BallR[i]); }
}
float pad = smin + 2 * Cell;
float pad = smin + 2 * cell;
lo -= pad; hi += pad;
int nx = (int)MathF.Ceiling((hi.x - lo.x) / Cell) + 1, ny = (int)MathF.Ceiling((hi.y - lo.y) / Cell) + 1, nz = (int)MathF.Ceiling((hi.z - lo.z) / Cell) + 1;
int nx = (int)MathF.Ceiling((hi.x - lo.x) / cell) + 1, ny = (int)MathF.Ceiling((hi.y - lo.y) / cell) + 1, nz = (int)MathF.Ceiling((hi.z - lo.z) / cell) + 1;
var samples = new float[nx, ny, nz];
for (int x = 0; x < nx; x++)
for (int y = 0; y < ny; y++)
for (int z = 0; z < nz; z++)
samples[x, y, z] = f.Eval(lo + new float3(x, y, z) * Cell, out _, out _, out _).w;
var nets = CultGeometrySurfaceNets.Extract(samples, 0f, lo, Cell);
samples[x, y, z] = f.Eval(lo + new float3(x, y, z) * cell, out _, out _, out _).w;
var nets = CultGeometrySurfaceNets.Extract(samples, 0f, lo, cell);
// Two Newton steps put each net vertex on the isosurface.
var v = new float3[nets.VertexCount];
@ -251,7 +255,7 @@ public static class PuppetField
}
}
public float Thickness(int i) => _kind[i] == Box3DSoaKind.Box ? math.min(_size[i].x, math.min(_size[i].y, _size[i].z)) : _size[i].x;
public float Thickness(int i) => PuppetField.Thickness(_kind[i], _size[i]);
/// <summary>The body's reach from its origin: the farthest the primitive extends.</summary>
public float Extent(int i) => _kind[i] == Box3DSoaKind.Box ? math.length(_size[i]) : _size[i].x + _size[i].y;

View file

@ -42,22 +42,27 @@ public sealed class PuppetModel
/// <summary>Reads the shape bodies and qualifying joints of the lanes and updates.</summary>
public bool Update(in Box3DSoaView view)
{
Lanes(view, _laneBodies, _laneJoints);
return Update(_laneBodies, _laneJoints);
}
/// <summary>The shape bodies (with their pose now) and the qualifying joints of the lanes: a Revolute, Spherical or Weld between two shapes.</summary>
public static void Lanes(in Box3DSoaView view, List<PuppetBody> bodies, List<PuppetJointLane> joints)
{
bodies.Clear(); joints.Clear();
var kind = view.Kind;
var bodies = _laneBodies; bodies.Clear();
for (int i = 0; i < kind.Length; i++)
{
if (!PuppetField.HasShape((Box3DSoaKind)kind[i])) continue;
bodies.Add(new PuppetBody(view.StableId[i], (Box3DSoaKind)kind[i], new float3(view.Size0[i], view.Size1[i], view.Size2[i]),
Rigid.FromQuaternion(view.RotationX[i], view.RotationY[i], view.RotationZ[i], view.RotationW[i], new float3(view.PositionX[i], view.PositionY[i], view.PositionZ[i]))));
}
var joints = _laneJoints; joints.Clear();
for (int j = 0; j < view.JointCount; j++)
{
int a = view.JointBodyA[j], b = view.JointBodyB[j];
if (a < 0 || b < 0 || !PuppetField.Qualifies((Box3DSoaJointKind)view.JointKind[j], (Box3DSoaKind)kind[a], (Box3DSoaKind)kind[b])) continue;
joints.Add(new PuppetJointLane((Box3DSoaJointKind)view.JointKind[j], view.StableId[a], view.StableId[b], new float3(view.JointOriginX[j], view.JointOriginY[j], view.JointOriginZ[j])));
}
return Update(bodies, joints);
}
/// <summary>

View file

@ -12,7 +12,8 @@ namespace BadDay.Client.Tests;
/// </summary>
public static class PuppetChecks
{
private static readonly float3 Zero = new(0, 0, 0);
/// <summary>No skinned edge may be longer than this many times its bind length.</summary>
public const float StretchLimit = 4f;
private static PuppetBody Body(ulong id, Box3DSoaKind kind, float s0, float s1, float y) =>
new(id, kind, new float3(s0, s1, 0), Rigid.FromQuaternion(0, 0, 0, 1, new float3(0, y, 0)));
@ -30,7 +31,7 @@ public static class PuppetChecks
new(Box3DSoaJointKind.Revolute, 11, 12, new float3(0, 0.85f, 0)),
});
public static void Run(Action<string> fail)
public static void Run(Action<string> fail, in Box3DSoaView creationView)
{
void Check(bool ok, string what) { if (!ok) fail(what); }
PuppetModel Fresh() => new(Look.SminRadius, Look.JointBallScale, Look.BoxRound);
@ -74,5 +75,132 @@ public static class PuppetChecks
Check(!many.Update(crowd, new List<PuppetJointLane>()), "an over-full puppet reported a change with none");
crowd.RemoveAt(0);
Check(many.Update(crowd, new List<PuppetJointLane>()) && many.Shape is not null, "the puppet did not come back once it fit the skin");
// The real puppet at its creation pose: the grid cell is the coarsest that resolves its limbs, and bent every which way
// no skinned edge is a web.
var real = new List<PuppetBody>(); var realLanes = new List<PuppetJointLane>();
PuppetModel.Lanes(creationView, real, realLanes);
var index = real.Select((b, k) => (b.Id, k)).ToDictionary(x => x.Id, x => x.k);
var inputs = realLanes.Select(j => new PuppetJoint(j.Kind, index[j.A], index[j.B], real[index[j.A]].Bind.Inverse().Apply(j.Origin))).ToList();
PuppetShape Build(float cell) => PuppetField.Build(real, inputs, Look.SminRadius, Look.JointBallScale, Look.BoxRound, cell);
// Resolved: the thinnest limb spans at least two cells across (the grid can then represent it), the mesh is one piece, and
// every body owns enough of the surface to close a limb (at least 48 triangle corners are most influenced by it).
float thinnest = real.Min(b => PuppetField.Thickness(b.Kind, b.Size));
bool Resolved(float cell)
{
var shape = Build(cell);
var owned = new int[real.Count];
for (int v = 0; v < shape.Positions.Length; v++) owned[shape.WeightA[v] >= 0.5f ? shape.BoneA[v] : shape.BoneB[v]]++;
return 2 * thinnest >= 2 * cell - 1e-6f && Pieces(shape) == 1 && owned.Min() >= 48;
}
// The look constants may be changed by the operator's joint-look question, within what the mesh can hold: a blend wider than
// the thinnest limb swallows it, and a negative ball or rounding is no shape.
Check(Look.SminRadius > 0 && Look.SminRadius <= thinnest, $"Look.SminRadius {Look.SminRadius} m is not within (0, the thinnest limb's radius {thinnest} m]");
Check(Look.JointBallScale >= 0 && Look.BoxRound >= 0, "Look.JointBallScale or Look.BoxRound is negative");
Check(Resolved(PuppetField.Cell), $"the shipped {PuppetField.Cell * 1000:F0} mm cell does not resolve the limbs");
foreach (float coarser in new[] { 0.05f, 0.06f, 0.08f, 0.10f })
Check(coarser <= PuppetField.Cell || !Resolved(coarser), $"a {coarser * 1000:F0} mm cell resolves the limbs, so {PuppetField.Cell * 1000:F0} mm is not the coarsest");
// Bent at random, every joint at once, no skinned edge is a web. The bounds are what the shipped look measures with a
// margin (200 poses each: 3.24x and 0.140 m at 45 degrees, 5.0x and 0.205 m at 90); a bind edge is about a cell
// (0.04 m), so 0.17 m is four cells and 0.25 m is six. At 90 degrees only the length is bounded, since the ratio
// overstates when a bind edge is tiny.
var puppet = Build(PuppetField.Cell);
float worstRatio = 0, worstLength = 0, worstLength90 = 0;
for (int seed = 0; seed < 200; seed++)
{
var (ratio, length) = Stretch(puppet, Bend(puppet, seed, 45f * MathF.PI / 180f));
worstRatio = MathF.Max(worstRatio, ratio); worstLength = MathF.Max(worstLength, length);
worstLength90 = MathF.Max(worstLength90, Stretch(puppet, Bend(puppet, seed, 90f * MathF.PI / 180f)).Length);
}
Check(worstRatio <= StretchLimit, $"every joint bent up to 45 degrees stretches an edge {worstRatio:F2}x its bind length, over {StretchLimit}x");
Check(worstLength <= 0.17f, $"every joint bent up to 45 degrees makes a skinned edge {worstLength:F3} m long, over 0.17 m");
Check(worstLength90 <= 0.25f, $"every joint bent up to 90 degrees makes a skinned edge {worstLength90:F3} m long, over 0.25 m");
}
/// <summary>The mesh's connected pieces with coincident triangle corners welded.</summary>
public static int Pieces(PuppetShape shape)
{
var id = new Dictionary<(long, long, long), int>();
var corner = new int[shape.Positions.Length];
for (int i = 0; i < corner.Length; i++)
{
var p = shape.Positions[i];
var key = ((long)Math.Round(p.x * 1e5), (long)Math.Round(p.y * 1e5), (long)Math.Round(p.z * 1e5));
if (!id.TryGetValue(key, out corner[i])) id[key] = corner[i] = id.Count;
}
var parent = Enumerable.Range(0, id.Count).ToArray();
int Find(int x) { while (parent[x] != x) x = parent[x] = parent[parent[x]]; return x; }
for (int t = 0; t < corner.Length; t += 3) { parent[Find(corner[t + 1])] = Find(corner[t]); parent[Find(corner[t + 2])] = Find(corner[t]); }
return corner.Select(Find).Distinct().Count();
}
/// <summary>
/// The worst a skinned triangle edge gets under <paramref name="bones"/> (per body, applied to the spread bind): its length over
/// its bind length, and its length in metres. The ratio overstates when the bind edge is tiny; the length does not.
/// </summary>
public static (float Ratio, float Length) Stretch(PuppetShape shape, Rigid[] bones)
{
float3 Skin(int v) { float w = shape.WeightA[v]; var p = shape.Positions[v]; return bones[shape.BoneA[v]].Apply(p) * w + bones[shape.BoneB[v]].Apply(p) * (1 - w); }
float ratio = 0, length = 0;
for (int t = 0; t < shape.Positions.Length; t += 3)
for (int e = 0; e < 3; e++)
{
int a = t + e, b = t + (e + 1) % 3;
float bind = math.length(shape.Positions[a] - shape.Positions[b]);
float now = math.length(Skin(a) - Skin(b));
length = MathF.Max(length, now);
if (bind > 1e-5f) ratio = MathF.Max(ratio, now / bind);
}
return (ratio, length);
}
private static int[] Parents(PuppetShape shape)
{
var up = Enumerable.Repeat(-1, shape.Ids.Length).ToArray();
foreach (var j in shape.Joints) if (up[j.B] < 0) up[j.B] = j.A;
return up;
}
/// <summary>Whether body <paramref name="i"/> is <paramref name="root"/> or hangs under it through the joints' first-parent tree.</summary>
public static bool Under(PuppetShape shape, int i, int root)
{
var up = Parents(shape);
for (int d = 0; d <= up.Length; d++)
{
if (i == root) return true;
if (up[i] < 0) return false;
i = up[i];
}
return false;
}
private static Rigid Identity => Rigid.FromQuaternion(0, 0, 0, 1, new float3(0, 0, 0));
/// <summary>The bones of a pose with joint <paramref name="joint"/>'s child subtree turned by <paramref name="radians"/> about <paramref name="axis"/> through the joint origin.</summary>
public static Rigid[] Swing(PuppetShape shape, int joint, float3 axis, float radians)
{
var turn = Rigid.About(shape.Joints[joint].Origin, axis, radians);
return Enumerable.Range(0, shape.Ids.Length).Select(i => Under(shape, i, shape.Joints[joint].B) ? turn : Identity).ToArray();
}
/// <summary>The bones of a pose with every joint bent by a random angle up to <paramref name="maxRadians"/> about a random axis, parents first.</summary>
public static Rigid[] Bend(PuppetShape shape, int seed, float maxRadians)
{
var rng = new System.Random(seed);
var bones = Enumerable.Range(0, shape.Ids.Length).Select(_ => Identity).ToArray();
var up = Parents(shape);
int Depth(int i) { int d = 0; while (up[i] >= 0 && d <= up.Length) { i = up[i]; d++; } return d; }
foreach (int j in Enumerable.Range(0, shape.Joints.Length).OrderBy(j => Depth(shape.Joints[j].B)))
{
var joint = shape.Joints[j];
if (up[joint.B] != joint.A) continue; // only the joint that decides the body's blend
var axis = new float3((float)rng.NextDouble() * 2 - 1, (float)rng.NextDouble() * 2 - 1, (float)rng.NextDouble() * 2 - 1);
axis = math.length(axis) < 1e-3f ? new float3(1, 0, 0) : math.normalize(axis);
var turn = Rigid.About(bones[joint.A].Apply(joint.Origin), axis, ((float)rng.NextDouble() * 2 - 1) * maxRadians);
for (int i = 0; i < bones.Length; i++) if (Under(shape, i, joint.B)) bones[i] = turn.After(bones[i]);
}
return bones;
}
}

View file

@ -57,7 +57,7 @@ public partial class Smoke : Node
private async Task Scenario()
{
CheckEngineAndScene();
PuppetChecks.Run(failure => Check(false, "puppet: " + failure));
PuppetChecks.Run(failure => Check(false, "puppet: " + failure), Session.View);
if (_failures.Count > 0) return;
// Slow motion, by wall clock: a quarter of the session steps per real second, the same run.
@ -176,74 +176,28 @@ public partial class Smoke : Node
Check(environment.BackgroundColor.Luminance < 0.2f, "the background is not dark grey");
}
/// <summary>No skinned triangle edge may be longer than this many times its bind length.</summary>
private const float StretchLimit = 4f;
/// <summary>The puppet's one mesh: size, one piece, and not stretched into a web by the pose it is in or by a joint swung 90 degrees.</summary>
/// <summary>The puppet's one mesh as it is drawn: size, one piece, and not stretched into a web by the pose it is in or by a joint swung 90 degrees.</summary>
private void CheckPuppetMesh(string when)
{
if (_main.Bodies.PuppetShape is not { } shape) { Check(false, $"{when}: the puppet has no mesh"); return; }
Check(shape.Triangles is >= 2000 and <= 6000, $"{when}: the puppet mesh has {shape.Triangles} triangles, not 2000 to 6000");
int pieces = Pieces(shape);
int pieces = PuppetChecks.Pieces(shape);
Check(pieces == 1, $"{when}: the puppet mesh is {pieces} pieces, not one");
var posed = new Transform3D[shape.Ids.Length];
var posed = new Rigid[shape.Ids.Length];
for (int i = 0; i < posed.Length; i++)
posed[i] = (_main.Bodies.PoseOf(shape.Ids[i]) ?? Transform3D.Identity) * Puppet.ToTransform(shape.SpreadBind[i].Inverse());
float stretch = MaxStretch(shape, posed);
Check(stretch <= StretchLimit, $"{when}: a skinned edge is {stretch:F1}x its bind length, over {StretchLimit}x");
posed[i] = Puppet.ToRigid((_main.Bodies.PoseOf(shape.Ids[i]) ?? Transform3D.Identity) * Puppet.ToTransform(shape.SpreadBind[i].Inverse()));
float stretch = PuppetChecks.Stretch(shape, posed).Ratio;
Check(stretch <= PuppetChecks.StretchLimit, $"{when}: a skinned edge is {stretch:F1}x its bind length, over {PuppetChecks.StretchLimit}x");
// Every Spherical joint swung 90 degrees: its child subtree turns about the joint origin.
var up = Enumerable.Repeat(-1, shape.Ids.Length).ToArray();
foreach (var j in shape.Joints) if (up[j.B] < 0) up[j.B] = j.A;
foreach (var j in shape.Joints.Where(j => j.Kind == global::Ymir.Box3D.Box3DSoaJointKind.Spherical))
for (int j = 0; j < shape.Joints.Length; j++)
{
var origin = new Vector3(j.Origin.x, j.Origin.y, j.Origin.z);
var swing = new Transform3D(new Basis(Vector3.Right, Mathf.Pi / 2), origin) * new Transform3D(Basis.Identity, -origin);
var bones = new Transform3D[shape.Ids.Length];
for (int i = 0; i < bones.Length; i++)
{
bool under = false;
for (int k = i, d = 0; k >= 0 && d <= bones.Length; k = up[k], d++) if (k == j.B) { under = true; break; }
bones[i] = under ? swing : Transform3D.Identity;
}
stretch = MaxStretch(shape, bones);
Check(stretch <= StretchLimit, $"{when}: with body {shape.Ids[j.B]} swung 90 degrees a skinned edge is {stretch:F1}x its bind length, over {StretchLimit}x");
if (shape.Joints[j].Kind != global::Ymir.Box3D.Box3DSoaJointKind.Spherical) continue;
stretch = PuppetChecks.Stretch(shape, PuppetChecks.Swing(shape, j, new CultMath.float3(1, 0, 0), MathF.PI / 2)).Ratio;
Check(stretch <= PuppetChecks.StretchLimit, $"{when}: with body {shape.Ids[shape.Joints[j].B]} swung 90 degrees a skinned edge is {stretch:F1}x its bind length, over {PuppetChecks.StretchLimit}x");
}
}
private static float MaxStretch(PuppetShape shape, Transform3D[] bones)
{
Vector3 Bind(int v) => new(shape.Positions[v].x, shape.Positions[v].y, shape.Positions[v].z);
Vector3 Skin(int v) { var p = Bind(v); float w = shape.WeightA[v]; return bones[shape.BoneA[v]] * p * w + bones[shape.BoneB[v]] * p * (1 - w); }
float worst = 0;
for (int t = 0; t < shape.Positions.Length; t += 3)
for (int e = 0; e < 3; e++)
{
int a = t + e, b = t + (e + 1) % 3;
float bind = (Bind(a) - Bind(b)).Length();
if (bind > 1e-5f) worst = Mathf.Max(worst, (Skin(a) - Skin(b)).Length() / bind);
}
return worst;
}
/// <summary>Connected components of the mesh with its triangles' coincident corners welded.</summary>
private static int Pieces(PuppetShape shape)
{
var id = new Dictionary<(long, long, long), int>();
var corner = new int[shape.Positions.Length];
for (int i = 0; i < corner.Length; i++)
{
var p = shape.Positions[i];
var key = ((long)Math.Round(p.x * 1e5), (long)Math.Round(p.y * 1e5), (long)Math.Round(p.z * 1e5));
if (!id.TryGetValue(key, out corner[i])) id[key] = corner[i] = id.Count;
}
var parent = Enumerable.Range(0, id.Count).ToArray();
int Find(int x) { while (parent[x] != x) x = parent[x] = parent[parent[x]]; return x; }
for (int t = 0; t < corner.Length; t += 3) { parent[Find(corner[t + 1])] = Find(corner[t]); parent[Find(corner[t + 2])] = Find(corner[t]); }
return corner.Select(Find).Distinct().Count();
}
private void CheckPoses(string when)
{
var view = Session.View;