Skip to content

Next Gen STEP AP242 Native-ish BREP Geometric Modeling Kernel

Add gameplay body qualification and fix boundary pose semantics

Yuechen Lib321193d4903
diff --git a/Aetheris.Humanoid.Tests/HumanoidRestX1Tests.cs b/Aetheris.Humanoid.Tests/HumanoidRestX1Tests.cs
index 27114f52..d80a46a2 100644
--- a/Aetheris.Humanoid.Tests/HumanoidRestX1Tests.cs
+++ b/Aetheris.Humanoid.Tests/HumanoidRestX1Tests.cs
@@ -88,6 +88,27 @@ public sealed class HumanoidRestX1Tests
Assert.InRange(Math.Abs(actual.FlexionDegrees - 120), 0, .001);
}
+ [Theory]
+ [InlineData(HumanoidJointKind.LeftHip, -20)]
+ [InlineData(HumanoidJointKind.RightHip, -20)]
+ [InlineData(HumanoidJointKind.LeftShoulder, -30)]
+ [InlineData(HumanoidJointKind.RightShoulder, -30)]
+ public void ExactNegativeFlexionBoundaryRetainsItsSemanticBranch(HumanoidJointKind joint, double degrees)
+ {
+ var source = CanonicalAdultTemplate.Create();
+ var skeleton = HumanoidRestPoseNormalizer.Normalize(source).Skeleton;
+ var solved = HumanoidKinematicSolver.Solve(skeleton,
+ new("negative-boundary", skeleton.SkeletonId, skeleton.RestPoseId, 0,
+ [new(joint, FlexionDegrees: degrees)]));
+
+ Assert.True(solved.IsSolved);
+ var actual = HumanoidPoseSemantics.Measure(skeleton, solved.Pose!.GlobalTransforms, joint);
+ Assert.InRange(Math.Abs(actual.FlexionDegrees - degrees), 0, .001);
+ Assert.InRange(Math.Abs(actual.AbductionDegrees), 0, .001);
+ Assert.All(solved.Pose.SemanticResiduals,
+ residual => Assert.InRange(residual.MaximumAbsoluteDegrees, 0, .001));
+ }
+
private static HumanoidSkeleton ArmSkeleton(double abduction)
{
var radians = abduction * Math.PI / 180;
diff --git a/Aetheris.Humanoid.Tests/HumanoidSkinningTests.cs b/Aetheris.Humanoid.Tests/HumanoidSkinningTests.cs
new file mode 100644
index 00000000..3893d400
--- /dev/null
+++ b/Aetheris.Humanoid.Tests/HumanoidSkinningTests.cs
@@ -0,0 +1,211 @@
+using System.Numerics;
+using Aetheris.Humanoid;
+using Aetheris.Kernel.Core.Math;
+using Xunit;
+
+namespace Aetheris.Humanoid.Tests;
+
+public sealed class HumanoidSkinningTests
+{
+ [Fact]
+ public void RigidPaletteMatchesMatrixWithRotationAndTranslation()
+ {
+ var matrix = Matrix4x4.CreateFromYawPitchRoll(.7f, -.4f, 1.1f) *
+ Matrix4x4.CreateTranslation(125, -37, 860);
+ var point = new Vector3(42, 73, -116);
+ var skin = HumanoidSkinDualQuaternion.FromRigidTransform(matrix);
+ Assert.InRange(Vector3.Distance(Vector3.Transform(point, matrix), skin.TransformPoint(point)), 0, .0002);
+ }
+
+ [Fact]
+ public void HalfHipRotationPreservesRadiusAndMatchesAnalyticPoint()
+ {
+ var (surface, skeleton) = Fixture();
+ var binding = new HumanoidSkinningBinding(surface, skeleton);
+ var solved = Solve(skeleton, 90);
+ var point = binding.Evaluate(solved)[0];
+ var expected = new Point3D(-8, Math.Sqrt(50), 100 - Math.Sqrt(50));
+ Assert.InRange((point - expected).Length, 0, .0001);
+ Assert.Equal(3, binding.CreatePalette(solved).Count);
+ Assert.Equal(2, binding.MaximumInfluences);
+ }
+
+ [Fact]
+ public void BindPoseReconstructsRestVertices()
+ {
+ var (surface, skeleton) = Fixture();
+ var binding = new HumanoidSkinningBinding(surface, skeleton);
+ var points = binding.Evaluate(Solve(skeleton, 0));
+ for (var index = 0; index < points.Count; index++)
+ {
+ Assert.InRange((points[index] - surface.Vertices[index].Position).Length, 0, .0001);
+ }
+ }
+
+ [Fact]
+ public void BindingRetainsVertexAndWeightSnapshots()
+ {
+ var (surface, skeleton) = Fixture();
+ var weights = surface.SkinWeights[0].Weights.ToArray();
+ var vertices = surface.Vertices.ToArray();
+ surface = surface with
+ {
+ Vertices = vertices,
+ SkinWeights = [new(0, weights), surface.SkinWeights[1], surface.SkinWeights[2]],
+ };
+ var binding = new HumanoidSkinningBinding(surface, skeleton);
+ var solved = Solve(skeleton, 70);
+ var before = binding.Evaluate(solved).ToArray();
+ weights[0] = new(0, 1);
+ vertices[0] = vertices[0] with { Position = new(1000, 1000, 1000) };
+ Assert.Equal(before, binding.Evaluate(solved));
+ }
+
+ [Fact]
+ public void StaleShapeAndRestSkeletonAreRejected()
+ {
+ var (surface, skeleton) = Fixture();
+ var binding = new HumanoidSkinningBinding(surface, skeleton, 1);
+ Assert.Throws<InvalidOperationException>(() => binding.Evaluate(Solve(skeleton, 45)));
+ binding = new(surface, skeleton);
+ var differentRest = skeleton with { RestPoseId = "different-rest" };
+ Assert.Throws<InvalidOperationException>(() => binding.Evaluate(Solve(differentRest, 45)));
+ }
+
+ [Theory]
+ [InlineData(-.1)]
+ [InlineData(double.NaN)]
+ [InlineData(double.PositiveInfinity)]
+ public void InvalidWeightsAreRejected(double value)
+ {
+ var (surface, skeleton) = Fixture();
+ surface = surface with
+ {
+ SkinWeights = [new(0, [new(1, value), new(2, 1 - value)]),
+ surface.SkinWeights[1], surface.SkinWeights[2]],
+ };
+ Assert.Throws<InvalidDataException>(() => new HumanoidSkinningBinding(surface, skeleton));
+ }
+
+ [Fact]
+ public void DuplicateJointInfluencesAreRejected()
+ {
+ var (surface, skeleton) = Fixture();
+ surface = surface with
+ {
+ SkinWeights = [new(0, [new(1, .5), new(1, .5)]),
+ surface.SkinWeights[1], surface.SkinWeights[2]],
+ };
+ Assert.Throws<InvalidDataException>(() => new HumanoidSkinningBinding(surface, skeleton));
+ }
+
+ [Fact]
+ public void ScaleShearAndNonfiniteFramesAreRejected()
+ {
+ Assert.Throws<InvalidDataException>(() =>
+ HumanoidSkinDualQuaternion.FromRigidTransform(Matrix4x4.CreateScale(2)));
+ var shear = Matrix4x4.Identity;
+ shear.M12 = .5f;
+ Assert.Throws<InvalidDataException>(() => HumanoidSkinDualQuaternion.FromRigidTransform(shear));
+ var nonfinite = Matrix4x4.Identity;
+ nonfinite.M14 = float.NaN;
+ Assert.Throws<InvalidDataException>(() => HumanoidSkinDualQuaternion.FromRigidTransform(nonfinite));
+ }
+
+ [Fact]
+ public void CorrectiveActivatesFromSolvedAnatomicalFlexionAndRetainsItsData()
+ {
+ var (surface, skeleton) = Fixture();
+ var deltas = new[] { new HumanoidVertexCorrection(0, new(0, -10, -17)) };
+ var shape = new HumanoidPoseCorrective("hip", HumanoidJointKind.LeftHip, 30, 90, deltas);
+ var binding = new HumanoidSkinningBinding(surface, skeleton, correctives: [shape]);
+ Assert.Equal(0, binding.ObserveCorrectives(Solve(skeleton, 20))["hip"]);
+ Assert.Equal(.5, binding.ObserveCorrectives(Solve(skeleton, 60))["hip"], 5);
+ Assert.Equal(1, binding.ObserveCorrectives(Solve(skeleton, 90))["hip"]);
+ var before = binding.Evaluate(Solve(skeleton, 90)).ToArray();
+ deltas[0] = new(0, new(1000, 1000, 1000));
+ Assert.Equal(before, binding.Evaluate(Solve(skeleton, 90)));
+ var uncorrected = new HumanoidSkinningBinding(surface, skeleton);
+ Assert.NotEqual(uncorrected.Evaluate(Solve(skeleton, 90))[0], before[0]);
+ }
+
+ [Fact]
+ public void InvalidCorrectiveBindingsAndDuplicateNamesAreRejected()
+ {
+ var (surface, skeleton) = Fixture();
+ var valid = new HumanoidPoseCorrective("hip", HumanoidJointKind.LeftHip, 30, 90,
+ [new(0, new(0, 0, -10))]);
+ Assert.Throws<InvalidDataException>(() =>
+ new HumanoidSkinningBinding(surface, skeleton, correctives: [valid, valid]));
+ var wrongIndex = valid with { Vertices = [new(999, Vector3.Zero)] };
+ Assert.Throws<InvalidDataException>(() =>
+ new HumanoidSkinningBinding(surface, skeleton, correctives: [wrongIndex]));
+ var wrongCurve = valid with { FullFlexionDegrees = 30 };
+ Assert.Throws<InvalidDataException>(() =>
+ new HumanoidSkinningBinding(surface, skeleton, correctives: [wrongCurve]));
+ }
+
+ [Fact]
+ public void GameplayArtifactRoundtripUsesExplicitSourceGeneratedSerialization()
+ {
+ var (surface, skeleton) = Fixture();
+ var provenance = CanonicalAdultTemplate.Create().Provenance;
+ var shape = new HumanoidPoseCorrective("hip", HumanoidJointKind.LeftHip, 30, 90,
+ [new(0, new(0, -10, -17))]);
+ var artifact = new HumanoidGameplayBodyArtifact(HumanoidGameplayBody.Schema,
+ "test-body", surface, skeleton, [shape], provenance);
+ var path = Path.Combine(AppContext.BaseDirectory, "body-" + Guid.NewGuid() + ".json");
+ try
+ {
+ HumanoidGameplayBody.Save(artifact, path);
+ var body = HumanoidGameplayBody.Load(path);
+ var pose = body.Solve("hip90", [new(HumanoidJointKind.LeftHip, 90)]).Pose!;
+ var reference = new HumanoidSkinningBinding(surface, skeleton, correctives: [shape]);
+ Assert.Equal(reference.Evaluate(Solve(skeleton, 90)), body.Evaluate(pose).Positions);
+ Assert.Equal("test-body", body.Id);
+ Assert.Equal(1, body.ObserveCorrectives(pose)["hip"]);
+ Assert.Throws<InvalidDataException>(() => HumanoidArtifactIO.Load(path));
+ }
+ finally
+ {
+ File.Delete(path);
+ }
+ }
+
+ private static SolvedHumanoidPose Solve(HumanoidSkeleton skeleton, double angle)
+ {
+ var result = HumanoidKinematicSolver.Solve(skeleton,
+ new("test", skeleton.SkeletonId, skeleton.RestPoseId, 0,
+ [new(HumanoidJointKind.LeftHip, angle)]));
+ Assert.True(result.IsSolved, string.Join("; ", result.Diagnostics));
+ return result.Pose!;
+ }
+
+ private static (HumanoidSurface Surface, HumanoidSkeleton Skeleton) Fixture()
+ {
+ var root = Matrix4x4.Identity;
+ var hip = Matrix4x4.CreateTranslation(-10, 0, 100);
+ Matrix4x4.Invert(hip, out var inverse);
+ var skeleton = new HumanoidSkeleton("skin-fixture", "rest", "row-vector",
+ [
+ new("root", HumanoidJointKind.Root, AnatomicalSide.Center, null,
+ HumanoidTransform.Identity, root, root),
+ new("pelvis", HumanoidJointKind.Pelvis, AnatomicalSide.Center, 0,
+ HumanoidTransform.Identity, root, root),
+ new("hip", HumanoidJointKind.LeftHip, AnatomicalSide.Left, 1,
+ HumanoidTransform.FromTranslation(new(-10, 0, 100)), hip, inverse),
+ ], new Dictionary<HumanoidJointKind, HumanoidJointKind>());
+ var surface = new HumanoidSurface("skin-fixture", "triangles", "fixed",
+ [
+ new("a", new(-8, 0, 90), HumanoidRegionKind.LeftThigh, 0),
+ new("b", new(-10, 2, 90), HumanoidRegionKind.LeftThigh, 1),
+ new("c", new(-12, 0, 90), HumanoidRegionKind.LeftThigh, 2),
+ ], [new("triangle", 0, 1, 2, HumanoidRegionKind.LeftThigh, null)], [], null,
+ [
+ new(0, [new(1, .5), new(2, .5)]),
+ new(1, [new(1, .5), new(2, .5)]),
+ new(2, [new(1, .5), new(2, .5)]),
+ ], [], new Dictionary<HumanoidRegionKind, HumanoidRegionKind>());
+ return (surface, skeleton);
+ }
+}
diff --git a/Aetheris.Humanoid/HumanoidDeformationContext.cs b/Aetheris.Humanoid/HumanoidDeformationContext.cs
index 5bbbcf4c..9996de9c 100644
--- a/Aetheris.Humanoid/HumanoidDeformationContext.cs
+++ b/Aetheris.Humanoid/HumanoidDeformationContext.cs
@@ -98,6 +98,9 @@ public static class HumanoidDeformationCandidates
if (!Enum.IsDefined(spec.Method) || !double.IsFinite(spec.WeightExponent) || spec.WeightExponent is < .5 or > 2)
throw new ArgumentException("Bounded transition generators support exponents [0.5,2].");
var output = new Point3D[context.Vertices.Count];
+ var palette = spec.Method == TransitionBlendMethod.DualQuaternion
+ ? context.SkinTransforms.Select(HumanoidSkinDualQuaternion.FromRigidTransform).ToArray()
+ : null;
for (var i = 0; i < output.Length; i++)
{
var patch = context.Vertices[i];
@@ -113,29 +116,10 @@ public static class HumanoidDeformationCandidates
Vector3 transformed;
if (spec.Method == TransitionBlendMethod.Linear)
transformed = modified.Aggregate(Vector3.Zero, (sum, w) => sum + Vector3.Transform(source, context.SkinTransforms[w.JointIndex]) * (float)w.Weight);
- else transformed = DualQuaternionPoint(source, modified, context.SkinTransforms);
+ else transformed = HumanoidSkinningBinding.Blend(modified, palette!).TransformPoint(source);
output[i] = new(transformed.X, transformed.Y, transformed.Z);
}
return new(spec.Id, Array.AsReadOnly(output), $"{spec.Method}; normalized generated X1 weights exponent={spec.WeightExponent:R}; fixed patch boundary; no source-weight claim");
}
- private static Vector3 DualQuaternionPoint(Vector3 point, IReadOnlyList<JointWeight> weights, IReadOnlyList<Matrix4x4> transforms)
- {
- var real = new Quaternion(0, 0, 0, 0); var dual = real;
- var reference = Quaternion.CreateFromRotationMatrix(transforms[weights[0].JointIndex]);
- foreach (var w in weights)
- {
- var m = transforms[w.JointIndex];
- var q = Quaternion.Normalize(Quaternion.CreateFromRotationMatrix(m));
- var d = Quaternion.Multiply(new Quaternion(m.Translation, 0), q) * .5f;
- var sign = Quaternion.Dot(reference, q) < 0 ? -1 : 1;
- real += q * (float)(w.Weight * sign); dual += d * (float)(w.Weight * sign);
- }
- var length = real.Length();
- if (length < 1e-8f) throw new InvalidOperationException("Degenerate dual-quaternion blend.");
- real *= 1 / length; dual *= 1 / length;
- dual -= real * Quaternion.Dot(real, dual);
- var translation = Quaternion.Multiply(dual, Quaternion.Conjugate(real)) * 2;
- return Vector3.Transform(point, real) + new Vector3(translation.X, translation.Y, translation.Z);
- }
}
diff --git a/Aetheris.Humanoid/HumanoidGameplayBody.cs b/Aetheris.Humanoid/HumanoidGameplayBody.cs
new file mode 100644
index 00000000..082846f0
--- /dev/null
+++ b/Aetheris.Humanoid/HumanoidGameplayBody.cs
@@ -0,0 +1,99 @@
+using System.Collections.ObjectModel;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+
+namespace Aetheris.Humanoid;
+
+public sealed record HumanoidGameplayBodyArtifact(
+ string Schema, string Id, HumanoidSurface Surface, HumanoidSkeleton Skeleton,
+ IReadOnlyList<HumanoidPoseCorrective> Correctives, HumanoidProvenance Provenance);
+
+/// <summary>
+/// Explicitly loaded gameplay body, separate from CanonicalHumanoid admission.
+/// A pose solve and surface screen remain independent; failed surfaces are diagnostic output.
+/// </summary>
+public sealed class HumanoidGameplayBody
+{
+ public const string Schema = "aetheris.humanoid.gameplay-body.v1";
+ private readonly HumanoidSkinningBinding binding;
+
+ public HumanoidGameplayBody(HumanoidGameplayBodyArtifact artifact)
+ {
+ ArgumentNullException.ThrowIfNull(artifact);
+ if (artifact.Schema != Schema || string.IsNullOrWhiteSpace(artifact.Id) ||
+ artifact.Surface is null || artifact.Skeleton is null || artifact.Correctives is null ||
+ artifact.Provenance is null || artifact.Surface.Faces is null || artifact.Surface.Vertices is null ||
+ artifact.Surface.SkinWeights is null || artifact.Skeleton.Joints is null ||
+ artifact.Skeleton.Symmetry is null || artifact.Surface.Faces.Count == 0 ||
+ artifact.Surface.Faces.Any(face => face.A < 0 || face.B < 0 || face.C < 0 ||
+ face.A >= artifact.Surface.Vertices.Count || face.B >= artifact.Surface.Vertices.Count ||
+ face.C >= artifact.Surface.Vertices.Count || face.A == face.B || face.A == face.C || face.B == face.C))
+ {
+ throw new InvalidDataException("HUM313: Incomplete or unsupported gameplay body artifact.");
+ }
+
+ Surface = artifact.Surface with
+ {
+ Vertices = Array.AsReadOnly(artifact.Surface.Vertices.ToArray()),
+ Faces = Array.AsReadOnly(artifact.Surface.Faces.ToArray()),
+ SkinWeights = Array.AsReadOnly(artifact.Surface.SkinWeights.Select(skin =>
+ skin with { Weights = Array.AsReadOnly(skin.Weights.ToArray()) }).ToArray()),
+ };
+ Skeleton = artifact.Skeleton with
+ {
+ Joints = Array.AsReadOnly(artifact.Skeleton.Joints.ToArray()),
+ Symmetry = new ReadOnlyDictionary<HumanoidJointKind, HumanoidJointKind>(
+ artifact.Skeleton.Symmetry.ToDictionary(pair => pair.Key, pair => pair.Value)),
+ };
+ Id = artifact.Id;
+ binding = new(Surface, Skeleton, correctives: artifact.Correctives);
+ }
+
+ public string Id { get; }
+ public HumanoidSurface Surface { get; }
+ public HumanoidSkeleton Skeleton { get; }
+
+ public HumanoidSolveResult Solve(string poseId, IReadOnlyList<AnatomicalJointRequest> requests)
+ {
+ return HumanoidKinematicSolver.Solve(Skeleton,
+ new(poseId, Skeleton.SkeletonId, Skeleton.RestPoseId, 0, requests));
+ }
+
+ public HumanoidSurfaceEvaluation Evaluate(SolvedHumanoidPose pose)
+ {
+ var positions = binding.Evaluate(pose);
+ var evidence = HumanoidConstrainedSurface.Inspect(Surface, Skeleton, pose.GlobalTransforms, positions);
+ return new(positions, evidence);
+ }
+
+ public IReadOnlyList<HumanoidSkinDualQuaternion> CreatePalette(SolvedHumanoidPose pose) =>
+ binding.CreatePalette(pose);
+
+ public IReadOnlyDictionary<string, double> ObserveCorrectives(SolvedHumanoidPose pose) =>
+ binding.ObserveCorrectives(pose);
+
+ public static HumanoidGameplayBody Load(string path)
+ {
+ using var stream = File.OpenRead(path);
+ if (stream.Length > 128L * 1024 * 1024)
+ {
+ throw new InvalidDataException("HUM313: Gameplay body exceeds the 128 MiB artifact budget.");
+ }
+ var artifact = JsonSerializer.Deserialize(stream, HumanoidGameplayJson.Default.HumanoidGameplayBodyArtifact)
+ ?? throw new InvalidDataException("HUM313: Gameplay body artifact is empty.");
+ return new(artifact);
+ }
+
+ public static void Save(HumanoidGameplayBodyArtifact artifact, string path)
+ {
+ _ = new HumanoidGameplayBody(artifact);
+ Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!);
+ using var stream = File.Create(path);
+ JsonSerializer.Serialize(stream, artifact, HumanoidGameplayJson.Default.HumanoidGameplayBodyArtifact);
+ }
+}
+
+[JsonSourceGenerationOptions(WriteIndented = true, PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
+ IncludeFields = true, UseStringEnumConverter = true)]
+[JsonSerializable(typeof(HumanoidGameplayBodyArtifact))]
+internal partial class HumanoidGameplayJson : JsonSerializerContext;
diff --git a/Aetheris.Humanoid/HumanoidModule.cs b/Aetheris.Humanoid/HumanoidModule.cs
index 036386d7..13cf673c 100644
--- a/Aetheris.Humanoid/HumanoidModule.cs
+++ b/Aetheris.Humanoid/HumanoidModule.cs
@@ -9,7 +9,8 @@ public static class HumanoidModule
public static AetherisModule Definition { get; } = new(Id, "Humanoid", Version,
[
Capability("Humanoid.CanonicalSurface", "Versioned adult organic surface with stable topology, regions, symmetry, components, and binding triangulation."),
- Capability("Humanoid.Skeleton", "Canonical semantic skeleton, rest/bind transforms, linear blend skinning, and bounded pose evaluation."),
+ Capability("Humanoid.Skeleton",
+ "Semantic skeleton, rest/bind transforms, linear and retained dual-quaternion skinning, explicit pose correctives, and bounded pose evaluation."),
Capability("Humanoid.Landmarks", "Typed surface, joint, measurement, and attachment landmark semantics."),
Capability("Humanoid.Measurements", "Versioned adult measurement protocols with explicit pose and operands."),
Capability("Humanoid.Morphs", "Bounded stature and limb proportion controls with coherent skeleton and binding updates."),
diff --git a/Aetheris.Humanoid/HumanoidSemanticPose.cs b/Aetheris.Humanoid/HumanoidSemanticPose.cs
index 543fe87e..4c7a73e0 100644
--- a/Aetheris.Humanoid/HumanoidSemanticPose.cs
+++ b/Aetheris.Humanoid/HumanoidSemanticPose.cs
@@ -72,8 +72,14 @@ public static class HumanoidPoseSemantics
var secondFlexion = direction.Y >= 0 ? 180 - firstFlexion : -180 - firstFlexion;
var secondAbduction = NormalizeDegrees(firstAbduction + 180);
var shoulder = kind.ToString().EndsWith("Shoulder");
- var firstValid = firstFlexion >= (shoulder ? -30 : -20) && firstFlexion <= 120 &&
- firstAbduction >= (shoulder ? -30 : -25) && firstAbduction <= (shoulder ? 120 : 45);
+ // Float joint centers can place an exact domain boundary a few millionths
+ // of a degree outside it. Do not select the opposite Euler branch for that
+ // roundoff; the solve's admissible domain remains unchanged.
+ const double branchToleranceDegrees = .0001;
+ var firstValid = firstFlexion >= (shoulder ? -30 : -20) - branchToleranceDegrees &&
+ firstFlexion <= 120 + branchToleranceDegrees &&
+ firstAbduction >= (shoulder ? -30 : -25) - branchToleranceDegrees &&
+ firstAbduction <= (shoulder ? 120 : 45) + branchToleranceDegrees;
(flexion, abduction) = firstValid
? (firstFlexion, firstAbduction)
: (secondFlexion, secondAbduction);
diff --git a/Aetheris.Humanoid/HumanoidSkinning.cs b/Aetheris.Humanoid/HumanoidSkinning.cs
new file mode 100644
index 00000000..49d12dde
--- /dev/null
+++ b/Aetheris.Humanoid/HumanoidSkinning.cs
@@ -0,0 +1,236 @@
+using System.Numerics;
+using Aetheris.Kernel.Core.Math;
+
+namespace Aetheris.Humanoid;
+
+public sealed record HumanoidVertexCorrection(int VertexIndex, Vector3 DeltaMm);
+
+/// <summary>An authored pre-skin shape, activated by solved absolute anatomical flexion.</summary>
+public sealed record HumanoidPoseCorrective(
+ string Id, HumanoidJointKind Joint, double StartFlexionDegrees, double FullFlexionDegrees,
+ IReadOnlyList<HumanoidVertexCorrection> Vertices);
+
+/// <summary>Two float4 values per joint, in System.Numerics XYZW quaternion order.</summary>
+public readonly record struct HumanoidSkinDualQuaternion(Quaternion Real, Quaternion Dual)
+{
+ public static HumanoidSkinDualQuaternion FromRigidTransform(Matrix4x4 transform)
+ {
+ if (!Matrix4x4.Decompose(transform, out var scale, out var rotation, out var translation) ||
+ Vector3.Distance(scale, Vector3.One) > 1e-4f ||
+ !Finite(rotation) || !Finite(translation))
+ {
+ throw new InvalidDataException("HUM310: Dual-quaternion skinning requires finite rigid transforms.");
+ }
+
+ var reconstructed = Matrix4x4.CreateFromQuaternion(rotation) *
+ Matrix4x4.CreateTranslation(translation);
+ if (MaximumDifference(transform, reconstructed) > 1e-3f)
+ {
+ throw new InvalidDataException("HUM310: A skin transform contains shear or a non-affine frame.");
+ }
+
+ var real = Quaternion.Normalize(rotation);
+ var dual = Quaternion.Multiply(new Quaternion(translation, 0), real) * .5f;
+ return new(real, dual);
+ }
+
+ public Vector3 TransformPoint(Vector3 point)
+ {
+ var translation = Quaternion.Multiply(Dual, Quaternion.Conjugate(Real)) * 2;
+ return Vector3.Transform(point, Real) + new Vector3(translation.X, translation.Y, translation.Z);
+ }
+
+ private static float MaximumDifference(Matrix4x4 a, Matrix4x4 b)
+ {
+ float[] differences =
+ [
+ a.M11 - b.M11, a.M12 - b.M12, a.M13 - b.M13, a.M14 - b.M14,
+ a.M21 - b.M21, a.M22 - b.M22, a.M23 - b.M23, a.M24 - b.M24,
+ a.M31 - b.M31, a.M32 - b.M32, a.M33 - b.M33, a.M34 - b.M34,
+ a.M41 - b.M41, a.M42 - b.M42, a.M43 - b.M43, a.M44 - b.M44,
+ ];
+ if (differences.Any(value => !float.IsFinite(value)))
+ {
+ return float.PositiveInfinity;
+ }
+ return differences.Max(MathF.Abs);
+ }
+
+ private static bool Finite(Quaternion value) =>
+ float.IsFinite(value.X) && float.IsFinite(value.Y) &&
+ float.IsFinite(value.Z) && float.IsFinite(value.W);
+
+ private static bool Finite(Vector3 value) =>
+ float.IsFinite(value.X) && float.IsFinite(value.Y) && float.IsFinite(value.Z);
+}
+
+/// <summary>
+/// A retained rest surface and skin binding. Pose palettes are O(joints); vertex evaluation is
+/// an explicit CPU reference. The same palette can be uploaded for GPU deformation.
+/// Binding compilation is not canonical or production admission of a character asset.
+/// </summary>
+public sealed class HumanoidSkinningBinding
+{
+ private readonly HumanoidSkeleton skeleton;
+ private readonly long shapeRevision;
+ private readonly Vector3[] positions;
+ private readonly JointWeight[][] influences;
+ private readonly HumanoidPoseCorrective[] correctives;
+
+ public HumanoidSkinningBinding(HumanoidSurface surface, HumanoidSkeleton skeleton, long shapeRevision = 0,
+ IReadOnlyList<HumanoidPoseCorrective>? correctives = null)
+ {
+ ArgumentNullException.ThrowIfNull(surface);
+ ArgumentNullException.ThrowIfNull(skeleton);
+ if (surface.Vertices.Count == 0 || surface.SkinWeights.Count != surface.Vertices.Count ||
+ skeleton.Joints.Count == 0)
+ {
+ throw new InvalidDataException("HUM005: A skin binding needs a complete rest surface and skeleton.");
+ }
+
+ this.skeleton = skeleton with { Joints = Array.AsReadOnly(skeleton.Joints.ToArray()) };
+ this.shapeRevision = shapeRevision;
+ positions = new Vector3[surface.Vertices.Count];
+ influences = new JointWeight[surface.Vertices.Count][];
+ for (var index = 0; index < positions.Length; index++)
+ {
+ var point = surface.Vertices[index].Position;
+ var skin = surface.SkinWeights[index];
+ if (!double.IsFinite(point.X) || !double.IsFinite(point.Y) || !double.IsFinite(point.Z) ||
+ skin.VertexIndex != index || skin.Weights.Count == 0 ||
+ skin.Weights.Any(weight => weight.JointIndex < 0 || weight.JointIndex >= skeleton.Joints.Count ||
+ !double.IsFinite(weight.Weight) || weight.Weight < 0) ||
+ skin.Weights.Select(weight => weight.JointIndex).Distinct().Count() != skin.Weights.Count ||
+ Math.Abs(skin.Weights.Sum(weight => weight.Weight) - 1) > CanonicalAdultStandardV1.WeightTolerance)
+ {
+ throw new InvalidDataException($"HUM005: Invalid rest vertex or normalized skin binding at {index}.");
+ }
+
+ positions[index] = new((float)point.X, (float)point.Y, (float)point.Z);
+ if (!float.IsFinite(positions[index].X) || !float.IsFinite(positions[index].Y) ||
+ !float.IsFinite(positions[index].Z))
+ {
+ throw new InvalidDataException($"HUM005: Rest vertex {index} exceeds the float skinning domain.");
+ }
+ influences[index] = skin.Weights.Where(weight => weight.Weight > 0)
+ .OrderByDescending(weight => weight.Weight).ThenBy(weight => weight.JointIndex).ToArray();
+ }
+ this.correctives = (correctives ?? []).Select(corrective =>
+ {
+ if (string.IsNullOrWhiteSpace(corrective.Id) ||
+ !skeleton.Joints.Any(joint => joint.Kind == corrective.Joint) ||
+ !double.IsFinite(corrective.StartFlexionDegrees) ||
+ !double.IsFinite(corrective.FullFlexionDegrees) ||
+ corrective.FullFlexionDegrees <= corrective.StartFlexionDegrees ||
+ corrective.Vertices.Any(vertex => vertex.VertexIndex < 0 || vertex.VertexIndex >= VertexCount ||
+ !float.IsFinite(vertex.DeltaMm.X) || !float.IsFinite(vertex.DeltaMm.Y) ||
+ !float.IsFinite(vertex.DeltaMm.Z)) ||
+ corrective.Vertices.Select(vertex => vertex.VertexIndex).Distinct().Count() != corrective.Vertices.Count)
+ {
+ throw new InvalidDataException($"HUM312: Invalid pose corrective {corrective.Id}.");
+ }
+ return corrective with { Vertices = Array.AsReadOnly(corrective.Vertices.ToArray()) };
+ }).ToArray();
+ if (this.correctives.Select(corrective => corrective.Id).Distinct(StringComparer.Ordinal).Count() !=
+ this.correctives.Length)
+ {
+ throw new InvalidDataException("HUM312: Pose corrective IDs must be unique.");
+ }
+ }
+
+ public int VertexCount => positions.Length;
+ public int MaximumInfluences => influences.Max(weights => weights.Length);
+
+ public IReadOnlyList<HumanoidSkinDualQuaternion> CreatePalette(SolvedHumanoidPose pose)
+ {
+ ArgumentNullException.ThrowIfNull(pose);
+ if (pose.ShapeRevision != shapeRevision || skeleton.SkeletonId != pose.Skeleton.SkeletonId ||
+ skeleton.RestPoseId != pose.Skeleton.RestPoseId || !skeleton.Joints.SequenceEqual(pose.Skeleton.Joints))
+ {
+ throw new InvalidOperationException("HUM208: Skin binding belongs to a different rest skeleton or shape revision.");
+ }
+
+ var palette = new HumanoidSkinDualQuaternion[skeleton.Joints.Count];
+ for (var index = 0; index < palette.Length; index++)
+ {
+ var transform = skeleton.Joints[index].InverseBind * pose.GlobalTransforms[index];
+ palette[index] = HumanoidSkinDualQuaternion.FromRigidTransform(transform);
+ }
+ return Array.AsReadOnly(palette);
+ }
+
+ public IReadOnlyList<Point3D> Evaluate(SolvedHumanoidPose pose)
+ {
+ var palette = CreatePalette(pose);
+ var corrected = ApplyCorrectives(pose);
+ var result = new Point3D[positions.Length];
+ for (var index = 0; index < result.Length; index++)
+ {
+ var blended = Blend(influences[index], palette);
+ var point = blended.TransformPoint(corrected[index]);
+ result[index] = new(point.X, point.Y, point.Z);
+ }
+ return Array.AsReadOnly(result);
+ }
+
+ public IReadOnlyDictionary<string, double> ObserveCorrectives(SolvedHumanoidPose pose)
+ {
+ CreatePalette(pose);
+ return new System.Collections.ObjectModel.ReadOnlyDictionary<string, double>(
+ correctives.ToDictionary(corrective => corrective.Id,
+ corrective => Activation(corrective, pose), StringComparer.Ordinal));
+ }
+
+ private Vector3[] ApplyCorrectives(SolvedHumanoidPose pose)
+ {
+ if (correctives.Length == 0)
+ {
+ return positions;
+ }
+ var corrected = positions.ToArray();
+ foreach (var corrective in correctives)
+ {
+ var amount = (float)Activation(corrective, pose);
+ foreach (var vertex in corrective.Vertices)
+ {
+ corrected[vertex.VertexIndex] += vertex.DeltaMm * amount;
+ }
+ }
+ return corrected;
+ }
+
+ private static double Activation(HumanoidPoseCorrective corrective, SolvedHumanoidPose pose)
+ {
+ var joint = pose.Joints.FirstOrDefault(request => request.Joint == corrective.Joint);
+ var degrees = joint?.FlexionDegrees ?? 0;
+ var t = Math.Clamp((degrees - corrective.StartFlexionDegrees) /
+ (corrective.FullFlexionDegrees - corrective.StartFlexionDegrees), 0, 1);
+ return t * t * (3 - 2 * t);
+ }
+
+ internal static HumanoidSkinDualQuaternion Blend(
+ IReadOnlyList<JointWeight> weights, IReadOnlyList<HumanoidSkinDualQuaternion> palette)
+ {
+ var real = new Quaternion(0, 0, 0, 0);
+ var dual = real;
+ var reference = palette[weights[0].JointIndex].Real;
+ foreach (var weight in weights)
+ {
+ var transform = palette[weight.JointIndex];
+ var sign = Quaternion.Dot(reference, transform.Real) < 0 ? -1 : 1;
+ var amount = (float)(sign * weight.Weight);
+ real += transform.Real * amount;
+ dual += transform.Dual * amount;
+ }
+
+ var length = real.Length();
+ if (!float.IsFinite(length) || length < 1e-8f)
+ {
+ throw new InvalidDataException("HUM311: Degenerate dual-quaternion skin blend.");
+ }
+ real *= 1 / length;
+ dual *= 1 / length;
+ dual -= real * Quaternion.Dot(real, dual);
+ return new(real, dual);
+ }
+}
diff --git a/docs/public/humanoid-gameplay-body.md b/docs/public/humanoid-gameplay-body.md
new file mode 100644
index 00000000..f627587f
--- /dev/null
+++ b/docs/public/humanoid-gameplay-body.md
@@ -0,0 +1,128 @@
+# Antonia gameplay body
+
+The Antonia Polygon A-pose candidate now has an editable Blender body and an
+explicit C# gameplay-body loader. This is a qualified development base for the
+recorded pose corpus, separate from canonical adult admission. It retains the
+original admitted Antonia geometry and notice; Genesis 9 was a local visual
+reference only. No reference geometry, weights or corrective deltas were copied.
+
+## Open and customize
+
+The generated bundle is `artifacts/local/humanoid-production/`:
+
+- `antonia-gameplay.blend`: original 27,112 quads, original UV layout, 55-joint
+ rig, two hip corrective shapes, subdivision preview, simple authored materials,
+ studio lighting and a timeline pose library. Select `ANTONIA_EDITABLE_QUADS`.
+- `pose-library.json`: pose names and frame numbers. Timeline markers select the
+ corresponding keyed rig rotations and corrective amounts; no embedded script
+ execution is necessary.
+- `antonia.gameplay-body.json`: fixed 54,224 binding triangles, 27,193 vertices,
+ rest skeleton, complete weights, correctives and source provenance.
+- `runtime-evidence.json`, `blender-evidence.json`, `saved-blend-evidence.json`:
+ runtime screening, independent Blender replay and fresh-process file reopening.
+- `ANTONIA-LICENSE.txt`: retained original attribution and notice. Preserve it
+ when distributing a derivative. The proprietary reference is not bundled.
+
+The runtime uses dual-quaternion skinning. Weight changes retain central pelvis
+support, smooth elbow/knee transitions, strengthen shoulder support and enforce
+bilateral correspondence. Sparse pre-skin shapes support hip flexion using an
+explicit smoothstep activation from 30 to 90 degrees. No mesh indices or source
+UV identities are changed. Subdivision improves the editable/rendered preview;
+qualification is on the unsubdivided binding mesh.
+
+## C# usage
+
+Reference `Aetheris.Humanoid`, then load the explicitly typed body:
+
+```csharp
+using Aetheris.Humanoid;
+
+var body = HumanoidGameplayBody.Load(bodyPath);
+var result = body.Solve("sit", [
+ new(HumanoidJointKind.LeftHip, FlexionDegrees: 90),
+ new(HumanoidJointKind.RightHip, FlexionDegrees: 90),
+ new(HumanoidJointKind.LeftKnee, FlexionDegrees: 90),
+ new(HumanoidJointKind.RightKnee, FlexionDegrees: 90),
+]);
+if (!result.IsSolved)
+{
+ throw new InvalidOperationException(string.Join("; ", result.Diagnostics));
+}
+
+var pose = result.Pose!;
+var surface = body.Evaluate(pose);
+var palette = body.CreatePalette(pose);
+var correctiveAmounts = body.ObserveCorrectives(pose);
+```
+
+Coordinates are millimetres, +X right, +Y forward, +Z up. Pose requests are
+absolute anatomical states, not source-bone rotation deltas. Unspecified joints
+retain the A-pose rest; shoulder rest abduction is 35 degrees. Solving legal
+joint coordinates and screening the deformed surface are separate operations:
+inspect `surface.Evidence.IsAdmissible` before admitting a pose. Failed screens
+remain available as diagnostic geometry.
+
+Bindings snapshot their inputs and reject mismatched rest/shape revisions.
+The gameplay loader uses source-generated JSON metadata and requires no
+reflection-based discovery. `HumanoidArtifactIO.Load` continues to reject this
+artifact as a canonical humanoid.
+
+`CreatePalette` prepares two float4 quaternions per joint in XYZW order, in
+O(joints) time. `Evaluate` is the CPU reference, including corrective application.
+An Aurelian Vulkan skinning adapter is **not implemented or qualified here**.
+It must apply pre-skin correctives and the same normalized dual-quaternion blend,
+including quaternion sign alignment. Preserve all six possible influences.
+
+Ordinary glTF/GLB skinning does not encode this dual-quaternion convention.
+Do not export this body and silently substitute linear-blend skinning: the
+qualification would no longer apply. Use the Blender authoring asset and typed
+body artifact until the engine's matching skinning path is available.
+
+## Reproduce
+
+With the retained X1, RERIG and REST-X2 inputs and installed Blender:
+
+```powershell
+pwsh -File scripts/qualify-antonia-gameplay.ps1
+# Authoring iterations after the full .NET gate has already passed:
+pwsh -File scripts/qualify-antonia-gameplay.ps1 -SkipFullTests
+```
+
+The wrapper builds/tests, generates the recipe, reloads the serialized C# body,
+exports actual solved rotations, replays every pose in Blender, saves/reopens
+the editable file in a fresh process and checks vertex parity. Missing retained
+inputs fail with their paths; the wrapper downloads nothing. Earlier input
+reproduction is described in [humanoid research](humanoid-research.md) and the
+REST-X1/X2 and RERIG release records. Generated outputs stay ignored and local.
+
+Optional local visual comparison, requiring the retained Genesis reference:
+
+```powershell
+& 'C:\Program Files\Blender Foundation\Blender 5.2\blender.exe' --background --factory-startup --disable-autoexec --python-exit-code 1 --python scripts/render-antonia-gameplay-comparison.py
+python scripts/assemble-antonia-review.py
+```
+
+That comparison uses the same Antonia pose rotations before/after, and a fixed
+neutral scale for the separately posed reference. Genesis hip90 actually reaches
+87.519 degrees; its column is a visual benchmark, not numerical pose parity.
+Reference renders remain local and are not embedded in the open body.
+
+## Qualified scope and limits
+
+The 53-case corpus covers bilateral shoulder/elbow/hip/knee holdouts, lowered
+arms, forward/backward strides, a bilateral walking key pose, two-handed aiming,
+seated and squat poses. Every intended case passes the unchanged surface screen;
+maximum Blender/runtime vertex difference is 0.006363 mm. Fresh-process Blender
+reopening verifies eight representative poses within 0.000069 mm. The maximum
+qualified edge distortion ratio is 3.435, below the existing 4x ceiling.
+
+The two 100-degree hip stress poses still fail with five/six reversal flags.
+The screen measures edge distortion, collapsed triangles and a dominant-bone
+normal reversal proxy; it is not an exact self-intersection proof. Discrete poses
+do not qualify every interpolated animation or arbitrary twist combination.
+Deep crouches and large hip flexion need further authored correction work.
+
+The body is a usable base, not a complete DAZ-grade character product: facial
+animation, hair, clothing, LODs, production texture maps, full-body retargeting,
+candidate-specific morph/attachment admission and GPU integration remain future
+work. No automatic canonical promotion is performed.
diff --git a/docs/public/humanoid-research.md b/docs/public/humanoid-research.md
index 1baa8fb2..76e8b460 100644
--- a/docs/public/humanoid-research.md
+++ b/docs/public/humanoid-research.md
@@ -11,6 +11,9 @@ evaluates A-pose preparation through Aetheris's normal skin evaluator. Its
output is an `AntoniaAdoptionCandidate`, **not** a `CanonicalHumanoid`.
Candidate loading as a canonical runtime artifact is rejected.
+For the separately qualified editable body, retained dual-quaternion skinning
+and C# gameplay loader, see [Antonia gameplay body](humanoid-gameplay-body.md).
+
From the repository root:
```powershell
diff --git a/docs/release/HUMANOID-GAMEPLAY-X1.md b/docs/release/HUMANOID-GAMEPLAY-X1.md
new file mode 100644
index 00000000..38d25939
--- /dev/null
+++ b/docs/release/HUMANOID-GAMEPLAY-X1.md
@@ -0,0 +1,73 @@
+# HUMANOID-GAMEPLAY-X1 — Antonia development body
+
+2026-10-08. Success for a bounded editable gameplay body and typed runtime
+deformation path. This is not canonical adult promotion or an unrestricted
+production-character certification.
+
+## Delivered
+
+- Retained admitted original Antonia geometry, original quad topology and UVs.
+- Bilateral weights, central pelvis support, smooth hinge transitions and
+ shoulder support; no four-influence truncation.
+- Shared retained dual-quaternion skin binding, source-generated gameplay JSON,
+ two sparse authored hip flexion correctives, explicit anatomical activation.
+- Editable Blender rig, subdivision preview, own simple materials and 55-pose
+ timeline library. Fresh-process reopening works with script execution disabled.
+- Reproducible recipe and fail-closed qualification in
+ `scripts/qualify-antonia-gameplay.ps1`; local before/after/reference review.
+- Fixed negative-flexion boundary measurement selecting an incorrect Euler
+ branch due to float roundoff. Joint-domain constraints are unchanged.
+
+## Evidence
+
+The original LBS baseline was replayed in Blender. The final body was serialized,
+reloaded and evaluated in C#, then independently replayed from solved local
+quaternions in Blender. Both use the existing edge-distortion and reversal-proxy
+screen; its thresholds were not weakened.
+
+| Pose | Baseline maximum edge ratio / flags | Final maximum edge ratio / flags |
+| --- | ---: | ---: |
+| Hip 90 | 9.059 / 71 | 3.408 / 0 |
+| Knee 90 | 5.624 / 28 | 2.133 / 0 |
+| Elbow 120 | 7.018 / 22 | 2.334 / 0 |
+| Seated | 31.079 / 288 | 3.435 / 0 |
+| Squat | 32.422 / 221 | 3.014 / 0 |
+
+All 53 intended cases pass the runtime screen with no collapsed triangles or
+reversal flags. Maximum C#/Blender vertex difference is 0.006363 mm; maximum
+semantic residual is 0.000053 degrees. Eight saved-file poses reopen within
+0.000069 mm. Topology: 27,193 vertices, 27,112 editable quads, 54,224 binding
+triangles, 108,448 UV loops, 55 joints.
+
+Local evidence is under `artifacts/local/humanoid-production/`; raw trials,
+reference renders and generated character files remain ignored. The Blender
+file contains no Genesis payload. The local Genesis comparison uses fixed rest
+scale; its hip90 pose is actually 87.519 degrees and is not numeric pose parity.
+
+Validation: full Release build (zero errors, two existing WASM warnings), 86
+focused humanoid tests, one source-generated gameplay roundtrip with JSON
+reflection disabled, and 4,408 serial solution tests across 21 assemblies
+(zero failures/skips). Actual Blender replay and fresh-process saved-file
+reopening also pass. The full solution command was:
+
+```powershell
+dotnet test Aetheris.slnx -c Release --no-build -m:1 --logger trx --results-directory artifacts/local/humanoid-production/full-tests-final -v quiet -- RunConfiguration.MaxCpuCount=1
+```
+
+The complete asset wrapper exits zero with `ANTONIA_GAMEPLAY_QUALIFIED`.
+See the generated TRX and logs for exact command results.
+
+## Remaining limits
+
+Left/right hip100 stress poses retain five/six reversal flags. Screening does
+not prove absence of self-intersections, qualify every interpolated animation,
+or admit arbitrary twist combinations. No automatic canonical measurement,
+morph or attachment admission is added for Antonia.
+
+The CPU skinning reference and GPU-ready palette are implemented; Aurelian
+Vulkan dispatch is not. Ordinary glTF skinning cannot silently replace the DQS
+contract. Hair, clothing, facial animation, LODs and production texture maps are
+outside this body's qualification. Genesis geometry, weights and morph deltas
+were not transferred; no tools or assets were downloaded for this work.
+
+Usage and reproduction: [Antonia gameplay body](../public/humanoid-gameplay-body.md).
diff --git a/scripts/assemble-antonia-review.py b/scripts/assemble-antonia-review.py
new file mode 100644
index 00000000..7412bae5
--- /dev/null
+++ b/scripts/assemble-antonia-review.py
@@ -0,0 +1,49 @@
+"""Assemble existing local renders into a labelled visual review sheet."""
+
+from pathlib import Path
+
+from PIL import Image, ImageDraw, ImageFont
+
+
+ROOT = Path(__file__).resolve().parents[1]
+BUNDLE = ROOT / "artifacts/local/humanoid-production"
+
+
+def main():
+ column_width = 360
+ row_height = 440
+ header_height = 90
+ sheet = Image.new("RGB", (column_width * 3, header_height + row_height * 4), "#24282d")
+ draw = ImageDraw.Draw(sheet)
+ font = ImageFont.truetype("C:/Windows/Fonts/arial.ttf", 19)
+ small_font = ImageFont.truetype("C:/Windows/Fonts/arial.ttf", 15)
+ titles = ("Previous A-pose weights / LBS", "Improved Antonia / DQS", "Local Genesis 9 reference")
+ for column, title in enumerate(titles):
+ draw.text((column * column_width + 12, 16), title, fill="white", font=font)
+ draw.text((12, 51), "Identical Antonia requests; Genesis is a separate visual benchmark.",
+ fill="#c8cdd2", font=small_font)
+ poses = ("hip90", "knee90", "elbow120", "shoulder120")
+ for row, pose in enumerate(poses):
+ paths = (
+ BUNDLE / "comparison" / f"before--{pose}.png",
+ BUNDLE / "renders" / f"candidate--{pose}.png",
+ BUNDLE / "comparison" / f"genesis--{pose}.png",
+ )
+ for column, path in enumerate(paths):
+ with Image.open(path) as source:
+ rendered = source.convert("RGB")
+ rendered.thumbnail((column_width, row_height - 35))
+ x = column * column_width + (column_width - rendered.width) // 2
+ y = header_height + row * row_height + 35
+ sheet.paste(rendered, (x, y))
+ label = pose
+ if column == 2 and pose == "hip90":
+ label += " (actual 87.519 degrees)"
+ draw.text((column * column_width + 12, y - 27), label, fill="white", font=small_font)
+ output = BUNDLE / "comparison" / "review-sheet.png"
+ sheet.save(output)
+ print(output)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/build-antonia-gameplay.py b/scripts/build-antonia-gameplay.py
new file mode 100644
index 00000000..61d77b60
--- /dev/null
+++ b/scripts/build-antonia-gameplay.py
@@ -0,0 +1,401 @@
+"""Build the open Antonia gameplay candidate and independently replay Aetheris poses.
+
+Uses the existing admitted Antonia geometry, never Genesis geometry or deltas.
+Generated meshes, binary parity samples and render evidence stay in artifacts/local.
+"""
+
+import argparse
+import importlib
+import json
+from pathlib import Path
+import sys
+
+import bpy
+import numpy as np
+from mathutils import Quaternion, Vector
+
+sys.path.insert(0, str(Path(__file__).parent))
+study = importlib.import_module("humanoid-production-study")
+rest_study = study.rest_study
+h = study.helpers
+ROOT = study.ROOT
+
+
+def selected_weights(surface, rest, rig, field):
+ edited = study.anatomical_weights(field, surface, rest, rig, .45, .16, elbow_width=.10)
+ edited = study.metrics.brush_gain(edited, rest, rig, "Shoulder", .16, 1.2)
+ return study.symmetric_weights(edited, surface)
+
+
+def corrective_shapes(rest, rig):
+ result = []
+ for side in ("Left", "Right"):
+ sign = -1 if side == "Left" else 1
+ center = np.array((sign * .09, .065, rig.data.bones[side + "Hip"].head_local.z + .035))
+ radius = np.array((.09, .075, .085)) * 1.25
+ distance = (rest - center) / radius
+ influence = np.exp(-np.sum(distance ** 2, axis=1) * 2)
+ delta = influence[:, None] * np.array((0, -.01, -.017))
+ delta[np.linalg.norm(delta, axis=1) < 1e-6] = 0
+ result.append((side, delta))
+ return result
+
+
+def pose_corpus():
+ result = study.corpus()
+ for side in ("Left", "Right"):
+ for angle in (-20, 20):
+ result.append(dict(name=f"{side.lower()}-hip-stride-{angle}", requested=[
+ dict(joint=side + "Hip", flexionDegrees=angle),
+ ]))
+ for angle in (0, 15, 45):
+ result.append(dict(name=f"{side.lower()}-shoulder-low-{angle}", requested=[
+ dict(joint=side + "Shoulder", abductionDegrees=angle),
+ ]))
+ for angle in (-25, 30, 60):
+ result.append(dict(name=f"{side.lower()}-shoulder-flex-{angle}", requested=[
+ dict(joint=side + "Shoulder", flexionDegrees=angle, abductionDegrees=35),
+ ]))
+ for angle in (65, 105):
+ result.append(dict(name=f"{side.lower()}-elbow-{angle}", requested=[
+ dict(joint=side + "Shoulder", abductionDegrees=35),
+ dict(joint=side + "Elbow", flexionDegrees=angle),
+ ]))
+ for angle in (75, 110):
+ result.append(dict(name=f"{side.lower()}-shoulder-{angle}", requested=[
+ dict(joint=side + "Shoulder", abductionDegrees=angle),
+ ]))
+ result.append(dict(name="walking-bilateral", requested=[
+ dict(joint="LeftHip", flexionDegrees=30),
+ dict(joint="RightHip", flexionDegrees=-20),
+ dict(joint="LeftKnee", flexionDegrees=35),
+ dict(joint="RightKnee", flexionDegrees=5),
+ dict(joint="LeftShoulder", flexionDegrees=-20, abductionDegrees=20),
+ dict(joint="RightShoulder", flexionDegrees=20, abductionDegrees=20),
+ dict(joint="LeftElbow", flexionDegrees=20),
+ dict(joint="RightElbow", flexionDegrees=20),
+ ]))
+ result.append(dict(name="aim-two-handed", requested=[
+ dict(joint="LeftShoulder", flexionDegrees=65, abductionDegrees=15),
+ dict(joint="RightShoulder", flexionDegrees=65, abductionDegrees=15),
+ dict(joint="LeftElbow", flexionDegrees=60),
+ dict(joint="RightElbow", flexionDegrees=60),
+ ]))
+ for case in result:
+ case["role"] = "qualification"
+ if any(request["joint"].endswith("Hip") and request.get("flexionDegrees", 0) > 90
+ for request in case["requested"]):
+ case["role"] = "stress"
+ return result
+
+
+def inputs(out):
+ surface, rig, body, rest, triangles, scene, field, mapping = study.setup()
+ edited = selected_weights(surface, rest, rig, field)
+ baseline = h.read(ROOT / "artifacts/local/humanoid-rest-x2/selected-weights.json")
+ portable = dict(baseline)
+ portable["skinning"] = "dual-quaternion"
+ portable["maxInfluences"] = max(map(len, edited))
+ portable["provenance"] = dict(
+ source="Original open Antonia base geometry; corrected A-pose weights and authored hip shapes",
+ steps=["symmetry-pair averaging", "central pelvis retention strength 0.45",
+ "knee smooth transition half-width 160 mm", "elbow smooth transition half-width 100 mm",
+ "shoulder support gain 1.2 radius 160 mm with bilateral averaging",
+ "dual-quaternion skinning", "bilateral pre-skin hip corrective at 30..90 degrees"],
+ scriptSha256=h.sha(__file__), weightScriptSha256=h.sha(study.__file__),
+ blender=bpy.app.version_string, proprietaryGeometryOrDeltasUsed=False,
+ )
+ portable["vertices"] = [dict(vertexId=vertex["id"], weights=[
+ dict(boneId=name, weight=value) for name, value in sorted(row.items())
+ ]) for vertex, row in zip(surface["vertices"], edited)]
+ h.write(out / "weights.json", portable)
+ correctives = []
+ for side, delta in corrective_shapes(rest, rig):
+ correctives.append(dict(
+ id=f"hip-flexion-volume.{side.lower()}", joint=side + "Hip",
+ startFlexionDegrees=30, fullFlexionDegrees=90,
+ vertices=[dict(vertexIndex=index, deltaMm=dict(
+ x=float(point[0] * 1000), y=float(point[1] * 1000), z=float(point[2] * 1000)))
+ for index, point in enumerate(delta) if np.linalg.norm(point) > 0],
+ ))
+ h.write(out / "correctives.json", correctives)
+ h.write(out / "pose-corpus.json", pose_corpus())
+ h.write(out / "recipe.json", dict(
+ schema="antonia.gameplay-recipe.v1", restPoseId=baseline["restPoseId"],
+ sourceTopologyId=surface["topologyId"], connectivityHash=surface["connectivityHash"],
+ originalNoticeSha256=h.sha(ROOT / "fixtures/Canonical/Humanoid/antonia-original-LICENSE.txt"),
+ sourceCandidateSha256=h.sha(ROOT / "artifacts/local/humanoid-x1/antonia-adoption-candidate.json"),
+ baselineWeightsSha256=h.sha(ROOT / "artifacts/local/humanoid-rest-x2/selected-weights.json"),
+ weightRecipe=portable["provenance"],
+ correctiveRecipe=dict(centerXmm=90, centerYmm=65, centerAboveHipMm=35,
+ gaussianRadiiMm=[112.5, 93.75, 106.25], deltaMm=[0, -10, -17],
+ sparseCutoffMm=.001, activation="smoothstep((absolute flexion - 30) / 60)"),
+ intendedEnvelope="Hip flexion -20..90; knee 0..110; elbow 0..120; shoulder abduction 0..120; tested flexion and combined poses",
+ canonicalPromotion=False, exportWarning="Ordinary glTF export does not preserve dual-quaternion skinning",
+ ))
+ print("ANTONIA_GAMEPLAY_INPUTS_READY", out, flush=True)
+
+
+def add_shape_keys(body, rest, shapes):
+ body.shape_key_add(name="Basis")
+ for side, delta in shapes:
+ key = body.shape_key_add(name=f"hip-flexion-volume.{side.lower()}")
+ key.data.foreach_set("co", (rest + delta).reshape(-1))
+
+
+def restore_quads(body, candidate):
+ index_map = {source: target for target, source in enumerate(candidate["sourceVertexIndices"])}
+ faces = [tuple(index_map[index] for index in polygon["sourceVertexIndices"])
+ for polygon in candidate["sourcePolygons"]]
+ mesh = bpy.data.meshes.new("Antonia original quad topology")
+ mesh.from_pydata([tuple(vertex.co) for vertex in body.data.vertices], [], faces)
+ mesh.update()
+ for polygon in mesh.polygons:
+ polygon.use_smooth = True
+ preview = body.copy()
+ preview.data = mesh
+ preview.name = "ANTONIA_EDITABLE_QUADS"
+ bpy.context.scene.collection.objects.link(preview)
+ preview.hide_render = False
+ preview.hide_set(False)
+ return preview
+
+
+def materials(body, candidate):
+ material_specs = [
+ ("Skin", (.42, .23, .15, 1), .48),
+ ("Lips", (.34, .095, .07, 1), .4),
+ ("Nails", (.48, .31, .25, 1), .3),
+ ("Sclera", (.8, .83, .76, 1), .22),
+ ("Iris", (.035, .11, .09, 1), .25),
+ ("Pupil", (.002, .002, .002, 1), .2),
+ ("Cornea", (.8, .85, .9, 1), .08),
+ ]
+ for name, color, roughness in material_specs:
+ material = bpy.data.materials.new("Antonia." + name)
+ material.diffuse_color = color
+ material.use_nodes = True
+ shader = material.node_tree.nodes.get("Principled BSDF")
+ shader.inputs["Base Color"].default_value = color
+ shader.inputs["Roughness"].default_value = roughness
+ if name == "Cornea":
+ shader.inputs["Transmission Weight"].default_value = 1
+ shader.inputs["IOR"].default_value = 1.376
+ if name == "Skin":
+ shader.inputs["Subsurface Weight"].default_value = .08
+ body.data.materials.append(material)
+ for polygon, source in zip(body.data.polygons, candidate["sourcePolygons"]):
+ name = source["material"]
+ index = 0
+ if name == "lips":
+ index = 1
+ elif name.startswith("nails"):
+ index = 2
+ elif name.startswith("sclera"):
+ index = 3
+ elif name.startswith("iris"):
+ index = 4
+ elif name.startswith("pupil"):
+ index = 5
+ elif name.startswith("cornea"):
+ index = 6
+ polygon.material_index = index
+
+
+def restore_source_uvs(body, candidate):
+ path = ROOT / "artifacts/local/humanoid-x1/source/Antonia-1.2.obj"
+ admission = h.read(ROOT / "fixtures/Canonical/Humanoid/antonia-original.sidecar.json")
+ expected = next(item["sha256"] for item in admission["files"] if item["localName"] == path.name)
+ if h.sha(path) != expected:
+ raise RuntimeError("Original Antonia geometry hash mismatch before UV restoration.")
+ uvs = []
+ faces = []
+ for line in path.read_text().splitlines():
+ if line.startswith("vt "):
+ uvs.append(tuple(float(value) for value in line.split()[1:3]))
+ elif line.startswith("f "):
+ faces.append([tuple(int(value) - 1 for value in token.split("/")[:2])
+ for token in line.split()[1:]])
+ layer = body.data.uv_layers.new(name="Antonia original UV")
+ for polygon, source in zip(body.data.polygons, candidate["sourcePolygons"]):
+ face = faces[source["sourceFaceIndex"]]
+ if [corner[0] for corner in face] != source["sourceVertexIndices"]:
+ raise RuntimeError("Original UV face identity mismatch.")
+ for loop_index, corner in zip(polygon.loop_indices, face):
+ layer.data[loop_index].uv = uvs[corner[1]]
+
+
+def replay(out):
+ surface, rig, body, rest, triangles, scene, field, mapping = study.setup()
+ edited = selected_weights(surface, rest, rig, field)
+ h.assign(body, edited)
+ body.modifiers[0].use_deform_preserve_volume = True
+ shapes = corrective_shapes(rest, rig)
+ add_shape_keys(body, rest, shapes)
+ exact = {case["name"]: case for case in h.read(out / "pose-transforms.json")}
+ output = out / "blender"
+ output.mkdir(exist_ok=True)
+ renders = out / "renders"
+ renders.mkdir(exist_ok=True)
+ records = []
+ for case in pose_corpus():
+ rest_study.apply_semantic(rig, mapping, [])
+ transform = exact[case["name"]]
+ for rotation in transform["localRotations"]:
+ rig.pose.bones[rotation["joint"]].rotation_quaternion = Quaternion(
+ (rotation["w"], rotation["x"], rotation["y"], rotation["z"]))
+ for name, activation in transform["correctives"].items():
+ body.data.shape_keys.key_blocks[name].value = activation
+ bpy.context.view_layer.update()
+ posed = h.positions(body)
+ (posed * 1000).astype("<f4").tofile(output / f"{case['name']}.positions.f32")
+ measured = study.metrics.measure(rest, posed, triangles,
+ h.normal_transport(rig, edited, triangles))
+ records.append(dict(pose=case["name"], role=case["role"], metrics=measured))
+ if case["name"] in ("canonical-apose", "shoulder120", "elbow120", "hip90", "knee90", "seated", "squat", "reach"):
+ h.render(scene, body, renders / f"candidate--{case['name']}.png")
+ print(case["name"], round(measured["max"], 3), measured["reversalCount"], flush=True)
+ rest_study.apply_semantic(rig, mapping, [])
+ for key in body.data.shape_keys.key_blocks:
+ key.value = 0
+ body.hide_set(True)
+ body.hide_render = True
+ body.name = "ANTONIA_RUNTIME_BINDING_TRIANGLES"
+ candidate = h.read(ROOT / "artifacts/local/humanoid-x1/antonia-adoption-candidate.json")
+ preview = restore_quads(body, candidate)
+ h.assign(preview, edited)
+ add_shape_keys(preview, rest, shapes)
+ materials(preview, candidate)
+ restore_source_uvs(preview, candidate)
+ subdivision = preview.modifiers.new("Optional Catmull-Clark finish", "SUBSURF")
+ subdivision.levels = 1
+ subdivision.render_levels = 2
+ rig["asset_id"] = "antonia.gameplay-candidate.v1"
+ rig["skinning"] = "dual-quaternion"
+ rig["qualification"] = "runtime-evidence.json; hip100 remains an explicit stress specimen"
+ for side in ("left", "right"):
+ rig[f"hip_corrective_{side}"] = 0.0
+ name = "hip-flexion-volume." + side
+ for mesh in (preview, body):
+ driver = mesh.data.shape_keys.key_blocks[name].driver_add("value").driver
+ driver.type = "SCRIPTED"
+ variable = driver.variables.new()
+ variable.name = "amount"
+ variable.type = "SINGLE_PROP"
+ variable.targets[0].id = rig
+ variable.targets[0].data_path = f'["hip_corrective_{side}"]'
+ driver.expression = "amount"
+ pose_index = []
+ for index, case in enumerate(pose_corpus()):
+ frame = 1 + index * 10
+ transform = exact[case["name"]]
+ rest_study.apply_semantic(rig, mapping, [])
+ for rotation in transform["localRotations"]:
+ rig.pose.bones[rotation["joint"]].rotation_quaternion = Quaternion(
+ (rotation["w"], rotation["x"], rotation["y"], rotation["z"]))
+ for bone in rig.pose.bones:
+ bone.keyframe_insert(data_path="rotation_quaternion", frame=frame)
+ for side in ("left", "right"):
+ rig[f"hip_corrective_{side}"] = float(transform["correctives"]["hip-flexion-volume." + side])
+ rig.keyframe_insert(data_path=f'["hip_corrective_{side}"]', frame=frame)
+ scene.timeline_markers.new(case["name"], frame=frame)
+ pose_index.append(dict(frame=frame, pose=case["name"], role=case["role"]))
+ scene.frame_end = pose_index[-1]["frame"]
+ scene.frame_set(1)
+ h.write(out / "pose-library.json", pose_index)
+ subdivision.show_viewport = False
+ library_parity = []
+ for name in ("canonical-apose", "hip90", "seated", "elbow120", "squat"):
+ entry = next(item for item in pose_index if item["pose"] == name)
+ scene.frame_set(entry["frame"])
+ bpy.context.view_layer.update()
+ positions = h.positions(preview) * 1000
+ expected = np.fromfile(output / f"{name}.positions.f32", dtype="<f4").reshape(-1, 3)
+ maximum = float(np.max(np.linalg.norm(positions - expected, axis=1)))
+ if maximum > .015:
+ raise RuntimeError(f"Editable quad pose library does not reproduce runtime pose {name}: {maximum} mm")
+ library_parity.append(dict(pose=name, maximumMm=maximum))
+ subdivision.show_viewport = True
+ scene.frame_set(1)
+ scene.display.shading.color_type = "MATERIAL"
+ scene.render.engine = "BLENDER_EEVEE"
+ scene.render.resolution_x = 1100
+ scene.render.resolution_y = 1250
+ scene.world.use_nodes = True
+ scene.world.node_tree.nodes["Background"].inputs["Color"].default_value = (.12, .14, .18, 1)
+ scene.world.node_tree.nodes["Background"].inputs["Strength"].default_value = .35
+ for name, location, energy, size in (
+ ("Soft key", (2.5, 3, 3.5), 450, 3),
+ ("Soft fill", (-2, 1.5, 2.5), 250, 3),
+ ("Rim", (0, -2.5, 3), 350, 2),
+ ):
+ data = bpy.data.lights.new(name, "AREA")
+ data.energy = energy
+ data.shape = "DISK"
+ data.size = size
+ light = bpy.data.objects.new(name, data)
+ scene.collection.objects.link(light)
+ light.location = location
+ light.rotation_euler = (Vector((0, 0, 1.1)) - light.location).to_track_quat("-Z", "Y").to_euler()
+ for pose in ("canonical-apose", "seated", "elbow120"):
+ entry = next(item for item in pose_index if item["pose"] == pose)
+ scene.frame_set(entry["frame"])
+ h.render(scene, preview, renders / f"editable--{pose}.png")
+ scene.frame_set(1)
+ scene["authoring_notes"] = "Explicit corrective activations are supplied by the typed pose API; no embedded Python auto-execution. Do not export glTF and silently fall back to LBS."
+ notice = bpy.data.texts.new("ANTONIA-LICENSE.txt")
+ notice.write((ROOT / "fixtures/Canonical/Humanoid/antonia-original-LICENSE.txt").read_text())
+ recipe = bpy.data.texts.new("GAMEPLAY-RECIPE.json")
+ recipe.write((out / "recipe.json").read_text())
+ h.active(preview)
+ rig.select_set(True)
+ bpy.ops.wm.save_as_mainfile(filepath=str(out / "antonia-gameplay.blend"))
+ h.write(out / "blender-evidence.json", dict(
+ schema="antonia.gameplay-blender-replay.v1", cases=records,
+ editableQuads=len(preview.data.polygons), runtimeTriangles=len(triangles),
+ editablePoseLibraryParity=library_parity,
+ uvLoops=len(preview.data.uv_layers.active.data),
+ proprietaryPayloadsEmbedded=False,
+ ))
+ print("ANTONIA_GAMEPLAY_BLENDER_REPLAY_COMPLETE", out, flush=True)
+
+
+def verify_saved(out):
+ path = out / "antonia-gameplay.blend"
+ bpy.ops.wm.open_mainfile(filepath=str(path), use_scripts=False)
+ body = bpy.data.objects["ANTONIA_EDITABLE_QUADS"]
+ subdivision = next(modifier for modifier in body.modifiers if modifier.type == "SUBSURF")
+ subdivision.show_viewport = False
+ entries = h.read(out / "pose-library.json")
+ reports = []
+ for name in ("canonical-apose", "hip90", "seated", "elbow120", "squat",
+ "left-hip-holdout-80", "walking-bilateral", "aim-two-handed"):
+ entry = next(item for item in entries if item["pose"] == name)
+ bpy.context.scene.frame_set(entry["frame"])
+ bpy.context.view_layer.update()
+ positions = h.positions(body) * 1000
+ expected = np.fromfile(out / "blender" / f"{name}.positions.f32", dtype="<f4").reshape(-1, 3)
+ maximum = float(np.max(np.linalg.norm(positions - expected, axis=1)))
+ if maximum > .015:
+ raise RuntimeError(f"Saved Blender pose does not reproduce {name}: {maximum} mm")
+ reports.append(dict(pose=name, maximumMm=maximum))
+ h.write(out / "saved-blend-evidence.json", dict(
+ accepted=True, blendSha256=h.sha(path), cases=reports,
+ embeddedScriptExecution=False, vertices=len(body.data.vertices),
+ quads=len(body.data.polygons), uvLoops=len(body.data.uv_layers.active.data),
+ ))
+ print("ANTONIA_SAVED_BLEND_VERIFIED", len(reports), "poses", flush=True)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--out", default=str(ROOT / "artifacts/local/humanoid-production"))
+ parser.add_argument("--phase", choices=("inputs", "replay", "verify"), required=True)
+ args = parser.parse_args(sys.argv[sys.argv.index("--") + 1:])
+ directory = study.output_path(args.out)
+ if args.phase == "inputs":
+ inputs(directory)
+ elif args.phase == "replay":
+ replay(directory)
+ else:
+ verify_saved(directory)
diff --git a/scripts/humanoid-production-study.py b/scripts/humanoid-production-study.py
new file mode 100644
index 00000000..3ec62659
--- /dev/null
+++ b/scripts/humanoid-production-study.py
@@ -0,0 +1,320 @@
+"""Reproducible Antonia deformation experiments. No proprietary source transfer."""
+
+import argparse
+import importlib
+import json
+from pathlib import Path
+import sys
+import time
+
+import bpy
+import numpy as np
+
+sys.path.insert(0, str(Path(__file__).parent))
+rest_study = importlib.import_module("humanoid-rest-x2")
+helpers = rest_study.h
+metrics = rest_study.x1
+ROOT = helpers.ROOT
+
+
+def output_path(value):
+ path = Path(value).resolve()
+ if not path.is_relative_to((ROOT / "artifacts/local").resolve()):
+ raise ValueError("Generated humanoid output must stay in artifacts/local.")
+ path.mkdir(parents=True, exist_ok=True)
+ return path
+
+
+def setup():
+ candidate, surface, artifact, evidence, vertices = rest_study.normalized_inputs()
+ rig, body, rest, triangles, scene = rest_study.make_open_scene(
+ surface, artifact, vertices
+ )
+ field = rest_study.portable_field(
+ ROOT / "artifacts/local/humanoid-rest-x2/selected-weights.json"
+ )
+ helpers.assign(body, field)
+ mapping = rest_study.role_map(rig)
+ return surface, rig, body, rest, triangles, scene, field, mapping
+
+
+def corpus():
+ cases = rest_study.canonical_corpus()
+ for side in ("Left", "Right"):
+ for angle in (55, 80, 100):
+ cases.append(dict(
+ name=f"{side.lower()}-hip-holdout-{angle}",
+ requested=[dict(joint=side + "Hip", flexionDegrees=angle)],
+ ))
+ for angle in (65, 110):
+ cases.append(dict(
+ name=f"{side.lower()}-knee-holdout-{angle}",
+ requested=[dict(joint=side + "Knee", flexionDegrees=angle)],
+ ))
+ cases.append(dict(name="seated", requested=[
+ dict(joint="LeftHip", flexionDegrees=90),
+ dict(joint="RightHip", flexionDegrees=90),
+ dict(joint="LeftKnee", flexionDegrees=90),
+ dict(joint="RightKnee", flexionDegrees=90),
+ ]))
+ cases.append(dict(name="squat", requested=[
+ dict(joint="LeftHip", flexionDegrees=80, abductionDegrees=15),
+ dict(joint="RightHip", flexionDegrees=80, abductionDegrees=15),
+ dict(joint="LeftKnee", flexionDegrees=110),
+ dict(joint="RightKnee", flexionDegrees=110),
+ ]))
+ return cases
+
+
+def smoothstep(value):
+ t = max(0.0, min(1.0, value))
+ return t * t * (3 - 2 * t)
+
+
+def symmetric_weights(field, surface):
+ result = [dict(row) for row in field]
+ def mirror(name):
+ if name.startswith("Left"):
+ return "Right" + name[4:]
+ if name.startswith("Right"):
+ return "Left" + name[5:]
+ return name
+ for index, vertex in enumerate(surface["vertices"]):
+ partner = vertex.get("symmetryPartnerIndex")
+ if partner is None or partner < index:
+ continue
+ reflected = {mirror(name): weight for name, weight in field[partner].items()}
+ names = sorted(set(field[index]) | set(reflected))
+ averaged = {name: .5 * (field[index].get(name, 0) + reflected.get(name, 0))
+ for name in names}
+ result[index] = averaged
+ result[partner] = {mirror(name): weight for name, weight in averaged.items()}
+ return rest_study.normalize(result)
+
+
+def anatomical_weights(field, surface, rest, rig, hip_strength, hinge_width,
+ anterior_strength=0, anterior_width=.12, elbow_width=0):
+ result = symmetric_weights(field, surface)
+ hip_height = rig.data.bones["LeftHip"].head_local.z
+ for index, (point, row) in enumerate(zip(rest, result)):
+ center_factor = 1 - smoothstep(abs(point[0]) / .095)
+ height_factor = np.exp(-((point[2] - (hip_height - .065)) / .12) ** 4)
+ anterior = anterior_strength * smoothstep((point[1] + .045) / .10)
+ anterior *= smoothstep((point[2] - (hip_height - .025)) / anterior_width)
+ anchor = 1 - (1 - hip_strength * center_factor * height_factor) * (1 - anterior)
+ transferred = 0.0
+ for name in ("LeftHip", "RightHip"):
+ amount = row.get(name, 0) * anchor
+ row[name] = row.get(name, 0) - amount
+ transferred += amount
+ row["Pelvis"] = row.get("Pelvis", 0) + transferred
+ joints = [(side + "Knee", side + "Hip", side + "Ankle", hinge_width)
+ for side in ("Left", "Right")]
+ if elbow_width > 0:
+ joints.extend((side + "Elbow", side + "Shoulder", side + "Wrist", elbow_width)
+ for side in ("Left", "Right"))
+ for joint, parent, distal_joint, width in joints:
+ center = np.array(rig.data.bones[joint].head_local)
+ distal = np.array(rig.data.bones[distal_joint].head_local)
+ direction = (distal - center) / np.linalg.norm(distal - center)
+ longitudinal = float(np.dot(point - center, direction))
+ pair = row.get(joint, 0) + row.get(parent, 0)
+ distance = np.linalg.norm(point - center)
+ if pair < .5 or distance > .25:
+ continue
+ replacement = smoothstep((longitudinal + width) / (2 * width))
+ fade = 1 - smoothstep((distance - .15) / .10)
+ current = row.get(joint, 0) / pair
+ child = current + fade * (replacement - current)
+ row[joint] = pair * child
+ row[parent] = pair * (1 - child)
+ result[index] = row
+ return rest_study.normalize(result)
+
+
+def smooth_modifier(body, rig, rest, iterations, factor, scale):
+ centers = [np.array(rig.data.bones[side + kind].head_local)
+ for side in ("Left", "Right")
+ for kind in ("Hip", "Knee", "Shoulder", "Elbow")]
+ radii = [.22, .13, .18, .12] * 2
+ influence = np.zeros(len(rest))
+ for center, radius in zip(centers, radii):
+ distance = np.linalg.norm(rest - center, axis=1) / radius
+ influence = np.maximum(influence, np.clip(1 - distance ** 2, 0, 1) ** 2)
+ group = body.vertex_groups.new(name="REST_AWARE_JOINT_FINISH")
+ for index, value in enumerate(influence):
+ if value > 1e-6:
+ group.add([index], float(value), "REPLACE")
+ modifier = body.modifiers.new("Rest-aware joint correction", "CORRECTIVE_SMOOTH")
+ modifier.vertex_group = group.name
+ modifier.factor = factor
+ modifier.iterations = iterations
+ modifier.scale = scale
+ modifier.smooth_type = "LENGTH_WEIGHTED"
+ modifier.use_pin_boundary = True
+ modifier.rest_source = "ORCO"
+ return modifier
+
+
+def run(args):
+ out = output_path(args.out)
+ surface, rig, body, rest, triangles, scene, field, mapping = setup()
+ cases = corpus()
+ armature = next(mod for mod in body.modifiers if mod.type == "ARMATURE")
+ corrective_specs = {}
+ trials = [("baseline-lbs", False, None, field), ("volume-dqs", True, None, field)]
+ if args.phase == "selected":
+ edited = anatomical_weights(field, surface, rest, rig, .5, .16)
+ trials.append(("selected-anatomical-dqs", True, None, edited))
+ elif args.phase == "elbow":
+ for width in (.06, .08, .10, .12, .14):
+ edited = anatomical_weights(field, surface, rest, rig, .45, .16, elbow_width=width)
+ trials.append((f"dqs-elbow-{width}", True, None, edited))
+ cases = [case for case in cases if case["name"] in (
+ "elbow45", "elbow90", "elbow120", "reach", "shoulder120"
+ )]
+ elif args.phase in ("corrective", "corrective2", "corrective3", "corrective4"):
+ edited = anatomical_weights(field, surface, rest, rig, .45, .16)
+ trials.append(("anatomical-reference", True, None, edited))
+ fronts = (-.02, -.01, .01, .02, .03)
+ ups = (-.01, 0, .01)
+ if args.phase == "corrective2":
+ fronts = (-.03, -.02, -.01, 0, .01)
+ ups = (-.015, -.02, -.03)
+ if args.phase == "corrective3":
+ fronts = (-.005, -.01, -.015)
+ ups = (-.017, -.019, -.021)
+ if args.phase == "corrective4":
+ fronts = (-.01, -.02)
+ ups = (-.02, -.025)
+ for front in fronts:
+ for up in ups:
+ radii = (1.0,)
+ if args.phase == "corrective3":
+ radii = (1.0, 1.25)
+ if args.phase == "corrective4":
+ radii = (1.5, 1.75)
+ for radius in radii:
+ name = f"hip-corrective-{front}-{up}-{radius}"
+ trials.append((name, True, None, edited))
+ corrective_specs[name] = (front, up, radius)
+ cases = [case for case in cases if case["name"] in (
+ "hip70", "hip90", "seated", "squat", "left-hip-holdout-100", "abduction45"
+ )]
+ elif args.phase == "hip-smooth":
+ edited = anatomical_weights(field, surface, rest, rig, .45, .16)
+ centers = [np.array(rig.data.bones[side + "Hip"].head_local)
+ for side in ("Left", "Right")]
+ mask = np.minimum(*[np.linalg.norm(rest - center, axis=1)
+ for center in centers]) < .22
+ for iterations in (1, 3, 6, 12, 24):
+ smoothed = metrics.local_smooth(body, edited, mask, iterations, .5)
+ smoothed = symmetric_weights(smoothed, surface)
+ trials.append((f"dqs-hip-field-smooth-{iterations}", True, None, smoothed))
+ cases = [case for case in cases if case["name"] in (
+ "hip70", "hip90", "seated", "squat", "left-hip-holdout-100", "abduction45"
+ )]
+ elif args.phase == "fascia":
+ for strength in (.35, .65, 1.0):
+ for width in (.08, .12, .16):
+ edited = anatomical_weights(field, surface, rest, rig, .45, .16, strength, width)
+ trials.append((f"dqs-fascia-{strength}-{width}", True, None, edited))
+ cases = [case for case in cases if case["name"] in (
+ "hip70", "hip90", "seated", "squat", "left-hip-holdout-100", "abduction45"
+ )]
+ elif args.phase == "hip":
+ for strength in (.15, .25, .35, .45, .55, .65):
+ edited = anatomical_weights(field, surface, rest, rig, strength, .16)
+ trials.append((f"dqs-pelvis-{strength}", True, None, edited))
+ cases = [case for case in cases if case["name"] in (
+ "hip70", "hip90", "seated", "squat", "left-hip-holdout-100", "abduction45"
+ )]
+ elif args.phase == "smoothing":
+ for volume in (False, True):
+ for iterations in (5, 15, 30):
+ name = f"{'dqs' if volume else 'lbs'}-rest-smooth-{iterations}"
+ trials.append((name, volume, (iterations, 1.0, 1.0), field))
+ else:
+ for strength in (.5, 1.0):
+ for width in (.08, .12, .16):
+ edited = anatomical_weights(field, surface, rest, rig, strength, width)
+ for volume in (False, True):
+ name = f"{'dqs' if volume else 'lbs'}-anatomy-{strength}-{width}"
+ trials.append((name, volume, None, edited))
+ cases = [case for case in cases if case["name"] in (
+ "canonical-apose", "hip70", "hip90", "knee90", "seated", "squat",
+ "left-hip-holdout-100", "left-knee-holdout-110", "abduction45",
+ )]
+ records = []
+ for name, volume, smoothing, trial_field in trials:
+ started = time.perf_counter()
+ armature.use_deform_preserve_volume = volume
+ helpers.assign(body, trial_field)
+ modifier = None
+ if smoothing:
+ modifier = smooth_modifier(body, rig, rest, *smoothing)
+ result = []
+ for case in cases:
+ residuals = rest_study.apply_semantic(rig, mapping, case["requested"])
+ sculpted = rest.copy()
+ if name in corrective_specs:
+ front, up, radius = corrective_specs[name]
+ for side in ("Left", "Right"):
+ request = next((r for r in case["requested"]
+ if r["joint"] == side + "Hip"), {})
+ activation = smoothstep((request.get("flexionDegrees", 0) - 30) / 60)
+ sign = -1 if side == "Left" else 1
+ center = np.array((sign * .09, .065,
+ rig.data.bones[side + "Hip"].head_local.z + .035))
+ distance = (rest - center) / (np.array((.09, .075, .085)) * radius)
+ influence = np.exp(-np.sum(distance ** 2, axis=1) * 2)
+ sculpted[:, 1] += front * activation * influence
+ sculpted[:, 2] += up * activation * influence
+ body.data.vertices.foreach_set("co", sculpted.reshape(-1))
+ body.data.update()
+ bpy.context.view_layer.update()
+ posed = helpers.positions(body)
+ measured = metrics.measure(
+ rest, posed, triangles,
+ helpers.normal_transport(rig, trial_field, triangles), True,
+ )
+ result.append(dict(
+ pose=case["name"], requested=case["requested"], metrics=measured,
+ maximumSemanticResidualDegrees=max(
+ [r["maximumAbsoluteDegrees"] for r in residuals] or [0]
+ ),
+ ))
+ if args.render and case["name"] in (
+ "canonical-apose", "hip90", "knee90", "shoulder120", "seated", "squat"
+ ):
+ helpers.render(scene, body, out / f"{name}--{case['name']}.png")
+ rest_study.apply_semantic(rig, mapping, [])
+ body.data.vertices.foreach_set("co", rest.reshape(-1))
+ body.data.update()
+ record = dict(name=name, cases=result, seconds=time.perf_counter() - started)
+ records.append(record)
+ helpers.write(out / "trials.json", dict(
+ schema="aetheris.humanoid.production-study.v1",
+ blender=bpy.app.version_string,
+ baselineWeightsSha256=helpers.sha(
+ ROOT / "artifacts/local/humanoid-rest-x2/selected-weights.json"
+ ),
+ trials=records,
+ ))
+ print(name, [(case["pose"], round(case["metrics"]["max"], 3),
+ case["metrics"]["reversalCount"])
+ for case in result if case["pose"] in ("hip90", "knee90", "seated", "squat")],
+ flush=True)
+ if modifier:
+ group = body.vertex_groups.get(modifier.vertex_group)
+ body.modifiers.remove(modifier)
+ body.vertex_groups.remove(group)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--out", default=str(ROOT / "artifacts/local/humanoid-production-study"))
+ parser.add_argument("--render", action="store_true")
+ parser.add_argument("--phase", choices=("smoothing", "weights", "selected", "hip", "fascia", "hip-smooth", "corrective", "corrective2", "corrective3", "corrective4", "elbow"), default="smoothing")
+ arguments = sys.argv[sys.argv.index("--") + 1:]
+ run(parser.parse_args(arguments))
diff --git a/scripts/qualify-antonia-gameplay.ps1 b/scripts/qualify-antonia-gameplay.ps1
new file mode 100644
index 00000000..72257601
--- /dev/null
+++ b/scripts/qualify-antonia-gameplay.ps1
@@ -0,0 +1,53 @@
+param(
+ [string]$Blender = "C:\Program Files\Blender Foundation\Blender 5.2\blender.exe",
+ [switch]$SkipFullTests
+)
+
+$ErrorActionPreference = "Stop"
+$repoRoot = Split-Path -Parent $PSScriptRoot
+Push-Location $repoRoot
+try {
+ $bundle = "artifacts/local/humanoid-production"
+ $candidate = "artifacts/local/humanoid-x1/antonia-adoption-candidate.json"
+ $rig = "fixtures/Canonical/Humanoid/antonia-reference-skeleton-v1.json"
+ $sourceWeights = "artifacts/local/humanoid-rerig-x1/golden-weights.json"
+ $required = @(
+ $Blender, $candidate, $rig, $sourceWeights,
+ "artifacts/local/humanoid-rest-x1/canonical-apose.obj",
+ "artifacts/local/humanoid-rest-x1/evidence.json",
+ "artifacts/local/humanoid-rest-x2/selected-weights.json",
+ "artifacts/local/humanoid-x1/source/Antonia-1.2.obj"
+ )
+ foreach ($path in $required) {
+ if (-not (Test-Path -LiteralPath $path)) {
+ throw "Missing retained input: $path. Reproduce the documented X1/RERIG/REST-X2 source pipeline first. No downloads are performed by this script."
+ }
+ }
+ function Invoke-Checked([string]$Executable, [string[]]$Arguments) {
+ & $Executable @Arguments
+ if ($LASTEXITCODE -ne 0) {
+ throw "Command failed ($LASTEXITCODE): $Executable $($Arguments -join ' ')"
+ }
+ }
+ if (-not $SkipFullTests) {
+ Invoke-Checked "dotnet" @("build", "Aetheris.slnx", "-c", "Release", "-m:1")
+ Invoke-Checked "dotnet" @("test", "Aetheris.slnx", "-c", "Release", "--no-build", "-m:1",
+ "--", "RunConfiguration.MaxCpuCount=1")
+ }
+ $blenderArguments = @("--background", "--factory-startup", "--disable-autoexec",
+ "--python-exit-code", "1", "--python", "scripts/build-antonia-gameplay.py", "--")
+ Invoke-Checked $Blender ($blenderArguments + @("--phase", "inputs"))
+ $qualificationArguments = @("run", "--project", "tools/Aetheris.Humanoid.X0", "-c", "Release", "--",
+ "qualify-gameplay-body", "--input", $candidate, "--rig", $rig, "--source-weights", $sourceWeights,
+ "--bundle", $bundle)
+ Invoke-Checked "dotnet" ($qualificationArguments + @("--seed"))
+ Invoke-Checked $Blender ($blenderArguments + @("--phase", "replay"))
+ Invoke-Checked $Blender ($blenderArguments + @("--phase", "verify"))
+ Invoke-Checked "dotnet" $qualificationArguments
+ Copy-Item -LiteralPath "fixtures/Canonical/Humanoid/antonia-original-LICENSE.txt" -Destination "$bundle/ANTONIA-LICENSE.txt"
+ Copy-Item -LiteralPath "docs/public/humanoid-gameplay-body.md" -Destination "$bundle/README.md"
+ Write-Output "ANTONIA_GAMEPLAY_QUALIFIED $bundle"
+}
+finally {
+ Pop-Location
+}
diff --git a/scripts/render-antonia-gameplay-comparison.py b/scripts/render-antonia-gameplay-comparison.py
new file mode 100644
index 00000000..f16359ae
--- /dev/null
+++ b/scripts/render-antonia-gameplay-comparison.py
@@ -0,0 +1,70 @@
+"""Neutral before/after and retained local Genesis reference renders.
+
+The reference is rendered separately and is never saved into the open character asset.
+Its fixed neutral scale is reused for every pose; posed silhouettes are not rescaled.
+"""
+
+import importlib
+from pathlib import Path
+import sys
+
+import bpy
+import numpy as np
+from mathutils import Quaternion
+
+sys.path.insert(0, str(Path(__file__).parent))
+build = importlib.import_module("build-antonia-gameplay")
+h = build.h
+ROOT = build.ROOT
+
+
+def read_reference(path):
+ vertices = []
+ faces = []
+ for line in path.read_text(encoding="utf-8-sig").splitlines():
+ if line.startswith("v "):
+ x, y, z = map(float, line.split()[1:4])
+ vertices.append((-x, z, y))
+ elif line.startswith("f "):
+ faces.append(tuple(int(value.split("/")[0]) - 1 for value in line.split()[1:]))
+ return np.asarray(vertices), faces
+
+
+def main():
+ out = build.study.output_path(ROOT / "artifacts/local/humanoid-production/comparison")
+ surface, rig, body, rest, triangles, scene, field, mapping = build.study.setup()
+ h.assign(body, field)
+ transforms = {case["name"]: case for case in h.read(out.parent / "pose-transforms.json")}
+ poses = ("hip90", "knee90", "elbow120", "shoulder120")
+ for pose in poses:
+ build.rest_study.apply_semantic(rig, mapping, [])
+ for rotation in transforms[pose]["localRotations"]:
+ rig.pose.bones[rotation["joint"]].rotation_quaternion = Quaternion(
+ (rotation["w"], rotation["x"], rotation["y"], rotation["z"]))
+ bpy.context.view_layer.update()
+ h.render(scene, body, out / f"before--{pose}.png")
+ reference_dir = ROOT / "artifacts/local/humanoid-rest-x2/genesis-local"
+ neutral, neutral_faces = read_reference(reference_dir / "canonical-apose.obj")
+ scale = 1.75 / np.ptp(neutral[:, 2])
+ offset = np.array(((neutral[:, 0].min() + neutral[:, 0].max()) / 2,
+ (neutral[:, 1].min() + neutral[:, 1].max()) / 2,
+ neutral[:, 2].min()))
+ for pose in poses:
+ points, faces = read_reference(reference_dir / f"{pose}.obj")
+ points = (points - offset) * scale
+ reference = h.mesh("Local Genesis reference " + pose, points, faces,
+ h.collection("LOCAL_REFERENCE_ONLY"))
+ h.render(scene, reference, out / f"genesis--{pose}.png")
+ bpy.data.objects.remove(reference, do_unlink=True)
+ h.write(out / "reference-evidence.json", dict(
+ role="Retained local Genesis 9 visual reference; no geometry, weights or deltas transferred",
+ sourceNeutralSha256=h.sha(reference_dir / "canonical-apose.obj"),
+ referencePoses={pose: h.sha(reference_dir / f"{pose}.obj") for pose in poses},
+ fixedRestScaleToMetres=scale,
+ hip90Exception="Retained Genesis request reaches 87.519 degrees; this column is not numerical pose parity",
+ proprietaryPayloadEmbedded=False,
+ ))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/tune-antonia-shoulder.py b/scripts/tune-antonia-shoulder.py
new file mode 100644
index 00000000..87dddec5
--- /dev/null
+++ b/scripts/tune-antonia-shoulder.py
@@ -0,0 +1,50 @@
+"""Bounded shoulder weight finish against the real Aetheris pose replay."""
+
+import importlib
+from pathlib import Path
+import sys
+
+import bpy
+from mathutils import Quaternion
+
+sys.path.insert(0, str(Path(__file__).parent))
+build = importlib.import_module("build-antonia-gameplay")
+study = build.study
+h = build.h
+ROOT = build.ROOT
+
+
+def main():
+ out = study.output_path(ROOT / "artifacts/local/humanoid-production-shoulder")
+ surface, rig, body, rest, triangles, scene, field, mapping = study.setup()
+ selected = study.anatomical_weights(
+ field, surface, rest, rig, .45, .16, elbow_width=.10)
+ body.modifiers[0].use_deform_preserve_volume = True
+ transforms = h.read(ROOT / "artifacts/local/humanoid-production/pose-transforms.json")
+ cases = [case for case in transforms if case["name"] in (
+ "aim-two-handed", "shoulder120", "reach", "walking-bilateral",
+ "left-shoulder-flex-60", "left-shoulder-low-0",
+ )]
+ results = []
+ for gain in (.8, .9, .95, 1.0, 1.05, 1.1, 1.2):
+ edited = study.metrics.brush_gain(selected, rest, rig, "Shoulder", .16, gain)
+ edited = study.symmetric_weights(edited, surface)
+ h.assign(body, edited)
+ reports = []
+ for case in cases:
+ study.rest_study.apply_semantic(rig, mapping, [])
+ for rotation in case["localRotations"]:
+ rig.pose.bones[rotation["joint"]].rotation_quaternion = Quaternion(
+ (rotation["w"], rotation["x"], rotation["y"], rotation["z"]))
+ bpy.context.view_layer.update()
+ measured = study.metrics.measure(rest, h.positions(body), triangles,
+ h.normal_transport(rig, edited, triangles))
+ reports.append(dict(pose=case["name"], metrics=measured))
+ results.append(dict(gain=gain, cases=reports))
+ print(gain, [(case["pose"], round(case["metrics"]["max"], 3),
+ case["metrics"]["reversalCount"]) for case in reports], flush=True)
+ h.write(out / "trials.json", results)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/Aetheris.Humanoid.X0/GameplayBodyQualification.cs b/tools/Aetheris.Humanoid.X0/GameplayBodyQualification.cs
new file mode 100644
index 00000000..26b45b45
--- /dev/null
+++ b/tools/Aetheris.Humanoid.X0/GameplayBodyQualification.cs
@@ -0,0 +1,138 @@
+using System.Buffers.Binary;
+using System.Security.Cryptography;
+using System.Text.Json;
+using System.Text;
+using Aetheris.Humanoid;
+
+internal static class GameplayBodyQualification
+{
+ public static int Run(string input, string rig, string sourceWeights, string bundle, bool seed)
+ {
+ Directory.CreateDirectory(bundle);
+ File.WriteAllText(Path.Combine(bundle, "runtime-evidence.json"),
+ JsonSerializer.Serialize(new { accepted = false, stage = "preparing" }, HumanoidArtifactIO.JsonOptions));
+ var candidate = JsonSerializer.Deserialize<AntoniaAdoptionCandidate>(
+ File.ReadAllText(input), HumanoidArtifactIO.JsonOptions)
+ ?? throw new InvalidDataException("Missing Antonia candidate.");
+ var adoption = AntoniaReferenceRigAdapter.Adopt(candidate, rig);
+ var source = RestPoseQualification.ImportWeights(adoption.Surface, adoption.Skeleton, rig, sourceWeights);
+ var normalized = HumanoidRestPoseNormalizer.Normalize(source, adoption.Skeleton);
+ using var weightMetadata = JsonDocument.Parse(File.ReadAllText(Path.Combine(bundle, "weights.json")));
+ if (weightMetadata.RootElement.GetProperty("skinning").GetString() != "dual-quaternion" ||
+ weightMetadata.RootElement.GetProperty("restPoseId").GetString() != normalized.Skeleton.RestPoseId)
+ {
+ throw new InvalidDataException("Gameplay weights require the exact normalized rest and dual-quaternion convention.");
+ }
+ var surface = RestPoseQualification.ImportWeights(normalized.Surface, normalized.Skeleton,
+ rig, Path.Combine(bundle, "weights.json"));
+ var correctives = JsonSerializer.Deserialize<HumanoidPoseCorrective[]>(
+ File.ReadAllText(Path.Combine(bundle, "correctives.json")), HumanoidArtifactIO.JsonOptions)
+ ?? throw new InvalidDataException("Missing corrective bank.");
+ var corpus = JsonSerializer.Deserialize<GameplayPoseCase[]>(
+ File.ReadAllText(Path.Combine(bundle, "pose-corpus.json")), HumanoidArtifactIO.JsonOptions)
+ ?? throw new InvalidDataException("Missing pose corpus.");
+ var recipeIdentity = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(string.Join("\n",
+ new[] { input, rig, sourceWeights, Path.Combine(bundle, "weights.json"),
+ Path.Combine(bundle, "correctives.json") }.Select(path =>
+ Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(path))))))));
+ var provenance = candidate.Provenance with
+ {
+ GeneratorVersion = "antonia.gameplay-body.v1",
+ ConfigHash = recipeIdentity,
+ OutputHash = recipeIdentity,
+ AdmissionStatus = "Gameplay development candidate; separate pose qualification; no canonical promotion",
+ Transformations = candidate.Provenance.Transformations.Concat(
+ [
+ "Canonical A-pose normalization, bilateral weights, smooth hinge transitions and central pelvis retention",
+ "Retained dual-quaternion binding and two authored pre-skin hip flexion shapes",
+ ]).ToArray(),
+ };
+ var artifact = new HumanoidGameplayBodyArtifact(HumanoidGameplayBody.Schema,
+ "antonia.gameplay-candidate.v1", surface, normalized.Skeleton, correctives, provenance);
+ var assetPath = Path.Combine(bundle, "antonia.gameplay-body.json");
+ HumanoidGameplayBody.Save(artifact, assetPath);
+ var body = HumanoidGameplayBody.Load(assetPath);
+ var reports = new List<GameplayPoseReport>();
+ var transforms = new List<object>();
+ foreach (var item in corpus)
+ {
+ var solved = body.Solve(item.Name, item.Requested);
+ if (!solved.IsSolved)
+ {
+ throw new InvalidDataException(item.Name + ": " + string.Join("; ", solved.Diagnostics));
+ }
+ var pose = solved.Pose!;
+ var evaluated = body.Evaluate(pose);
+ var parityPath = Path.Combine(bundle, "blender", item.Name + ".positions.f32");
+ double? parityMm = null;
+ if (!seed)
+ {
+ var data = File.ReadAllBytes(parityPath);
+ if (data.Length != evaluated.Positions.Count * 12)
+ {
+ throw new InvalidDataException("Blender parity vertex count mismatch: " + item.Name);
+ }
+ parityMm = 0;
+ for (var index = 0; index < evaluated.Positions.Count; index++)
+ {
+ var offset = index * 12;
+ var x = BinaryPrimitives.ReadSingleLittleEndian(data.AsSpan(offset, 4));
+ var y = BinaryPrimitives.ReadSingleLittleEndian(data.AsSpan(offset + 4, 4));
+ var z = BinaryPrimitives.ReadSingleLittleEndian(data.AsSpan(offset + 8, 4));
+ var point = evaluated.Positions[index];
+ var distance = Math.Sqrt(Math.Pow(point.X - x, 2) + Math.Pow(point.Y - y, 2) +
+ Math.Pow(point.Z - z, 2));
+ if (!double.IsFinite(distance))
+ {
+ throw new InvalidDataException("Nonfinite Blender parity: " + item.Name);
+ }
+ parityMm = Math.Max(parityMm.Value, distance);
+ }
+ }
+ var report = new GameplayPoseReport(item.Name, item.Role, evaluated.Evidence.IsAdmissible,
+ evaluated.Evidence.Regions.Max(region => region.Maximum),
+ evaluated.Evidence.FlaggedFaceIds.Count, evaluated.Evidence.CollapsedTriangles,
+ pose.SemanticResiduals.Select(residual => residual.MaximumAbsoluteDegrees).DefaultIfEmpty(0).Max(),
+ parityMm, evaluated.Evidence.FlaggedFaceIds.ToArray());
+ reports.Add(report);
+ transforms.Add(new
+ {
+ name = item.Name,
+ localRotations = pose.PoseState.LocalRotations.Select(rotation => new
+ {
+ joint = rotation.Joint.ToString(), x = rotation.LocalRotation.X,
+ y = rotation.LocalRotation.Y, z = rotation.LocalRotation.Z, w = rotation.LocalRotation.W,
+ }),
+ correctives = body.ObserveCorrectives(pose),
+ });
+ }
+ var qualified = reports.Where(report => report.Role != "stress").ToArray();
+ var accepted = !seed && qualified.Length > 0 && qualified.All(report =>
+ report.SurfaceAdmissible && report.SemanticMaximumDegrees <= .05 && report.ParityMaximumMm <= .015);
+ var summary = new
+ {
+ schema = "aetheris.humanoid.gameplay-qualification.v1",
+ stage = seed ? "seed-for-independent-blender-replay" : "qualification",
+ accepted,
+ assetSha256 = Convert.ToHexStringLower(SHA256.HashData(File.ReadAllBytes(assetPath))),
+ bodyId = body.Id,
+ canonicalPromotion = false,
+ qualifiedCases = qualified.Length,
+ stressCases = reports.Count - qualified.Length,
+ qualifiedMaximumEdgeRatio = qualified.Max(report => report.MaximumEdgeRatio),
+ qualifiedReversals = qualified.Sum(report => report.ReversalFlags),
+ cases = reports,
+ };
+ File.WriteAllText(Path.Combine(bundle, "runtime-evidence.json"),
+ JsonSerializer.Serialize(summary, HumanoidArtifactIO.JsonOptions));
+ File.WriteAllText(Path.Combine(bundle, "pose-transforms.json"),
+ JsonSerializer.Serialize(transforms, HumanoidArtifactIO.JsonOptions));
+ Console.WriteLine(JsonSerializer.Serialize(summary, HumanoidArtifactIO.JsonOptions));
+ return seed || accepted ? 0 : 2;
+ }
+
+ private sealed record GameplayPoseCase(string Name, AnatomicalJointRequest[] Requested, string Role);
+ private sealed record GameplayPoseReport(string Pose, string Role, bool SurfaceAdmissible,
+ double MaximumEdgeRatio, int ReversalFlags, int CollapsedTriangles,
+ double SemanticMaximumDegrees, double? ParityMaximumMm, string[] FlaggedFaceIds);
+}
diff --git a/tools/Aetheris.Humanoid.X0/Program.cs b/tools/Aetheris.Humanoid.X0/Program.cs
index 19633ba5..8aab9f04 100644
--- a/tools/Aetheris.Humanoid.X0/Program.cs
+++ b/tools/Aetheris.Humanoid.X0/Program.cs
@@ -12,6 +12,9 @@ static int Run(string[] args)
{
return args[0] switch
{
+ "qualify-gameplay-body" => GameplayBodyQualification.Run(
+ Required(args, "--input"), Required(args, "--rig"), Required(args, "--source-weights"),
+ Required(args, "--bundle"), args.Contains("--seed")),
"generate"=>Generate(args[1..]),
"adopt-antonia"=>AdoptAntonia(args[1..]),
"constrained-antonia"=>ConstrainedQualification.Run(Required(args, "--input"), Value(args, "--out-dir") ?? Path.Combine("artifacts", "local", "humanoid-x2")),
@@ -116,4 +119,24 @@ static string? Value(string[] args,string name){var i=Array.IndexOf(args,name);r
static string Required(string[] args,string name)=>Value(args,name)??throw new ArgumentException($"Missing {name}.");
static string Kebab(string s)=>string.Concat(s.Select((c,i)=>char.IsUpper(c)&&i>0?"-"+char.ToLowerInvariant(c):char.ToLowerInvariant(c).ToString()));
static int Fail(string message){Console.Error.WriteLine(message);Usage();return 1;}
-static void Usage()=>Console.WriteLine("Aetheris.Humanoid research tooling (X0 synthetic / X1 adoption / X2 constrained / X3 judgment / X4 source comparison / X5 reference rig / REST-X1/X2 normalization)\n qualify-rest-x2 --input <candidate.json> --rig <reference-rig.json> --source-weights <source-rest-weights.json> --weights <A-pose-weights.json> --blender-dir <evidence-dir> [--out-dir <dir>]\n normalize-rest-antonia --input <candidate.json> --rig <reference-rig.json> --weights <weights.json> [--out-dir <dir>]\n golden-weights-antonia --input <candidate.json> --rig <reference-rig.json> --weights <weights.json> --corpus <poses.json> [--out-dir <dir>]\n reference-rig-antonia --input <candidate.json> --rig <reference-rig.json> [--out-dir <dir>]\n compare-source-pose --input <candidate.json> --source-pose <source.json> --output <report.json>\n judge-antonia --input <candidate.json> [--out-dir <dir>]\n constrained-antonia --input <candidate.json> [--out-dir <dir>]\n adopt-antonia --source <Antonia-1.2.obj> --notice <original-README> [--out-dir <dir>]\n generate [--out-dir <dir>]\n inspect --input <canonical.json>\n morph --input <canonical.json> --output <variant.json> [--height <mm>] [--arm-length <delta-mm>] [--leg-length <delta-mm>] [--shoulder-width <delta-mm>]\n pose --input <canonical.json> --output <posed.obj> [--left-elbow-deg <deg>] [--left-shoulder-deg <deg>] [--left-hip-deg <deg>] [--left-knee-deg <deg>]\n sweep --input <canonical.json> --output <evidence.json>");
+static void Usage()
+{
+ Console.WriteLine(
+ """
+ Aetheris.Humanoid research tooling (X0 synthetic / X1 adoption / X2 constrained / X3 judgment / X4 source comparison / X5 reference rig / REST-X1/X2 normalization)
+ qualify-gameplay-body --input <candidate.json> --rig <reference-rig.json> --source-weights <source-rest-weights.json> --bundle <dir> [--seed]
+ qualify-rest-x2 --input <candidate.json> --rig <reference-rig.json> --source-weights <source-rest-weights.json> --weights <A-pose-weights.json> --blender-dir <evidence-dir> [--out-dir <dir>]
+ normalize-rest-antonia --input <candidate.json> --rig <reference-rig.json> --weights <weights.json> [--out-dir <dir>]
+ golden-weights-antonia --input <candidate.json> --rig <reference-rig.json> --weights <weights.json> --corpus <poses.json> [--out-dir <dir>]
+ reference-rig-antonia --input <candidate.json> --rig <reference-rig.json> [--out-dir <dir>]
+ compare-source-pose --input <candidate.json> --source-pose <source.json> --output <report.json>
+ judge-antonia --input <candidate.json> [--out-dir <dir>]
+ constrained-antonia --input <candidate.json> [--out-dir <dir>]
+ adopt-antonia --source <Antonia-1.2.obj> --notice <original-README> [--out-dir <dir>]
+ generate [--out-dir <dir>]
+ inspect --input <canonical.json>
+ morph --input <canonical.json> --output <variant.json> [--height <mm>] [--arm-length <delta-mm>] [--leg-length <delta-mm>] [--shoulder-width <delta-mm>]
+ pose --input <canonical.json> --output <posed.obj> [--left-elbow-deg <deg>] [--left-shoulder-deg <deg>] [--left-hip-deg <deg>] [--left-knee-deg <deg>]
+ sweep --input <canonical.json> --output <evidence.json>
+ """);
+}